{"commit":"75110cd4beded0f39241cc1e74ac2615246dc8e5","subject":"Fix stos special instruction handling","message":"Fix stos special instruction handling\n","repos":"khimru\/ncval_ragel,khimru\/ncval_ragel,khimru\/ncval_ragel","old_file":"validator-x86_64.rl","new_file":"validator-x86_64.rl","new_contents":"\/*\n * Copyright (c) 2011 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"validator-x86_64.h\"\n\n#undef TRUE\n#define TRUE 1\n\n#undef FALSE\n#define FALSE 0\n\n#include \"validator-x86_64-instruction-consts.c\"\n\n#define check_jump_dest \\\n if ((jump_dest & bundle_mask) != bundle_mask) { \\\n if (jump_dest >= size) { \\\n printf(\"direct jump out of range: %zx\\n\", jump_dest); \\\n result = 1; \\\n goto error_detected; \\\n } else { \\\n BitmapSetBit(jump_dests, jump_dest + 1); \\\n } \\\n } \\\n operand0 = JMP_TO; \\\n base = REG_RIP; \\\n index = REG_NONE;\n\n%%{\n machine x86_64_decoder;\n alphtype unsigned char;\n\n action check_access {\n if ((base == REG_RIP) || (base == REG_R15) ||\n\t((base == REG_RSP) && (restricted_register != REG_RSP)) ||\n\t((base == REG_RBP) && (restricted_register != REG_RBP))) {\n if ((index == restricted_register) ||\n\t ((index == REG_RDI) &&\n\t (restricted_register == kSandboxedRsiRestrictedRdi))) {\n\tBitmapClearBit(valid_targets, begin - data);\n } else if ((index != REG_NONE) && (index != REG_RIZ)) {\n\tfprintf(stderr,\"Improper sandboxing in instruction %zx\", begin - data);\n\texit(1);\n }\n } else if ((index == REG_RIP) || (index == REG_R15) ||\n\t ((index == REG_RSP) && (restricted_register != REG_RSP)) ||\n\t ((index == REG_RBP) && (restricted_register != REG_RBP))) {\n if ((base == restricted_register) ||\n\t ((base == REG_RDI) &&\n\t (restricted_register == kSandboxedRsiRestrictedRdi))) {\n\tBitmapClearBit(valid_targets, begin - data);\n } else if ((base != REG_NONE) && (base != REG_RIZ)) {\n\tfprintf(stderr,\"Improper sandboxing in instruction @%zx\", begin - data);\n\texit(1);\n }\n } else {\n fprintf(stderr,\"Improper sandboxing in instruction @%zx\", begin - data);\n }\n }\n\n action rel8_operand {\n int8_t offset = (uint8_t) (p[0]);\n size_t jump_dest = offset + (p - data);\n check_jump_dest;\n }\n action rel16_operand {\n assert(FALSE);\n }\n action rel32_operand {\n int32_t offset =\n\t (uint32_t) (p[-3] + 256U * (p[-2] + 256U * (p[-1] + 256U * (p[0]))));\n size_t jump_dest = offset + (p - data);\n check_jump_dest;\n }\n\n include decode_x86_64 \"validator-x86_64-instruction.rl\";\n\n action process_normal_instruction {\n \/* Restricted %rsp or %rbp must be processed by appropriate nacl-special\n instruction, not with regular instruction. *\/\n if (restricted_register == REG_RSP) {\n printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n exit(1);\n } else if (restricted_register == REG_RBP) {\n printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n exit(1);\n }\n \/* If Sandboxed Rsi is destroyed then we must note that. *\/\n if (restricted_register == kSandboxedRsi) {\n for (i = 0; i < operands_count; ++i) {\n\tif ((operands[i].write == TRUE) &&\n\t (operands[i].name == REG_RSI) &&\n\t ((operands[i].type == OperandSandboxRestricted) ||\n\t (operands[i].type == OperandSandboxUnrestricted))) {\n\t restricted_register = kNoRestrictedReg;\n\t break;\n\t}\n }\n }\n if (restricted_register == kSandboxedRsi) {\n for (i = 0; i < operands_count; ++i) {\n\tif ((operands[i].write == TRUE) &&\n\t (operands[i].name == REG_RDI) &&\n\t (operands[i].type == OperandSandboxRestricted)) {\n\t sandboxed_rsi_restricted_rdi = begin;\n\t restricted_register = kSandboxedRsiRestrictedRdi;\n\t}\n }\n }\n if (restricted_register != kSandboxedRsiRestrictedRdi) {\n restricted_register = kNoRestrictedReg;\n for (i = 0; i < operands_count; ++i) {\n\tif (operands[i].write && operands[i].name <= REG_R15) {\n\t if (operands[i].type == OperandSandboxRestricted) {\n\t if (operands[i].name == REG_R15) {\n\t printf(\"Incorrectly modified register %%r15 at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t } else {\n\t restricted_register = operands[i].name;\n\t }\n\t } else if (operands[i].type == OperandSandboxUnrestricted) {\n\t if (operands[i].name == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t } else if (operands[i].name == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t } else if (operands[i].name == REG_R15) {\n\t printf(\"Incorrectly modified register %%r15 at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t }\n\t } else if (operands[i].type == OperandNoSandboxEffect) {\n\t if (operands[i].name == REG_R15) {\n\t printf(\"Incorrectly modified register %%r15 at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t }\n\t }\n }\n }\n }\n }\n\n # Remove special instructions which are only allowed in special cases.\n normal_instruction = (one_instruction - (\n (0x48 0x89 0xe5)\t\t | # mov %rsp,%rbp\n (0x48 0x89 0xec)\t\t | # mov %rbp,%rsp\n (0x48 0x81 0xe4 any{4})\t | # and $XXX,%rsp\n (0x48 0x83 0xe4 any)\t | # and $XXX,%rsp\n (0x4c 0x01 0xfd)\t\t | # add %r15,%rbp\n (0x49 0x8d 0x2c 0x2f)\t | # lea (%r15,%rbp,1),%rbp\n (0x4a 0x8d 0x6c 0x3d any)\t | # lea 0x0(%rbp,%r15,1),%rbp\n (0x48 0x81 0xe5 any{4})\t | # and $XXX,%rsp\n (0x48 0x83 0xe5 any)\t | # and $XXX,%rsp\n (0x4c 0x01 0xfc)\t\t | # add %r15,%rsp\n (0x4a 0x8d 0x24 0x3c)\t | # lea (%rsp,%r15,1),%rsp\n (0x49 0x8d 0x34 0x37)\t | # lea (%r15,%rsi,1),%rsi\n (0x49 0x8d 0x3c 0x3f)\t # lea (%r15,%rdi,1),%rdi\n )) @process_normal_instruction;\n\n special_instruction =\n (0x48 0x89 0xe5)\t\t\t | # mov %rsp,%rbp\n (0x48 0x81 0xe4 any{3} (0x80 .. 0xff)) | # and $XXX,%rsp\n (0x48 0x83 0xe4 (0x80 .. 0xff))\t # and $XXX,%rsp\n @{ if (restricted_register == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n } |\n (0x48 0x89 0xec)\t\t\t | # mov %rbp,%rsp\n (0x48 0x81 0xe5 any{3} (0x80 .. 0xff)) | # and $XXX,%rsp\n (0x48 0x83 0xe5 (0x80 .. 0xff))\t # and $XXX,%rsp\n @{ if (restricted_register == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n } |\n (0x4c 0x01 0xfd\t | # add %r15,%rbp\n 0x49 0x8d 0x2c 0x2f | # lea (%r15,%rbp,1),%rbp\n 0x4a 0x8d 0x6c 0x3d 0x00)\t # lea 0x0(%rbp,%r15,1),%rbp\n @{ if (restricted_register != REG_RBP) {\n\t printf(\"Incorrectly sandboxed %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n } |\n (0x4c 0x01 0xfc\t | # add %r15,%rsp\n 0x4a 0x8d 0x24 0x3c) # lea (%rsp,%r15,1),%rsp\n @{ if (restricted_register != REG_RSP) {\n\t printf(\"Incorrectly sandboxed %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n } |\n (0x83 0xe0 0xe0 0x4c 0x01 0xf8 0xff (0xd0|0xe0) | # naclcall\/jmp %eax, %r15\n 0x83 0xe1 0xe0 0x4c 0x01 0xf9 0xff (0xd1|0xe1) | # naclcall\/jmp %ecx, %r15\n 0x83 0xe2 0xe0 0x4c 0x01 0xfa 0xff (0xd2|0xe2) | # naclcall\/jmp %edx, %r15\n 0x83 0xe3 0xe0 0x4c 0x01 0xfb 0xff (0xd3|0xe3) | # naclcall\/jmp %ebx, %r15\n 0x83 0xe4 0xe0 0x4c 0x01 0xfc 0xff (0xd4|0xe4) | # naclcall\/jmp %esp, %r15\n 0x83 0xe5 0xe0 0x4c 0x01 0xfd 0xff (0xd5|0xe5) | # naclcall\/jmp %ebp, %r15\n 0x83 0xe6 0xe0 0x4c 0x01 0xfe 0xff (0xd6|0xe6) | # naclcall\/jmp %esi, %r15\n 0x83 0xe7 0xe0 0x4c 0x01 0xff 0xff (0xd7|0xe7)) # naclcall\/jmp %edi, %r15\n @{ if (restricted_register == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n } else if (restricted_register == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n BitmapClearBit(valid_targets, (p - data) - 4);\n BitmapClearBit(valid_targets, (p - data) - 1);\n restricted_register = kNoRestrictedReg;\n } |\n (0x41 0x83 0xe0 0xe0 0x4d 0x01 0xf8 0x41 0xff (0xd0|0xe0) | # naclcall\/jmp\n 0x41 0x83 0xe1 0xe0 0x4d 0x01 0xf9 0x41 0xff (0xd1|0xe1) | # %r8d, %r15\n 0x41 0x83 0xe2 0xe0 0x4d 0x01 0xfa 0x41 0xff (0xd2|0xe2) | # \u22ee\n 0x41 0x83 0xe3 0xe0 0x4d 0x01 0xfb 0x41 0xff (0xd3|0xe3) | # \u22ee\n 0x41 0x83 0xe4 0xe0 0x4d 0x01 0xfc 0x41 0xff (0xd4|0xe4) | # \u22ee\n 0x41 0x83 0xe5 0xe0 0x4d 0x01 0xfd 0x41 0xff (0xd5|0xe5) | # naclcall\/jmp\n 0x41 0x83 0xe6 0xe0 0x4d 0x01 0xfe 0x41 0xff (0xd6|0xe6)) # %r14d, %r15\n @{ if (restricted_register == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n } else if (restricted_register == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n BitmapClearBit(valid_targets, (p - data) - 5);\n BitmapClearBit(valid_targets, (p - data) - 2);\n restricted_register = kNoRestrictedReg;\n } |\n (0x49 0x8d 0x34 0x37) # lea (%r15,%rsi,1),%rsi\n @{ if (restricted_register == REG_RSI) {\n\t sandboxed_rsi = begin;\n\t restricted_register = kSandboxedRsi;\n } else {\n\t restricted_register = kNoRestrictedReg;\n }\n } |\n (0x49 0x8d 0x3c 0x3f) # lea (%r15,%rdi,1),%rdi\n @{ if (restricted_register == REG_RDI) {\n\t sandboxed_rdi = begin;\n\t restricted_register = kSandboxedRdi;\n } else if (restricted_register == kSandboxedRsiRestrictedRdi) {\n\t sandboxed_rdi = begin;\n\t restricted_register = kSandboxedRsiSandboxedRdi;\n } else {\n restricted_register = kNoRestrictedReg;\n }\n } |\n (0xac\t\t | # lods %ds:(%rsi),%al\n (data16|REXW_NONE)? 0xad)\t # lods %ds:(%rsi),%ax\/%eax\/%rax\n @{ if (restricted_register != kSandboxedRsi) {\n\t printf(\"Incorrectly sandboxed %%rdi at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n } |\n (0xae\t\t | # scas %ds:(%rsi),%al\n (data16|REXW_NONE)? 0xaf | # scas %ds:(%rsi),%ax\/%eax\/%rax\n (rep? 0xaa)\t | # stos %al,%es:(%rdi)\n (data16 |\n rep data16 |\n data16 rep) 0xab\t | # stos %ax,%es:(%rdi)\n rep? REXW_NONE? 0xab)\t # stos %eax\/%rax,%es:(%rdi)\n @{ if (restricted_register != kSandboxedRdi &&\n\t restricted_register != kSandboxedRsiSandboxedRdi) {\n\t printf(\"Incorrectly sandboxed %%rdi at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n } |\n (condrep? 0xa6\t | # cmpsb\t %es:(%rdi),%ds:(%rsi)\n (data16 |\n condrep data16 |\n data16 condrep) 0xa7 | # cmpsw\t %es:(%rdi),%ds:(%rsi)\n condrep? REXW_NONE? 0xa7 | # cmps[lq] %es:(%rdi),%ds:(%rsi)\n rep? 0xa4\t\t | # movsb\t %es:(%rdi),%ds:(%rsi)\n (data16 |\n rep data16 |\n data16 rep) 0xa5\t | # movsw\t %es:(%rdi),%ds:(%rsi)\n rep? REXW_NONE? 0xa5)\t# movs[lq] %es:(%rdi),%ds:(%rsi)\n @{ if (restricted_register != kSandboxedRsiSandboxedRdi) {\n\t printf(\"Incorrectly sandboxed %%rsi or %%rdi at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi_restricted_rdi - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n };\n\n main := ((normal_instruction | special_instruction) >{\n\tbegin = p;\n\tBitmapSetBit(valid_targets, p - data);\n\trex_prefix = FALSE;\n\tvex_prefix2 = 0xe0;\n\tvex_prefix3 = 0x00;\n })*\n $!{ process_error(p, userdata);\n\tresult = 1;\n\tgoto error_detected;\n };\n\n}%%\n\n%% write data;\n\n\/* Ignore this information for now. *\/\n#define data16_prefix if (0) result\n#define lock_prefix if (0) result\n#define repz_prefix if (0) result\n#define repnz_prefix if (0) result\n#define branch_not_taken if (0) result\n#define branch_taken if (0) result\n#define imm if (0) begin\n#define imm_operand if (0) result\n#define imm2 if (0) begin\n#define imm2_operand if (0) result\n#define scale if (0) result\n#define disp if (0) begin\n#define disp_type if (0) result\n#define operand0 operands[0].name\n#define operand1 operands[1].name\n#define operand2 operands[2].name\n#define operand3 operands[3].name\n#define operand4 operands[4].name\n#define operand0_type operands[0].type\n#define operand1_type operands[1].type\n#define operand2_type operands[2].type\n#define operand3_type operands[3].type\n#define operand4_type operands[4].type\n\/* It's not important for us. *\/\n#define operand0_read if (0) result\n#define operand1_read if (0) result\n#define operand2_read if (0) result\n#define operand3_read if (0) result\n#define operand4_read if (0) result\n#define operand0_write operands[0].write\n#define operand1_write operands[1].write\n#define operand2_write operands[2].write\n#define operand3_write operands[3].write\n#define operand4_write operands[4].write\n\nenum {\n REX_B = 1,\n REX_X = 2,\n REX_R = 4,\n REX_W = 8\n};\n\nenum disp_mode {\n DISPNONE,\n DISP8,\n DISP16,\n DISP32,\n DISP64,\n};\n\nenum imm_mode {\n IMMNONE,\n IMM2,\n IMM8,\n IMM16,\n IMM32,\n IMM64\n};\n\nstatic const uint8_t one = 1;\n\nstatic const int kBitsPerByte = 8;\n\nstatic inline uint8_t *BitmapAllocate(uint32_t indexes) {\n uint32_t byte_count = (indexes + kBitsPerByte - 1) \/ kBitsPerByte;\n uint8_t *bitmap = malloc(byte_count);\n if (bitmap != NULL) {\n memset(bitmap, 0, byte_count);\n }\n return bitmap;\n}\n\nstatic inline int BitmapIsBitSet(uint8_t *bitmap, uint32_t index) {\n return (bitmap[index \/ kBitsPerByte] & (1 << (index % kBitsPerByte))) != 0;\n}\n\nstatic inline void BitmapSetBit(uint8_t *bitmap, uint32_t index) {\n bitmap[index \/ kBitsPerByte] |= 1 << (index % kBitsPerByte);\n}\n\nstatic inline void BitmapClearBit(uint8_t *bitmap, uint32_t index) {\n bitmap[index \/ kBitsPerByte] &= ~(1 << (index % kBitsPerByte));\n}\n\nint CheckJumpTargets(uint8_t *valid_targets, uint8_t *jump_dests,\n size_t size) {\n size_t i;\n for (i = 0; i < size \/ 32; i++) {\n uint32_t jump_dest_mask = ((uint32_t *) jump_dests)[i];\n uint32_t valid_target_mask = ((uint32_t *) valid_targets)[i];\n if ((jump_dest_mask & ~valid_target_mask) != 0) {\n printf(\"bad jump to around %x\\n\", (unsigned)(i * 32));\n return 1;\n }\n }\n return 0;\n}\n\nint ValidateChunk(const uint8_t *data, size_t size,\n\t\t process_error_func process_error, void *userdata) {\n const size_t bundle_size = 32;\n const size_t bundle_mask = bundle_size - 1;\n\n uint8_t *valid_targets = BitmapAllocate(size);\n uint8_t *jump_dests = BitmapAllocate(size);\n\n const uint8_t *p = data;\n const uint8_t *begin;\n\n uint8_t rex_prefix, vex_prefix2, vex_prefix3;\n struct Operand {\n unsigned int name\t:5;\n unsigned int type\t:2;\n bool\t write\t:1;\n } operands[5];\n enum register_name base, index;\n uint8_t operands_count, i;\n int result = 0;\n \/*\n * These are borders of the appropriate instructions. Initialize them to make\n * compiler happy: they are never used uninitialized even without explicit\n * initialization but GCC is not sophysicated enough to prove that.\n *\/\n const uint8_t *sandboxed_rsi = 0;\n const uint8_t *sandboxed_rsi_restricted_rdi = 0;\n const uint8_t *sandboxed_rdi = 0;\n\n assert(size % bundle_size == 0);\n\n while (p < data + size) {\n const uint8_t *pe = p + bundle_size;\n const uint8_t *eof = pe;\n int cs;\n enum {\n kNoRestrictedReg = 32,\n kSandboxedRsi,\n kSandboxedRdi,\n kSandboxedRsiRestrictedRdi,\n kSandboxedRsiSandboxedRdi\n }; uint8_t restricted_register = kNoRestrictedReg;\n\n %% write init;\n %% write exec;\n\n if (restricted_register == REG_RBP) {\n printf(\"Incorrectly sandboxed %%rbp at the %d%zx\\n\", *data, p - data);\n exit(1);\n } else if (restricted_register == REG_RSP) {\n printf(\"Incorrectly sandboxed %%rbp at the %zx\\n\", p - data);\n exit(1);\n }\n }\n\n if (CheckJumpTargets(valid_targets, jump_dests, size)) {\n result = 1;\n goto error_detected;\n }\n\nerror_detected:\n return result;\n}\n","old_contents":"\/*\n * Copyright (c) 2011 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"validator-x86_64.h\"\n\n#undef TRUE\n#define TRUE 1\n\n#undef FALSE\n#define FALSE 0\n\n#include \"validator-x86_64-instruction-consts.c\"\n\n#define check_jump_dest \\\n if ((jump_dest & bundle_mask) != bundle_mask) { \\\n if (jump_dest >= size) { \\\n printf(\"direct jump out of range: %zx\\n\", jump_dest); \\\n result = 1; \\\n goto error_detected; \\\n } else { \\\n BitmapSetBit(jump_dests, jump_dest + 1); \\\n } \\\n } \\\n operand0 = JMP_TO; \\\n base = REG_RIP; \\\n index = REG_NONE;\n\n%%{\n machine x86_64_decoder;\n alphtype unsigned char;\n\n action check_access {\n if ((base == REG_RIP) || (base == REG_R15) ||\n\t((base == REG_RSP) && (restricted_register != REG_RSP)) ||\n\t((base == REG_RBP) && (restricted_register != REG_RBP))) {\n if ((index == restricted_register) ||\n\t ((index == REG_RDI) &&\n\t (restricted_register == kSandboxedRsiRestrictedRdi))) {\n\tBitmapClearBit(valid_targets, begin - data);\n } else if ((index != REG_NONE) && (index != REG_RIZ)) {\n\tfprintf(stderr,\"Improper sandboxing in instruction %zx\", begin - data);\n\texit(1);\n }\n } else if ((index == REG_RIP) || (index == REG_R15) ||\n\t ((index == REG_RSP) && (restricted_register != REG_RSP)) ||\n\t ((index == REG_RBP) && (restricted_register != REG_RBP))) {\n if ((base == restricted_register) ||\n\t ((base == REG_RDI) &&\n\t (restricted_register == kSandboxedRsiRestrictedRdi))) {\n\tBitmapClearBit(valid_targets, begin - data);\n } else if ((base != REG_NONE) && (base != REG_RIZ)) {\n\tfprintf(stderr,\"Improper sandboxing in instruction @%zx\", begin - data);\n\texit(1);\n }\n } else {\n fprintf(stderr,\"Improper sandboxing in instruction @%zx\", begin - data);\n }\n }\n\n action rel8_operand {\n int8_t offset = (uint8_t) (p[0]);\n size_t jump_dest = offset + (p - data);\n check_jump_dest;\n }\n action rel16_operand {\n assert(FALSE);\n }\n action rel32_operand {\n int32_t offset =\n\t (uint32_t) (p[-3] + 256U * (p[-2] + 256U * (p[-1] + 256U * (p[0]))));\n size_t jump_dest = offset + (p - data);\n check_jump_dest;\n }\n\n include decode_x86_64 \"validator-x86_64-instruction.rl\";\n\n action process_normal_instruction {\n \/* Restricted %rsp or %rbp must be processed by appropriate nacl-special\n instruction, not with regular instruction. *\/\n if (restricted_register == REG_RSP) {\n printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n exit(1);\n } else if (restricted_register == REG_RBP) {\n printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n exit(1);\n }\n \/* If Sandboxed Rsi is destroyed then we must note that. *\/\n if (restricted_register == kSandboxedRsi) {\n for (i = 0; i < operands_count; ++i) {\n\tif ((operands[i].write == TRUE) &&\n\t (operands[i].name == REG_RSI) &&\n\t ((operands[i].type == OperandSandboxRestricted) ||\n\t (operands[i].type == OperandSandboxUnrestricted))) {\n\t restricted_register = kNoRestrictedReg;\n\t break;\n\t}\n }\n }\n if (restricted_register == kSandboxedRsi) {\n for (i = 0; i < operands_count; ++i) {\n\tif ((operands[i].write == TRUE) &&\n\t (operands[i].name == REG_RDI) &&\n\t (operands[i].type == OperandSandboxRestricted)) {\n\t sandboxed_rsi_restricted_rdi = begin;\n\t restricted_register = kSandboxedRsiRestrictedRdi;\n\t}\n }\n }\n if (restricted_register != kSandboxedRsiRestrictedRdi) {\n restricted_register = kNoRestrictedReg;\n for (i = 0; i < operands_count; ++i) {\n\tif (operands[i].write && operands[i].name <= REG_R15) {\n\t if (operands[i].type == OperandSandboxRestricted) {\n\t if (operands[i].name == REG_R15) {\n\t printf(\"Incorrectly modified register %%r15 at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t } else {\n\t restricted_register = operands[i].name;\n\t }\n\t } else if (operands[i].type == OperandSandboxUnrestricted) {\n\t if (operands[i].name == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t } else if (operands[i].name == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t } else if (operands[i].name == REG_R15) {\n\t printf(\"Incorrectly modified register %%r15 at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t }\n\t } else if (operands[i].type == OperandNoSandboxEffect) {\n\t if (operands[i].name == REG_R15) {\n\t printf(\"Incorrectly modified register %%r15 at the %zx\\n\",\n\t\t\t\t\t\t\t\t p - data);\n\t exit(1);\n\t }\n\t }\n }\n }\n }\n }\n\n # Remove special instructions which are only allowed in special cases.\n normal_instruction = (one_instruction - (\n (0x48 0x89 0xe5)\t\t | # mov %rsp,%rbp\n (0x48 0x89 0xec)\t\t | # mov %rbp,%rsp\n (0x48 0x81 0xe4 any{4})\t | # and $XXX,%rsp\n (0x48 0x83 0xe4 any)\t | # and $XXX,%rsp\n (0x4c 0x01 0xfd)\t\t | # add %r15,%rbp\n (0x49 0x8d 0x2c 0x2f)\t | # lea (%r15,%rbp,1),%rbp\n (0x4a 0x8d 0x6c 0x3d any)\t | # lea 0x0(%rbp,%r15,1),%rbp\n (0x48 0x81 0xe5 any{4})\t | # and $XXX,%rsp\n (0x48 0x83 0xe5 any)\t | # and $XXX,%rsp\n (0x4c 0x01 0xfc)\t\t | # add %r15,%rsp\n (0x4a 0x8d 0x24 0x3c)\t | # lea (%rsp,%r15,1),%rsp\n (0x49 0x8d 0x34 0x37)\t | # lea (%r15,%rsi,1),%rsi\n (0x49 0x8d 0x3c 0x3f)\t # lea (%r15,%rdi,1),%rdi\n )) @process_normal_instruction;\n\n special_instruction =\n (0x48 0x89 0xe5)\t\t\t | # mov %rsp,%rbp\n (0x48 0x81 0xe4 any{3} (0x80 .. 0xff)) | # and $XXX,%rsp\n (0x48 0x83 0xe4 (0x80 .. 0xff))\t # and $XXX,%rsp\n @{ if (restricted_register == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n } |\n (0x48 0x89 0xec)\t\t\t | # mov %rbp,%rsp\n (0x48 0x81 0xe5 any{3} (0x80 .. 0xff)) | # and $XXX,%rsp\n (0x48 0x83 0xe5 (0x80 .. 0xff))\t # and $XXX,%rsp\n @{ if (restricted_register == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n } |\n (0x4c 0x01 0xfd\t | # add %r15,%rbp\n 0x49 0x8d 0x2c 0x2f | # lea (%r15,%rbp,1),%rbp\n 0x4a 0x8d 0x6c 0x3d 0x00)\t # lea 0x0(%rbp,%r15,1),%rbp\n @{ if (restricted_register != REG_RBP) {\n\t printf(\"Incorrectly sandboxed %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n } |\n (0x4c 0x01 0xfc\t | # add %r15,%rsp\n 0x4a 0x8d 0x24 0x3c) # lea (%rsp,%r15,1),%rsp\n @{ if (restricted_register != REG_RSP) {\n\t printf(\"Incorrectly sandboxed %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n } |\n (0x83 0xe0 0xe0 0x4c 0x01 0xf8 0xff (0xd0|0xe0) | # naclcall\/jmp %eax, %r15\n 0x83 0xe1 0xe0 0x4c 0x01 0xf9 0xff (0xd1|0xe1) | # naclcall\/jmp %ecx, %r15\n 0x83 0xe2 0xe0 0x4c 0x01 0xfa 0xff (0xd2|0xe2) | # naclcall\/jmp %edx, %r15\n 0x83 0xe3 0xe0 0x4c 0x01 0xfb 0xff (0xd3|0xe3) | # naclcall\/jmp %ebx, %r15\n 0x83 0xe4 0xe0 0x4c 0x01 0xfc 0xff (0xd4|0xe4) | # naclcall\/jmp %esp, %r15\n 0x83 0xe5 0xe0 0x4c 0x01 0xfd 0xff (0xd5|0xe5) | # naclcall\/jmp %ebp, %r15\n 0x83 0xe6 0xe0 0x4c 0x01 0xfe 0xff (0xd6|0xe6) | # naclcall\/jmp %esi, %r15\n 0x83 0xe7 0xe0 0x4c 0x01 0xff 0xff (0xd7|0xe7)) # naclcall\/jmp %edi, %r15\n @{ if (restricted_register == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n } else if (restricted_register == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n BitmapClearBit(valid_targets, (p - data) - 4);\n BitmapClearBit(valid_targets, (p - data) - 1);\n restricted_register = kNoRestrictedReg;\n } |\n (0x41 0x83 0xe0 0xe0 0x4d 0x01 0xf8 0x41 0xff (0xd0|0xe0) | # naclcall\/jmp\n 0x41 0x83 0xe1 0xe0 0x4d 0x01 0xf9 0x41 0xff (0xd1|0xe1) | # %r8d, %r15\n 0x41 0x83 0xe2 0xe0 0x4d 0x01 0xfa 0x41 0xff (0xd2|0xe2) | # \u22ee\n 0x41 0x83 0xe3 0xe0 0x4d 0x01 0xfb 0x41 0xff (0xd3|0xe3) | # \u22ee\n 0x41 0x83 0xe4 0xe0 0x4d 0x01 0xfc 0x41 0xff (0xd4|0xe4) | # \u22ee\n 0x41 0x83 0xe5 0xe0 0x4d 0x01 0xfd 0x41 0xff (0xd5|0xe5) | # naclcall\/jmp\n 0x41 0x83 0xe6 0xe0 0x4d 0x01 0xfe 0x41 0xff (0xd6|0xe6)) # %r14d, %r15\n @{ if (restricted_register == REG_RSP) {\n\t printf(\"Incorrectly modified register %%rsp at the %zx\\n\", p - data);\n\t exit(1);\n } else if (restricted_register == REG_RBP) {\n\t printf(\"Incorrectly modified register %%rbp at the %zx\\n\", p - data);\n\t exit(1);\n }\n BitmapClearBit(valid_targets, (p - data) - 5);\n BitmapClearBit(valid_targets, (p - data) - 2);\n restricted_register = kNoRestrictedReg;\n } |\n (0x49 0x8d 0x34 0x37) # lea (%r15,%rsi,1),%rsi\n @{ if (restricted_register == REG_RSI) {\n\t sandboxed_rsi = begin;\n\t restricted_register = kSandboxedRsi;\n } else {\n\t restricted_register = kNoRestrictedReg;\n }\n } |\n (0x49 0x8d 0x3c 0x3f) # lea (%r15,%rdi,1),%rdi\n @{ if (restricted_register == REG_RDI) {\n\t sandboxed_rdi = begin;\n\t restricted_register = kSandboxedRdi;\n } else if (restricted_register == kSandboxedRsiRestrictedRdi) {\n\t sandboxed_rdi = begin;\n\t restricted_register = kSandboxedRsiSandboxedRdi;\n } else {\n restricted_register = kNoRestrictedReg;\n }\n } |\n (0xac\t\t | # lods %ds:(%rsi),%al\n (data16|REXW_NONE)? 0xad)\t # lods %ds:(%rsi),%ax\/%eax\/%rax\n @{ if (restricted_register != kSandboxedRsi) {\n\t printf(\"Incorrectly sandboxed %%rdi at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n } |\n (0xae\t\t | # scas %ds:(%rsi),%al\n (data16|REXW_NONE)? 0xaf | # scas %ds:(%rsi),%ax\/%eax\/%rax\n 0xaa\t\t | # stos %al,%es:(%rdi)\n (data16|REXW_NONE)? 0xab)\t # stos %ax\/%eax\/%rax,%es:(%rdi)\n @{ if (restricted_register != kSandboxedRdi &&\n\t restricted_register != kSandboxedRsiSandboxedRdi) {\n\t printf(\"Incorrectly sandboxed %%rdi at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n } |\n (condrep? 0xa6\t | # cmpsb\t %es:(%rdi),%ds:(%rsi)\n (data16 |\n condrep data16 |\n data16 condrep) 0xa7 | # cmpsw\t %es:(%rdi),%ds:(%rsi)\n condrep? REXW_NONE? 0xa7 | # cmps[lq] %es:(%rdi),%ds:(%rsi)\n rep? 0xa4\t\t | # movsb\t %es:(%rdi),%ds:(%rsi)\n (data16 |\n rep data16 |\n data16 rep) 0xa5\t | # movsw\t %es:(%rdi),%ds:(%rsi)\n rep? REXW_NONE? 0xa5)\t# movs[lq] %es:(%rdi),%ds:(%rsi)\n @{ if (restricted_register != kSandboxedRsiSandboxedRdi) {\n\t printf(\"Incorrectly sandboxed %%rsi or %%rdi at the %zx\\n\", p - data);\n\t exit(1);\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi_restricted_rdi - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n };\n\n main := ((normal_instruction | special_instruction) >{\n\tbegin = p;\n\tBitmapSetBit(valid_targets, p - data);\n\trex_prefix = FALSE;\n\tvex_prefix2 = 0xe0;\n\tvex_prefix3 = 0x00;\n })*\n $!{ process_error(p, userdata);\n\tresult = 1;\n\tgoto error_detected;\n };\n\n}%%\n\n%% write data;\n\n\/* Ignore this information for now. *\/\n#define data16_prefix if (0) result\n#define lock_prefix if (0) result\n#define repz_prefix if (0) result\n#define repnz_prefix if (0) result\n#define branch_not_taken if (0) result\n#define branch_taken if (0) result\n#define imm if (0) begin\n#define imm_operand if (0) result\n#define imm2 if (0) begin\n#define imm2_operand if (0) result\n#define scale if (0) result\n#define disp if (0) begin\n#define disp_type if (0) result\n#define operand0 operands[0].name\n#define operand1 operands[1].name\n#define operand2 operands[2].name\n#define operand3 operands[3].name\n#define operand4 operands[4].name\n#define operand0_type operands[0].type\n#define operand1_type operands[1].type\n#define operand2_type operands[2].type\n#define operand3_type operands[3].type\n#define operand4_type operands[4].type\n\/* It's not important for us. *\/\n#define operand0_read if (0) result\n#define operand1_read if (0) result\n#define operand2_read if (0) result\n#define operand3_read if (0) result\n#define operand4_read if (0) result\n#define operand0_write operands[0].write\n#define operand1_write operands[1].write\n#define operand2_write operands[2].write\n#define operand3_write operands[3].write\n#define operand4_write operands[4].write\n\nenum {\n REX_B = 1,\n REX_X = 2,\n REX_R = 4,\n REX_W = 8\n};\n\nenum disp_mode {\n DISPNONE,\n DISP8,\n DISP16,\n DISP32,\n DISP64,\n};\n\nenum imm_mode {\n IMMNONE,\n IMM2,\n IMM8,\n IMM16,\n IMM32,\n IMM64\n};\n\nstatic const uint8_t one = 1;\n\nstatic const int kBitsPerByte = 8;\n\nstatic inline uint8_t *BitmapAllocate(uint32_t indexes) {\n uint32_t byte_count = (indexes + kBitsPerByte - 1) \/ kBitsPerByte;\n uint8_t *bitmap = malloc(byte_count);\n if (bitmap != NULL) {\n memset(bitmap, 0, byte_count);\n }\n return bitmap;\n}\n\nstatic inline int BitmapIsBitSet(uint8_t *bitmap, uint32_t index) {\n return (bitmap[index \/ kBitsPerByte] & (1 << (index % kBitsPerByte))) != 0;\n}\n\nstatic inline void BitmapSetBit(uint8_t *bitmap, uint32_t index) {\n bitmap[index \/ kBitsPerByte] |= 1 << (index % kBitsPerByte);\n}\n\nstatic inline void BitmapClearBit(uint8_t *bitmap, uint32_t index) {\n bitmap[index \/ kBitsPerByte] &= ~(1 << (index % kBitsPerByte));\n}\n\nint CheckJumpTargets(uint8_t *valid_targets, uint8_t *jump_dests,\n size_t size) {\n size_t i;\n for (i = 0; i < size \/ 32; i++) {\n uint32_t jump_dest_mask = ((uint32_t *) jump_dests)[i];\n uint32_t valid_target_mask = ((uint32_t *) valid_targets)[i];\n if ((jump_dest_mask & ~valid_target_mask) != 0) {\n printf(\"bad jump to around %x\\n\", (unsigned)(i * 32));\n return 1;\n }\n }\n return 0;\n}\n\nint ValidateChunk(const uint8_t *data, size_t size,\n\t\t process_error_func process_error, void *userdata) {\n const size_t bundle_size = 32;\n const size_t bundle_mask = bundle_size - 1;\n\n uint8_t *valid_targets = BitmapAllocate(size);\n uint8_t *jump_dests = BitmapAllocate(size);\n\n const uint8_t *p = data;\n const uint8_t *begin;\n\n uint8_t rex_prefix, vex_prefix2, vex_prefix3;\n struct Operand {\n unsigned int name\t:5;\n unsigned int type\t:2;\n bool\t write\t:1;\n } operands[5];\n enum register_name base, index;\n uint8_t operands_count, i;\n int result = 0;\n \/*\n * These are borders of the appropriate instructions. Initialize them to make\n * compiler happy: they are never used uninitialized even without explicit\n * initialization but GCC is not sophysicated enough to prove that.\n *\/\n const uint8_t *sandboxed_rsi = 0;\n const uint8_t *sandboxed_rsi_restricted_rdi = 0;\n const uint8_t *sandboxed_rdi = 0;\n\n assert(size % bundle_size == 0);\n\n while (p < data + size) {\n const uint8_t *pe = p + bundle_size;\n const uint8_t *eof = pe;\n int cs;\n enum {\n kNoRestrictedReg = 32,\n kSandboxedRsi,\n kSandboxedRdi,\n kSandboxedRsiRestrictedRdi,\n kSandboxedRsiSandboxedRdi\n }; uint8_t restricted_register = kNoRestrictedReg;\n\n %% write init;\n %% write exec;\n\n if (restricted_register == REG_RBP) {\n printf(\"Incorrectly sandboxed %%rbp at the %d%zx\\n\", *data, p - data);\n exit(1);\n } else if (restricted_register == REG_RSP) {\n printf(\"Incorrectly sandboxed %%rbp at the %zx\\n\", p - data);\n exit(1);\n }\n }\n\n if (CheckJumpTargets(valid_targets, jump_dests, size)) {\n result = 1;\n goto error_detected;\n }\n\nerror_detected:\n return result;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"96b7296910af54fb8ad244d650a5333bb977b640","subject":"Ragel variable of element closing tags.","message":"Ragel variable of element closing tags.\n","repos":"ttasanen\/oga,altmetric\/oga,dfockler\/oga,ttasanen\/oga,ttasanen\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,ttasanen\/oga,YorickPeterse\/oga,altmetric\/oga,altmetric\/oga,jeffreybaird\/oga,altmetric\/oga,ttasanen\/oga,jeffreybaird\/oga,altmetric\/oga,YorickPeterse\/oga,YorickPeterse\/oga,dfockler\/oga,dfockler\/oga,jeffreybaird\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga","old_file":"ext\/ragel\/base_lexer.rl","new_file":"ext\/ragel\/base_lexer.rl","new_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n #\n # ## Machine Transitions\n #\n # To transition from one machine to another always use `fnext` instead of\n # `fcall` and `fret`. This removes the need for the code to keep track of a\n # stack.\n #\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_]+;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences would\n # actually make the rules\/actions more complex.\n #\n\n comment_start = '';\n comment = comment_start (any* -- comment_end) comment_end;\n\n action start_comment {\n callback(\"on_comment\", data, encoding, ts + 4, te - 3);\n }\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n\n cdata_start = '';\n cdata = cdata_start (any* -- cdata_end) cdata_end;\n\n action start_cdata {\n callback(\"on_cdata\", data, encoding, ts + 9, te - 3);\n }\n\n # Processing Instructions\n #\n # http:\/\/www.w3.org\/TR\/xpath\/#section-Processing-Instruction-Nodes\n # http:\/\/en.wikipedia.org\/wiki\/Processing_Instruction\n #\n # These are tags meant to be used by parsers\/libraries for custom behaviour.\n # One example are the tags used by PHP: . Note that the XML\n # declaration tags () are not considered to be a processing\n # instruction.\n #\n\n proc_ins_start = '';\n\n action start_proc_ins {\n callback_simple(\"on_proc_ins_start\");\n callback(\"on_proc_ins_name\", data, encoding, ts + 2, te);\n\n mark = te;\n\n fnext proc_ins_body;\n }\n\n proc_ins_body := |*\n proc_ins_end => {\n callback(\"on_text\", data, encoding, mark, ts);\n callback_simple(\"on_proc_ins_end\");\n\n fnext main;\n };\n\n any;\n *|;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote+ dquote);\n string_squote = (squote ^squote+ squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n callback(\"on_string\", data, encoding, ts + 1, te - 1);\n }\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Consumes everything between the [ and ]. Due to the use of :> the ]\n # is not consumed by any+.\n '[' any+ :> ']' => {\n callback(\"on_doctype_inline\", data, encoding, ts + 1, te - 1);\n };\n\n # Lex the public\/system IDs as regular strings.\n string => emit_string;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fnext main;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n string => emit_string;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n\n element_end = '<\/' identifier (':' identifier)* '>';\n\n action start_element {\n callback_simple(\"on_element_start\");\n fnext element_name;\n }\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(\"on_element_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_element_name\", data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"advance_line\");\n };\n\n # Attribute names and namespaces.\n identifier ':' => {\n callback(\"on_attribute_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n string => emit_string;\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(\"on_element_open_end\");\n fnext main;\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(\"on_element_end\");\n fnext main;\n };\n *|;\n\n # The main machine aka the entry point of Ragel.\n main := |*\n doctype_start => start_doctype;\n xml_decl_start => start_xml_decl;\n comment => start_comment;\n cdata => start_cdata;\n proc_ins_start => start_proc_ins;\n\n # The start of an element.\n '<' => start_element;\n\n # Regular closing tags.\n element_end => {\n callback_simple(\"on_element_end\");\n };\n\n # Treat everything else, except for \"<\", as regular text. The \"<\" sign\n # is used for tags so we can't emit text nodes for these characters.\n any+ -- '<' => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","old_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n #\n # ## Machine Transitions\n #\n # To transition from one machine to another always use `fnext` instead of\n # `fcall` and `fret`. This removes the need for the code to keep track of a\n # stack.\n #\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_]+;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences would\n # actually make the rules\/actions more complex.\n #\n\n comment_start = '';\n comment = comment_start (any* -- comment_end) comment_end;\n\n action start_comment {\n callback(\"on_comment\", data, encoding, ts + 4, te - 3);\n }\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n\n cdata_start = '';\n cdata = cdata_start (any* -- cdata_end) cdata_end;\n\n action start_cdata {\n callback(\"on_cdata\", data, encoding, ts + 9, te - 3);\n }\n\n # Processing Instructions\n #\n # http:\/\/www.w3.org\/TR\/xpath\/#section-Processing-Instruction-Nodes\n # http:\/\/en.wikipedia.org\/wiki\/Processing_Instruction\n #\n # These are tags meant to be used by parsers\/libraries for custom behaviour.\n # One example are the tags used by PHP: . Note that the XML\n # declaration tags () are not considered to be a processing\n # instruction.\n #\n\n proc_ins_start = '';\n\n action start_proc_ins {\n callback_simple(\"on_proc_ins_start\");\n callback(\"on_proc_ins_name\", data, encoding, ts + 2, te);\n\n mark = te;\n\n fnext proc_ins_body;\n }\n\n proc_ins_body := |*\n proc_ins_end => {\n callback(\"on_text\", data, encoding, mark, ts);\n callback_simple(\"on_proc_ins_end\");\n\n fnext main;\n };\n\n any;\n *|;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote+ dquote);\n string_squote = (squote ^squote+ squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n callback(\"on_string\", data, encoding, ts + 1, te - 1);\n }\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Consumes everything between the [ and ]. Due to the use of :> the ]\n # is not consumed by any+.\n '[' any+ :> ']' => {\n callback(\"on_doctype_inline\", data, encoding, ts + 1, te - 1);\n };\n\n # Lex the public\/system IDs as regular strings.\n string => emit_string;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fnext main;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n string => emit_string;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n action start_element {\n callback_simple(\"on_element_start\");\n fnext element_name;\n }\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(\"on_element_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_element_name\", data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"advance_line\");\n };\n\n # Attribute names and namespaces.\n identifier ':' => {\n callback(\"on_attribute_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n string => emit_string;\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(\"on_element_open_end\");\n fnext main;\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(\"on_element_end\");\n fnext main;\n };\n *|;\n\n # The main machine aka the entry point of Ragel.\n main := |*\n doctype_start => start_doctype;\n xml_decl_start => start_xml_decl;\n comment => start_comment;\n cdata => start_cdata;\n proc_ins_start => start_proc_ins;\n\n\n # The start of an element.\n '<' => start_element;\n\n # Regular closing tags.\n '<\/' identifier (':' identifier)* '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Treat everything else, except for \"<\", as regular text. The \"<\" sign\n # is used for tags so we can't emit text nodes for these characters.\n ^'<'+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"b41635a4d256affc07656c80ab5f6dbd0fb73e7a","subject":"Added \"any\" general properties","message":"Added \"any\" general properties\n","repos":"gjtorikian\/regexp_parser,ammar\/regexp_parser,ammar\/regexp_parser,jhart-r7\/regexp_parser","old_file":"lib\/regexp_parser\/scanner.rl","new_file":"lib\/regexp_parser\/scanner.rl","new_contents":"%%{\n machine re_scanner;\n\n wild = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n posix_class_name = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n property_name = 'Alnum' | 'Alpha' | 'Any' | 'Ascii' | 'Blank' |\n 'Cntrl' | 'Digit' | 'Graph' | 'Lower' | 'Print' |\n 'Punct' | 'Space' | 'Upper' | 'Word' | 'Xdigit';\n\n category_letter = 'L' . [ultmo]?;\n category_mark = 'M' . [nce]?;\n category_number = 'N' . [dlo]?;\n category_punctuation = 'P' . [cdseifo]?;\n category_symbol = 'S' . [mcko]?;\n category_separator = 'Z' . [slp]?;\n category_codepoint = 'C' . [cfson]?;\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n posix_class = '[:' . posix_class_name . ':]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n property_char = [pP];\n\n escaped_char = [aefnrtv];\n octal_sequence = '0' . [0-7]{2};\n\n hex_sequence = 'x' . xdigit{2};\n wide_hex_sequence = 'x' . '{7' . xdigit{1,7} . '}';\n control_sequence = ('c' | 'C-') . xdigit{1,2};\n meta_sequence = 'M-' . xdigit{1,2};\n meta_control_sequence = 'M-\\\\C-' . xdigit{1,2};\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_range = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_range;\n\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?';\n\n group_type = group_atomic | group_passive | group_named;\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters the 'break' a literal\n meta_char = wild | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n\n # character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n self.emit(:character_set, :close, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n '^' {\n self.emit(:character_set, :negate, data[ts..te-1].pack('c*'), ts, te)\n };\n\n alnum . '-' . alnum { # TODO: add properties\n self.emit(:character_set, :range, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '&&' {\n self.emit(:character_set, :intersection, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '\\\\' . [\\]\\-\\,b] {\n self.emit(:character_set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n\n posix_class {\n case text = data[ts..te-1].pack('c*')\n when '[:alnum:]'; self.emit(:character_set, :set_class_alnum, text, ts, te)\n when '[:alpha:]'; self.emit(:character_set, :set_class_alpha, text, ts, te)\n when '[:blank:]'; self.emit(:character_set, :set_class_blank, text, ts, te)\n when '[:cntrl:]'; self.emit(:character_set, :set_class_cntrl, text, ts, te)\n when '[:digit:]'; self.emit(:character_set, :set_class_digit, text, ts, te)\n when '[:graph:]'; self.emit(:character_set, :set_class_graph, text, ts, te)\n when '[:lower:]'; self.emit(:character_set, :set_class_lower, text, ts, te)\n when '[:print:]'; self.emit(:character_set, :set_class_print, text, ts, te)\n when '[:punct:]'; self.emit(:character_set, :set_class_punct, text, ts, te)\n when '[:space:]'; self.emit(:character_set, :set_class_space, text, ts, te)\n when '[:upper:]'; self.emit(:character_set, :set_class_upper, text, ts, te)\n when '[:xdigit:]'; self.emit(:character_set, :set_class_xdigit, text, ts, te)\n when '[:word:]'; self.emit(:character_set, :set_class_word, text, ts, te)\n when '[:ascii:]'; self.emit(:character_set, :set_class_ascii, text, ts, te)\n else raise \"Unsupported character posixe class at #{text} (char #{ts})\"\n end\n };\n\n any {\n self.emit(:character_set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n hex_sequence {\n self.emit(:escape_sequence, :hex, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n wide_hex_sequence {\n self.emit(:escape_sequence, :hex_wide, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n control_sequence {\n self.emit(:escape_sequence, :control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_sequence {\n self.emit(:escape_sequence, :meta, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_control_sequence {\n self.emit(:escape_sequence, :meta_control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n # TODO: extract into a separate machine... use in sets\n property_char . '{' . (property_name | general_category) . '}' > (escaped_alpha, 2) {\n text = data[ts..te-1].pack('c*')\n type = text[0,1] == 'p' ? :property: :inverted_property\n\n case name = data[ts+2..te-2].pack('c*')\n\n # Named\n when 'Alnum'; self.emit(type, :alnum, text, ts, te)\n when 'Alpha'; self.emit(type, :alpha, text, ts, te)\n when 'Any'; self.emit(type, :any, text, ts, te)\n when 'Ascii'; self.emit(type, :ascii, text, ts, te)\n when 'Blank'; self.emit(type, :blank, text, ts, te)\n when 'Cntrl'; self.emit(type, :cntrl, text, ts, te)\n when 'Digit'; self.emit(type, :digit, text, ts, te)\n when 'Graph'; self.emit(type, :graph, text, ts, te)\n when 'Lower'; self.emit(type, :lower, text, ts, te)\n when 'Print'; self.emit(type, :print, text, ts, te)\n when 'Punct'; self.emit(type, :punct, text, ts, te)\n when 'Space'; self.emit(type, :space, text, ts, te)\n when 'Upper'; self.emit(type, :upper, text, ts, te)\n when 'Word'; self.emit(type, :word, text, ts, te)\n when 'Xdigit'; self.emit(type, :xdigit, text, ts, te)\n\n # Letters\n when 'L'; self.emit(type, :letter_any, text, ts, te)\n when 'Lu'; self.emit(type, :letter_uppercase, text, ts, te)\n when 'Ll'; self.emit(type, :letter_lowercase, text, ts, te)\n when 'Lt'; self.emit(type, :letter_titlecase, text, ts, te)\n when 'Lm'; self.emit(type, :letter_modifier, text, ts, te)\n when 'Lo'; self.emit(type, :letter_other, text, ts, te)\n\n # Marks\n when 'M'; self.emit(type, :mark_any, text, ts, te)\n when 'Mn'; self.emit(type, :mark_nonspacing, text, ts, te)\n when 'Mc'; self.emit(type, :mark_spacing, text, ts, te)\n when 'Me'; self.emit(type, :mark_enclosing, text, ts, te)\n\n # Numbers\n when 'N'; self.emit(type, :number_any, text, ts, te)\n when 'Nd'; self.emit(type, :number_decimal, text, ts, te)\n when 'Nl'; self.emit(type, :number_letter, text, ts, te)\n when 'No'; self.emit(type, :number_other, text, ts, te)\n\n # Punctuation\n when 'P'; self.emit(type, :punct_any, text, ts, te)\n when 'Pc'; self.emit(type, :punct_connector, text, ts, te)\n when 'Pd'; self.emit(type, :punct_dash, text, ts, te)\n when 'Ps'; self.emit(type, :punct_open, text, ts, te)\n when 'Pe'; self.emit(type, :punct_close, text, ts, te)\n when 'Pi'; self.emit(type, :punct_initial, text, ts, te)\n when 'Pf'; self.emit(type, :punct_final, text, ts, te)\n when 'Po'; self.emit(type, :punct_other, text, ts, te)\n\n # Symbols\n when 'S'; self.emit(type, :symbol_any, text, ts, te)\n when 'Sm'; self.emit(type, :symbol_math, text, ts, te)\n when 'Sc'; self.emit(type, :symbol_currency, text, ts, te)\n when 'Sk'; self.emit(type, :symbol_modifier, text, ts, te)\n when 'So'; self.emit(type, :symbol_other, text, ts, te)\n\n # Separators\n when 'Z'; self.emit(type, :separator_any, text, ts, te)\n when 'Zs'; self.emit(type, :separator_space, text, ts, te)\n when 'Zl'; self.emit(type, :separator_line, text, ts, te)\n when 'Zp'; self.emit(type, :separator_paragraph, text, ts, te)\n\n # Codepoints\n when 'C'; self.emit(type, :code_any, text, ts, te)\n when 'Cc'; self.emit(type, :code_control, text, ts, te)\n when 'Cf'; self.emit(type, :code_format, text, ts, te)\n when 'Cs'; self.emit(type, :code_surrogate, text, ts, te)\n when 'Co'; self.emit(type, :code_private, text, ts, te)\n when 'Cn'; self.emit(type, :code_unassigned, text, ts, te)\n end\n };\n\n any > (escaped_alpha, 1) {\n self.emit(:escape_sequence, :literal, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n *|;\n\n\n # Main scanner\n main := |*\n\n # Anchors\n alternation {\n self.emit(:meta, :alternation, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Character types\n # . any (except new line)\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S whitespace, non-whitespace\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n wild {\n self.emit(:character_type, :any, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . char_type > (backslashed, 2) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\d'; self.emit(:character_type, :digit, text, ts, te)\n when '\\\\D'; self.emit(:character_type, :non_digit, text, ts, te)\n when '\\\\h'; self.emit(:character_type, :hex, text, ts, te)\n when '\\\\H'; self.emit(:character_type, :non_hex, text, ts, te)\n when '\\\\s'; self.emit(:character_type, :space, text, ts, te)\n when '\\\\S'; self.emit(:character_type, :non_space, text, ts, te)\n when '\\\\w'; self.emit(:character_type, :word, text, ts, te)\n when '\\\\W'; self.emit(:character_type, :non_word, text, ts, te)\n else raise \"Unsupported character type at #{text} (char #{ts})\"\n end\n };\n\n # Anchors\n beginning_of_line {\n self.emit(:anchor, :beginning_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n end_of_line {\n self.emit(:anchor, :end_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\A'; self.emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; self.emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; self.emit(:anchor, :eos_or_before_eol, text, ts, te)\n when '\\\\b'; self.emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; self.emit(:anchor, :non_word_boundary, text, ts, te)\n else raise \"Unsupported anchor at #{text} (char #{ts})\"\n end\n };\n\n # Escaped sequences\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Character sets\n set_open {\n self.emit(:character_set, :open, data[ts..te-1].pack('c*'), ts, te)\n fcall character_set;\n };\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n group_open . group_comment {\n self.emit(:group, :comment, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # (?mix-mix...) expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n group_open . group_options > (grouped, 1) {\n self.emit(:group, :options, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (? (grouped, 2) {\n case text = data[ts..te-1].pack('c*')\n when '(?='; self.emit(:assertion, :lookahead, text, ts, te)\n when '(?!'; self.emit(:assertion, :nlookahead, text, ts, te)\n when '(?<='; self.emit(:assertion, :lookbehind, text, ts, te)\n when '(?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group (single quotes are no supported, yet)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type? > (grouped, 3) {\n case text = data[ts..te-1].pack('c*')\n when '(?:'; self.emit(:group, :passive, text, ts, te)\n when '(?>'; self.emit(:group, :atomic, text, ts, te)\n when '(?<[a-zA-Z]\\w+>'\n self.emit(:group, :named, text, ts, te)\n else\n self.emit(:group, :capture, text, ts, te)\n end\n };\n\n group_close {\n self.emit(:group, :close, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = data[ts..te-1].pack('c*')\n when '?' ; self.emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; self.emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; self.emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n \n zero_or_more {\n case text = data[ts..te-1].pack('c*')\n when '*' ; self.emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; self.emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; self.emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n \n one_or_more {\n case text = data[ts..te-1].pack('c*')\n when '+' ; self.emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; self.emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; self.emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n\n # Intervals: min, max, and exact notations\n # ------------------------------------------------------------------------\n range_open . (digit+)? . ','? . (digit+)? . range_close . quantifier_mode? {\n self.emit(:quantifier, :interval, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Literal: anything, except meta characters. This includes 2, 3, and 4\n # unicode byte sequences.\n # ------------------------------------------------------------------------\n (any - meta_char)+ {\n self.emit(:literal, :literal, data[ts..te-1].pack('c*'), ts, te)\n };\n\n *|;\n}%%\n","old_contents":"%%{\n machine re_scanner;\n\n wild = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n posix_class_name = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n property_name = 'Alnum' | 'Alpha' | 'Any' | 'Ascii' | 'Blank' |\n 'Cntrl' | 'Digit' | 'Graph' | 'Lower' | 'Print' |\n 'Punct' | 'Space' | 'Upper' | 'Word' | 'Xdigit';\n\n category_letter = 'L' . [ultmo]?;\n category_mark = 'M' . [nce]?;\n category_number = 'N' . [dlo]?;\n category_punctuation = 'P' . [cdseifo]?;\n category_symbol = 'S' . [mcko]?;\n category_separator = 'Z' . [slp]?;\n category_codepoint = 'C' . [cfson]?;\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n posix_class = '[:' . posix_class_name . ':]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n property_char = [pP];\n\n escaped_char = [aefnrtv];\n octal_sequence = '0' . [0-7]{2};\n\n hex_sequence = 'x' . xdigit{2};\n wide_hex_sequence = 'x' . '{7' . xdigit{1,7} . '}';\n control_sequence = ('c' | 'C-') . xdigit{1,2};\n meta_sequence = 'M-' . xdigit{1,2};\n meta_control_sequence = 'M-\\\\C-' . xdigit{1,2};\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_range = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_range;\n\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?';\n\n group_type = group_atomic | group_passive | group_named;\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters the 'break' a literal\n meta_char = wild | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n\n # character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n self.emit(:character_set, :close, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n '^' {\n self.emit(:character_set, :negate, data[ts..te-1].pack('c*'), ts, te)\n };\n\n alnum . '-' . alnum { # TODO: add properties\n self.emit(:character_set, :range, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '&&' {\n self.emit(:character_set, :intersection, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '\\\\' . [\\]\\-\\,b] {\n self.emit(:character_set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n\n posix_class {\n case text = data[ts..te-1].pack('c*')\n when '[:alnum:]'; self.emit(:character_set, :set_class_alnum, text, ts, te)\n when '[:alpha:]'; self.emit(:character_set, :set_class_alpha, text, ts, te)\n when '[:blank:]'; self.emit(:character_set, :set_class_blank, text, ts, te)\n when '[:cntrl:]'; self.emit(:character_set, :set_class_cntrl, text, ts, te)\n when '[:digit:]'; self.emit(:character_set, :set_class_digit, text, ts, te)\n when '[:graph:]'; self.emit(:character_set, :set_class_graph, text, ts, te)\n when '[:lower:]'; self.emit(:character_set, :set_class_lower, text, ts, te)\n when '[:print:]'; self.emit(:character_set, :set_class_print, text, ts, te)\n when '[:punct:]'; self.emit(:character_set, :set_class_punct, text, ts, te)\n when '[:space:]'; self.emit(:character_set, :set_class_space, text, ts, te)\n when '[:upper:]'; self.emit(:character_set, :set_class_upper, text, ts, te)\n when '[:xdigit:]'; self.emit(:character_set, :set_class_xdigit, text, ts, te)\n when '[:word:]'; self.emit(:character_set, :set_class_word, text, ts, te)\n when '[:ascii:]'; self.emit(:character_set, :set_class_ascii, text, ts, te)\n else raise \"Unsupported character posixe class at #{text} (char #{ts})\"\n end\n };\n\n any {\n self.emit(:character_set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n hex_sequence {\n self.emit(:escape_sequence, :hex, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n wide_hex_sequence {\n self.emit(:escape_sequence, :hex_wide, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n control_sequence {\n self.emit(:escape_sequence, :control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_sequence {\n self.emit(:escape_sequence, :meta, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_control_sequence {\n self.emit(:escape_sequence, :meta_control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n # TODO: extract into a separate machine... use in sets\n property_char . '{' . (property_name | general_category) . '}' > (escaped_alpha, 2) {\n text = data[ts..te-1].pack('c*')\n type = text[0,1] == 'p' ? :property: :inverted_property\n\n case name = data[ts+2..te-2].pack('c*')\n\n # Named\n when 'Alnum'; self.emit(type, :alnum, text, ts, te)\n when 'Alpha'; self.emit(type, :alpha, text, ts, te)\n when 'Any'; self.emit(type, :any, text, ts, te)\n when 'Ascii'; self.emit(type, :ascii, text, ts, te)\n when 'Blank'; self.emit(type, :blank, text, ts, te)\n when 'Cntrl'; self.emit(type, :cntrl, text, ts, te)\n when 'Digit'; self.emit(type, :digit, text, ts, te)\n when 'Graph'; self.emit(type, :graph, text, ts, te)\n when 'Lower'; self.emit(type, :lower, text, ts, te)\n when 'Print'; self.emit(type, :print, text, ts, te)\n when 'Punct'; self.emit(type, :punct, text, ts, te)\n when 'Space'; self.emit(type, :space, text, ts, te)\n when 'Upper'; self.emit(type, :upper, text, ts, te)\n when 'Word'; self.emit(type, :word, text, ts, te)\n when 'Xdigit'; self.emit(type, :xdigit, text, ts, te)\n\n # Letters\n when 'Lu'; self.emit(type, :letter_uppercase, text, ts, te)\n when 'Ll'; self.emit(type, :letter_lowercase, text, ts, te)\n when 'Lt'; self.emit(type, :letter_titlecase, text, ts, te)\n when 'Lm'; self.emit(type, :letter_modifier, text, ts, te)\n when 'Lo'; self.emit(type, :letter_other, text, ts, te)\n\n # Marks\n when 'Mn'; self.emit(type, :mark_nonspacing, text, ts, te)\n when 'Mc'; self.emit(type, :mark_spacing, text, ts, te)\n when 'Me'; self.emit(type, :mark_enclosing, text, ts, te)\n\n # Numbers\n when 'Nd'; self.emit(type, :number_decimal, text, ts, te)\n when 'Nl'; self.emit(type, :number_letter, text, ts, te)\n when 'No'; self.emit(type, :number_other, text, ts, te)\n\n # Punctuation\n when 'Pc'; self.emit(type, :punct_connector, text, ts, te)\n when 'Pd'; self.emit(type, :punct_dash, text, ts, te)\n when 'Ps'; self.emit(type, :punct_open, text, ts, te)\n when 'Pe'; self.emit(type, :punct_close, text, ts, te)\n when 'Pi'; self.emit(type, :punct_initial, text, ts, te)\n when 'Pf'; self.emit(type, :punct_final, text, ts, te)\n when 'Po'; self.emit(type, :punct_other, text, ts, te)\n\n # Symbols\n when 'Sm'; self.emit(type, :symbol_math, text, ts, te)\n when 'Sc'; self.emit(type, :symbol_currency, text, ts, te)\n when 'Sk'; self.emit(type, :symbol_modifier, text, ts, te)\n when 'So'; self.emit(type, :symbol_other, text, ts, te)\n\n # Separators\n when 'Zs'; self.emit(type, :separator_space, text, ts, te)\n when 'Zl'; self.emit(type, :separator_line, text, ts, te)\n when 'Zp'; self.emit(type, :separator_paragraph, text, ts, te)\n\n # Codepoints\n when 'Cc'; self.emit(type, :code_control, text, ts, te)\n when 'Cf'; self.emit(type, :code_format, text, ts, te)\n when 'Cs'; self.emit(type, :code_surrogate, text, ts, te)\n when 'Co'; self.emit(type, :code_private, text, ts, te)\n when 'Cn'; self.emit(type, :code_unassigned, text, ts, te)\n end\n };\n\n any > (escaped_alpha, 1) {\n self.emit(:escape_sequence, :literal, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n *|;\n\n\n # Main scanner\n main := |*\n\n # Anchors\n alternation {\n self.emit(:meta, :alternation, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Character types\n # . any (except new line)\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S whitespace, non-whitespace\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n wild {\n self.emit(:character_type, :any, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . char_type > (backslashed, 2) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\d'; self.emit(:character_type, :digit, text, ts, te)\n when '\\\\D'; self.emit(:character_type, :non_digit, text, ts, te)\n when '\\\\h'; self.emit(:character_type, :hex, text, ts, te)\n when '\\\\H'; self.emit(:character_type, :non_hex, text, ts, te)\n when '\\\\s'; self.emit(:character_type, :space, text, ts, te)\n when '\\\\S'; self.emit(:character_type, :non_space, text, ts, te)\n when '\\\\w'; self.emit(:character_type, :word, text, ts, te)\n when '\\\\W'; self.emit(:character_type, :non_word, text, ts, te)\n else raise \"Unsupported character type at #{text} (char #{ts})\"\n end\n };\n\n # Anchors\n beginning_of_line {\n self.emit(:anchor, :beginning_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n end_of_line {\n self.emit(:anchor, :end_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\A'; self.emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; self.emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; self.emit(:anchor, :eos_or_before_eol, text, ts, te)\n when '\\\\b'; self.emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; self.emit(:anchor, :non_word_boundary, text, ts, te)\n else raise \"Unsupported anchor at #{text} (char #{ts})\"\n end\n };\n\n # Escaped sequences\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Character sets\n set_open {\n self.emit(:character_set, :open, data[ts..te-1].pack('c*'), ts, te)\n fcall character_set;\n };\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n group_open . group_comment {\n self.emit(:group, :comment, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # (?mix-mix...) expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n group_open . group_options > (grouped, 1) {\n self.emit(:group, :options, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (? (grouped, 2) {\n case text = data[ts..te-1].pack('c*')\n when '(?='; self.emit(:assertion, :lookahead, text, ts, te)\n when '(?!'; self.emit(:assertion, :nlookahead, text, ts, te)\n when '(?<='; self.emit(:assertion, :lookbehind, text, ts, te)\n when '(?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group (single quotes are no supported, yet)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type? > (grouped, 3) {\n case text = data[ts..te-1].pack('c*')\n when '(?:'; self.emit(:group, :passive, text, ts, te)\n when '(?>'; self.emit(:group, :atomic, text, ts, te)\n when '(?<[a-zA-Z]\\w+>'\n self.emit(:group, :named, text, ts, te)\n else\n self.emit(:group, :capture, text, ts, te)\n end\n };\n\n group_close {\n self.emit(:group, :close, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = data[ts..te-1].pack('c*')\n when '?' ; self.emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; self.emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; self.emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n \n zero_or_more {\n case text = data[ts..te-1].pack('c*')\n when '*' ; self.emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; self.emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; self.emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n \n one_or_more {\n case text = data[ts..te-1].pack('c*')\n when '+' ; self.emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; self.emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; self.emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n\n # Intervals: min, max, and exact notations\n # ------------------------------------------------------------------------\n range_open . (digit+)? . ','? . (digit+)? . range_close . quantifier_mode? {\n self.emit(:quantifier, :interval, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Literal: anything, except meta characters. This includes 2, 3, and 4\n # unicode byte sequences.\n # ------------------------------------------------------------------------\n (any - meta_char)+ {\n self.emit(:literal, :literal, data[ts..te-1].pack('c*'), ts, te)\n };\n\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f494e47351eb82a075c98920899869da3a5f3f4d","subject":"DRY up attributes machine.","message":"DRY up attributes machine.\n","repos":"github\/redcloth,purcell\/redcloth,dmitry\/redcloth,dmitry\/redcloth,amrocco\/redcloth,mmorga\/redcloth,amrocco\/redcloth,purcell\/redcloth,mmorga\/redcloth,github\/redcloth","old_file":"ext\/redcloth_scan\/redcloth_attributes.java.rl","new_file":"ext\/redcloth_scan\/redcloth_attributes.java.rl","new_contents":"\/*\n * redcloth_attributes.rl\n *\n * Copyright (C) 2008 Jason Garber\n *\/\nimport java.io.IOException;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyArray;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyHash;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyNumeric;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyString;\nimport org.jruby.RubySymbol;\nimport org.jruby.anno.JRubyMethod;\nimport org.jruby.runtime.Block;\nimport org.jruby.runtime.CallbackFactory;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.exceptions.RaiseException;\nimport org.jruby.runtime.load.BasicLibraryService;\n\nimport org.jruby.util.ByteList;\n\npublic class RedclothAttributes extends RedclothScanService.Base {\n\n%%{\n\n machine redcloth_attributes;\n include redcloth_common \"redcloth_common.java.rl\";\n include redcloth_attributes \"redcloth_attributes.rl\";\n\n}%%\n\n%% write data nofinal;\n\n public void SET_ATTRIBUTES() {\n SET_ATTRIBUTE(\"class_buf\", \"class\");\n SET_ATTRIBUTE(\"id_buf\", \"id\");\n SET_ATTRIBUTE(\"lang_buf\", \"lang\");\n SET_ATTRIBUTE(\"style_buf\", \"style\");\n }\n\n public void SET_ATTRIBUTE(String B, String A) {\n buf = ((RubyHash)regs).aref(runtime.newSymbol(B));\n if(!buf.isNil()) {\n ((RubyHash)regs).aset(runtime.newSymbol(A), buf);\n }\n }\n \n private int machine;\n private IRubyObject buf;\n \n public RedclothAttributes(int machine, IRubyObject self, byte[] data, int p, int pe) {\n this.runtime = self.getRuntime();\n this.self = self;\n\n \/\/ This is GROSS but necessary for EOF matching\n this.data = new byte[pe+1];\n System.arraycopy(data, p, this.data, 0, pe);\n this.data[pe] = 0;\n\n this.p = 0;\n this.pe = pe+1;\n this.eof = this.pe;\n this.orig_p = 0;\n this.orig_pe = this.pe;\n\n this.regs = RubyHash.newHash(runtime);\n this.buf = runtime.getNil();\n this.machine = machine;\n }\n\n public IRubyObject parse() {\n %% write init;\n \n cs = machine;\n\n %% write exec;\n\n return regs;\n }\n\n public static IRubyObject attributes(IRubyObject self, IRubyObject str) {\n ByteList bl = str.convertToString().getByteList();\n int cs = redcloth_attributes_en_inline;\n return new RedclothAttributes(cs, self, bl.bytes, bl.begin, bl.realSize).parse();\n }\n\n public static IRubyObject link_attributes(IRubyObject self, IRubyObject str) {\n ByteList bl = str.convertToString().getByteList();\n int cs = redcloth_attributes_en_link_says;\n return new RedclothAttributes(cs, self, bl.bytes, bl.begin, bl.realSize).parse();\n }\n}\n","old_contents":"\/*\n * redcloth_attributes.rl\n *\n * Copyright (C) 2008 Jason Garber\n *\/\nimport java.io.IOException;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyArray;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyHash;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyNumeric;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyString;\nimport org.jruby.RubySymbol;\nimport org.jruby.anno.JRubyMethod;\nimport org.jruby.runtime.Block;\nimport org.jruby.runtime.CallbackFactory;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.exceptions.RaiseException;\nimport org.jruby.runtime.load.BasicLibraryService;\n\nimport org.jruby.util.ByteList;\n\npublic class RedclothAttributes extends RedclothScanService.Base {\n\n%%{\n\n machine redcloth_attributes;\n include redcloth_common \"redcloth_common.java.rl\";\n \n C2_CLAS = ( \"(\" ( [^)#]+ >A %{ STORE(\"class_buf\"); } )? (\"#\" [^)]+ >A %{STORE(\"id_buf\");} )? \")\" ) ;\n C2_LNGE = ( \"[\" [^\\]]+ >A %{ STORE(\"lang_buf\"); } \"]\" ) ;\n C2_STYL = ( \"{\" [^}]+ >A %{ STORE(\"style_buf\"); } \"}\" ) ;\n C2 = ( C2_CLAS | C2_STYL | C2_LNGE )+ ;\n\n mtext_with_attributes = ( C2 mtext >A %T ) >X ;\n\n inline := |*\n\n mtext_with_attributes { SET_ATTRIBUTES(); } ;\n\n *|;\n\n link_text_with_attributes = C2 \".\"* \" \"* ( mtext+ ) >A %{ STORE(\"name\"); } ;\n link_text_without_attributes = ( mtext+ ) >B %{ STORE_B(\"name_without_attributes\"); } ;\n\n link_says := |*\n\n link_text_with_attributes { SET_ATTRIBUTES(); } ;\n link_text_without_attributes { SET_ATTRIBUTE(\"name_without_attributes\", \"name\"); } ;\n\n *|;\n\n}%%\n\n%% write data nofinal;\n\n public void SET_ATTRIBUTES() {\n SET_ATTRIBUTE(\"class_buf\", \"class\");\n SET_ATTRIBUTE(\"id_buf\", \"id\");\n SET_ATTRIBUTE(\"lang_buf\", \"lang\");\n SET_ATTRIBUTE(\"style_buf\", \"style\");\n }\n\n public void SET_ATTRIBUTE(String B, String A) {\n buf = ((RubyHash)regs).aref(runtime.newSymbol(B));\n if(!buf.isNil()) {\n ((RubyHash)regs).aset(runtime.newSymbol(A), buf);\n }\n }\n \n private int machine;\n private IRubyObject buf;\n \n public RedclothAttributes(int machine, IRubyObject self, byte[] data, int p, int pe) {\n this.runtime = self.getRuntime();\n this.self = self;\n\n \/\/ This is GROSS but necessary for EOF matching\n this.data = new byte[pe+1];\n System.arraycopy(data, p, this.data, 0, pe);\n this.data[pe] = 0;\n\n this.p = 0;\n this.pe = pe+1;\n this.eof = this.pe;\n this.orig_p = 0;\n this.orig_pe = this.pe;\n\n this.regs = RubyHash.newHash(runtime);\n this.buf = runtime.getNil();\n this.machine = machine;\n }\n\n public IRubyObject parse() {\n %% write init;\n \n cs = machine;\n\n %% write exec;\n\n return regs;\n }\n\n public static IRubyObject attributes(IRubyObject self, IRubyObject str) {\n ByteList bl = str.convertToString().getByteList();\n int cs = redcloth_attributes_en_inline;\n return new RedclothAttributes(cs, self, bl.bytes, bl.begin, bl.realSize).parse();\n }\n\n public static IRubyObject link_attributes(IRubyObject self, IRubyObject str) {\n ByteList bl = str.convertToString().getByteList();\n int cs = redcloth_attributes_en_link_says;\n return new RedclothAttributes(cs, self, bl.bytes, bl.begin, bl.realSize).parse();\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"bf38ab8cdff4001435ee1672d7a7bd4d43d7e1e2","subject":"[mtocpp_post] added quiet flag","message":"[mtocpp_post] added quiet flag\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/postprocess.rl","new_file":"src\/postprocess.rl","new_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\/\/ New for directory recursion\n#ifdef WIN32\n\t#include \n#else\n\t#include \n#endif\n\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n if (!quiet)\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p);\n if (!quiet)\n cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # bugfix: allow '>' in the end of typenames for Daniel's generic types\n ('<' . [^&]* . '>') => { fout.write(ts, te-ts); };\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US) => { fout.write(ts, te-ts); };\n\n '_m_tsbus_cotm_' => { fout << \">\"; fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n ('::mtoc_subst_') => { fout << '.'; fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:.,;_\\t])+ => { fout.write(ts, te-ts); };\n\n (')=0') => { fout << \")\"; };\n\n # word separators\n ([\\n <>()[\\]{}\\t:.;,_\\&]) => {fout << *ts;};\n\n # a single dot stays a dot\n ('.') => {fout << '.';};\n *|;\n}%%\n\nclass PostProcess {\n\nprivate:\n string docdir_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n bool quiet_;\n\npublic:\n \/**\n * @class PostProcess\n *\n * @change{1,2,dw,2011-11-04} Changed the postprocessor interface from taking a single file argument to\n * assuming the passed string to be a folder whos contents are to be postprocessed.\n *\/\n \/\/ constructor\n PostProcess(const string &docdir, const bool quiet_flag) :\n docdir_(docdir),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false),\n quiet_(quiet_flag)\n { }\n\n int execute()\n {\n DIR *dp;\n if ((dp = opendir(docdir_.c_str())) == NULL) {\n cerr << \"Error opening directory \" << docdir_ << endl;\n return -1;\n }\n\n struct dirent* dirp;\n string file;\n while ((dirp = readdir(dp)) != NULL) {\n file = string(dirp->d_name);\n \/\/ Process only html files\n if (file.substr(file.find_last_of(\".\") + 1) == \"html\" && file.find(\"8rl\") == string::npos) {\n postprocess(docdir_ + string(\"\/\") + file);\n }\n }\n closedir(dp);\n return 0;\n }\n\n \/\/ run postprocessor\n int postprocess(string file)\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try {\n is.open(file.c_str());\n } catch (std::ifstream::failure e) {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char* buf = new char[(int)(1.1*length)];\n char* p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n \n ofstream fout;\n try {\n fout.open(file.c_str(), ios_base::trunc);\n } catch (std::ofstream::failure e) {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << file << \": PARSE ERROR \" << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n};\n\nvoid usage()\n{\n cout << \"mtocpp_post Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: mtocpp_post [-q] filename\" << endl;\n cout << \"\\nOptions:\\n -q\\t\\tsuppresses debug output.\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n bool quiet = false;\n string docdir;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n if (argc == 3 && std::string(\"-q\") == std::string(argv[1]))\n {\n quiet = true;\n docdir = argv[2];\n }\n else if(argc == 2)\n docdir = argv[1];\n else\n {\n cerr << \"wrong arguments!\" << endl;\n usage();\n exit(-2);\n }\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n usage();\n exit(-2);\n }\n\n if (!quiet)\n cout << \"Running mtoc++ postprocessor on directory \" << docdir << endl;\n\n PostProcess scanner(docdir, quiet);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","old_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\/\/ New for directory recursion\n#ifdef WIN32\n\t#include \n#else\n\t#include \n#endif\n\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # bugfix: allow '>' in the end of typenames for Daniel's generic types\n ('<' . [^&]* . '>') => { fout.write(ts, te-ts); };\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US) => { fout.write(ts, te-ts); };\n\n '_m_tsbus_cotm_' => { fout << \">\"; fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n ('::mtoc_subst_') => { fout << '.'; fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:.,;_\\t])+ => { fout.write(ts, te-ts); };\n\n (')=0') => { fout << \")\"; };\n\n # word separators\n ([\\n <>()[\\]{}\\t:.;,_\\&]) => {fout << *ts;};\n\n # a single dot stays a dot\n ('.') => {fout << '.';};\n *|;\n}%%\n\nclass PostProcess {\n\nprivate:\n string docdir_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n\npublic:\n \/**\n * @class PostProcess\n *\n * @change{1,2,dw,2011-11-04} Changed the postprocessor interface from taking a single file argument to\n * assuming the passed string to be a folder whos contents are to be postprocessed.\n *\/\n \/\/ constructor\n PostProcess(const string &docdir) :\n docdir_(docdir),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false)\n { }\n\n int execute()\n {\n DIR *dp;\n if ((dp = opendir(docdir_.c_str())) == NULL) {\n cerr << \"Error opening directory \" << docdir_ << endl;\n return -1;\n }\n\n struct dirent* dirp;\n string file;\n while ((dirp = readdir(dp)) != NULL) {\n file = string(dirp->d_name);\n \/\/ Process only html files\n if (file.substr(file.find_last_of(\".\") + 1) == \"html\" && file.find(\"8rl\") == string::npos) {\n postprocess(docdir_ + string(\"\/\") + file);\n }\n }\n closedir(dp);\n return 0;\n }\n\n \/\/ run postprocessor\n int postprocess(string file)\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try {\n is.open(file.c_str());\n } catch (std::ifstream::failure e) {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char* buf = new char[(int)(1.1*length)];\n char* p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n \n ofstream fout;\n try {\n fout.open(file.c_str(), ios_base::trunc);\n } catch (std::ofstream::failure e) {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << file << \": PARSE ERROR \" << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string docdir;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n docdir = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n cout << \"Running mtoc++ postprocessor on directory \" << docdir << endl;\n \n PostProcess scanner(docdir);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"1b5f6dd04dd72527537f845e52341d102818b2e8","subject":"substitute all \"::\" by \".\" in the postprocessor...","message":"substitute all \"::\" by \".\" in the postprocessor...\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/postprocess.rl","new_file":"src\/postprocess.rl","new_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n # reconstruct return values\n retvals:= |*\n # matlab identifier (1 return value)\n (IDENT) => { fout.write(ts, te - ts); };\n\n # end list of return values\n '::retssubstituteend' => { fout << \"] =\"; fgoto main; };\n\n # end of return value\n '::retsubstituteend' => { fout << \" =\"; fgoto main; };\n\n # return value separator\n '::' => { fout <<\", \"; };\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US);\n\n '_tsbus_cotm' => { fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('rets::substitutestart::') => { fout << \"function [\"; fgoto retvals; };\n\n # one return value\n ('ret::substitutestart::') => { fout << \"function \"; fgoto retvals; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); };\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:,;_\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>()[\\]{}\\t:;,_\\&]) => {fout << *ts;};\n *|;\n}%%\n\nclass PostProcess\n{\n\npublic:\n \/\/ constructor\n PostProcess(const string & filename) :\n filename_(filename),\n line(1),\n ts(0), te(0), have(0)\n { }\n\n \/\/ run postprocessor\n int execute()\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try\n {\n is.open(filename_.c_str());\n }\n catch (std::ifstream::failure e)\n {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char * buf = new char[(int)(1.1*length)];\n char * p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n\n ofstream fout;\n try\n {\n fout.open(filename_.c_str(), ios_base::trunc);\n }\n catch (std::ofstream::failure e)\n {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << filename_ << \": PARSE ERROR in line \" << line << endl;\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n\nprivate:\n string filename_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n \/*int top;\n int stack[5];*\/\n\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string filename;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n filename = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n PostProcess scanner(filename);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","old_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n # reconstruct return values\n retvals:= |*\n # matlab identifier (1 return value)\n (IDENT) => { fout.write(ts, te - ts); };\n\n # end list of return values\n '::retssubstituteend' => { fout << \"] =\"; fgoto main; };\n\n # end of return value\n '::retsubstituteend' => { fout << \" =\"; fgoto main; };\n\n # return value separator\n '::' => { fout <<\", \"; };\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US);\n\n '_tsbus_cotm' => { fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('rets::substitutestart::') => { fout << \"function [\"; fgoto retvals; };\n\n # one return value\n ('ret::substitutestart::') => { fout << \"function \"; fgoto retvals; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # a word\n (any - [\\n <>()[\\]{}\\&:;_\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>()[\\]{}\\t:;_\\&]) => {fout << *ts;};\n *|;\n}%%\n\nclass PostProcess\n{\n\npublic:\n \/\/ constructor\n PostProcess(const string & filename) :\n filename_(filename),\n line(1),\n ts(0), te(0), have(0)\n { }\n\n \/\/ run postprocessor\n int execute()\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try\n {\n is.open(filename_.c_str());\n }\n catch (std::ifstream::failure e)\n {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char * buf = new char[(int)(1.1*length)];\n char * p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n\n ofstream fout;\n try\n {\n fout.open(filename_.c_str(), ios_base::trunc);\n }\n catch (std::ofstream::failure e)\n {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << filename_ << \": PARSE ERROR in line \" << line << endl;\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n\nprivate:\n string filename_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n \/*int top;\n int stack[5];*\/\n\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string filename;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n filename = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n PostProcess scanner(filename);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"453abcae548c39dcfaae37929eeef4d83a61740e","subject":"break set_document deps on set temporarily","message":"break set_document deps on set temporarily\n","repos":"nbargnesi\/bel-parser,OpenBEL\/bel_parser,nbargnesi\/bel-parser,nbargnesi\/bel-parser,OpenBEL\/bel_parser,OpenBEL\/bel_parser","old_file":"lib\/bel_parser\/parsers\/bel_script\/set_document.rl","new_file":"lib\/bel_parser\/parsers\/bel_script\/set_document.rl","new_contents":"# begin: ragel\n=begin\n%%{\n machine bel;\n\n include 'set.rl';\n\n DOCUMENT_KW = [dD][oO][cC][uU][mM][eE][nN][tT];\n\n action yield_document_property {\n yield(\n document_property(\n *@buffers[:set].children))\n }\n\n set_document :=\n SET_KW\n SP+\n DOCUMENT_KW\n SP+\n an_ident\n SP+\n EQL\n SP+\n (\n a_string |\n a_list |\n an_ident\n ) NL @yield_document_property;\n}%%\n=end\n# end: ragel\n\nrequire_relative '..\/ast\/node'\nrequire_relative '..\/mixin\/buffer'\nrequire_relative '..\/nonblocking_io_wrapper'\n\nmodule BELParser\n module Parsers\n module BELScript\n module SetDocument\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def parse(content)\n return nil unless content\n\n Parser.new(content).each do |obj|\n yield obj\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n include BELParser::Parsers::Buffer\n include BELParser::Parsers::AST::Sexp\n\n def initialize(content)\n @content = content\n # begin: ragel\n %% write data;\n # end: ragel\n end\n\n def each\n @buffers = {}\n @incomplete = {}\n data = @content.unpack('C*')\n p = 0\n pe = data.length\n eof = data.length\n\n # begin: ragel\n %% write init;\n %% write exec;\n # end: ragel\n end\n end\n end\n end\n end\nend\n\nif __FILE__ == $0\n $stdin.each_line do |line|\n BELParser::Parsers::BELScript::SetDocument.parse(line) { |obj|\n puts obj.inspect\n }\n end\nend\n\n# vim: ft=ruby ts=2 sw=2:\n# encoding: utf-8\n","old_contents":"# begin: ragel\n=begin\n%%{\n machine bel;\n\n include 'set.rl';\n\n DOCUMENT_KW = [dD][oO][cC][uU][mM][eE][nN][tT];\n\n action yield_document_property {\n yield(\n document_property(\n *@buffers[:set].children))\n }\n\n set_document :=\n SET_KW %set_keyword\n SP+\n DOCUMENT_KW\n SP+\n an_ident %name\n SP+\n EQL\n SP+\n (\n a_string %string_value |\n a_list %list_value |\n an_ident %ident_value\n ) NL @yield_document_property;\n}%%\n=end\n# end: ragel\n\nrequire_relative '..\/ast\/node'\nrequire_relative '..\/mixin\/buffer'\nrequire_relative '..\/nonblocking_io_wrapper'\n\nmodule BELParser\n module Parsers\n module BELScript\n module SetDocument\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def parse(content)\n return nil unless content\n\n Parser.new(content).each do |obj|\n yield obj\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n include BELParser::Parsers::Buffer\n include BELParser::Parsers::AST::Sexp\n\n def initialize(content)\n @content = content\n # begin: ragel\n %% write data;\n # end: ragel\n end\n\n def each\n @buffers = {}\n @incomplete = {}\n data = @content.unpack('C*')\n p = 0\n pe = data.length\n eof = data.length\n\n # begin: ragel\n %% write init;\n %% write exec;\n # end: ragel\n end\n end\n end\n end\n end\nend\n\nif __FILE__ == $0\n $stdin.each_line do |line|\n BELParser::Parsers::BELScript::SetDocument.parse(line) { |obj|\n puts obj.inspect\n }\n end\nend\n\n# vim: ft=ruby ts=2 sw=2:\n# encoding: utf-8\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"0cb722d69d24313b654de1bae82eb9fd2e118103","subject":"Finished SBC (illegal opcode addition 0xEB).","message":"Finished SBC (illegal opcode addition 0xEB).\n","repos":"cacciatc\/old_happiNES,cacciatc\/old_happiNES","old_file":"src\/2a03.rl","new_file":"src\/2a03.rl","new_contents":"\n#include \n#include \n\n#define PAGE_SIZE 256\n#define MY_STACK_SIZE 256\n#define RAM_SIZE 65535\n#define STACK_OFFSET 4096 \/\/7FFFF?\n\n#define IRQ 65534\n\n\/*memory*\/\nunsigned char m[RAM_SIZE];\n\/*registers*\/\nunsigned char y_register;\nunsigned char x_register;\nunsigned char a_register;\n\/*stack pointer*\/\nunsigned char pstack;\n\/*status flags*\/\nunsigned char status;\n\n\/*ragel specific vars*\/\nint cs;\n\/*pointer to current input*\/\nunsigned char *p;\n\/*pointer to the end of input*\/\nunsigned char *pe;\n \n\/*argugment count for opcodes*\/\nint arg_count = 0;\n\/*current number of cycles*\/\nint cycles = 0;\n\/*current opcode*\/\nunsigned char current_op= 0;\n\/*used for timing*\/\nint interrupt_period = 100;\n\n\/*memory functions*\/\nint read_memory(short address){\n return m[address];\n}\nvoid write_memory(short address,unsigned char value){\n m[address] = value;\n}\n\/*stack functions*\/\nvoid push(unsigned char value){\n m[pstack + STACK_OFFSET] = value;\n pstack -= 1;\n}\nunsigned char pop(){\n\tpstack += 1;\n return m[pstack + STACK_OFFSET];;\n}\n\n\/*addressing modes*\/\n\/*each function returns an adress*\/\nshort zero_page(unsigned char zero_page_address){\n return (zero_page_address);\n}\nshort zero_page_x(unsigned char zero_page_address){\n return ((zero_page_address + x_register));\n}\nshort zero_page_y(unsigned char zero_page_address){\n return ((zero_page_address + y_register));\n}\n\nshort relative(char offset){\n return (p+offset);\n}\n\nshort absolute(unsigned char most_sig_byte, unsigned char least_sig_byte){\n return ((most_sig_byte*(2^8)) + least_sig_byte);\n}\nshort absolute_x(unsigned char most_sig_byte, unsigned char least_sig_byte){\n return ((most_sig_byte*(2^8)) + least_sig_byte + x_register);\n}\nshort absolute_y(unsigned char most_sig_byte, unsigned char least_sig_byte){\n return ((most_sig_byte*(2^8)) + least_sig_byte + y_register);\n}\n\nshort indirect(unsigned char most_sig_byte, unsigned char least_sig_byte){\n unsigned char address_least = read_memory((most_sig_byte*(2^8)) + least_sig_byte);\n unsigned char address_most = read_memory((most_sig_byte*(2^8)) + least_sig_byte + 1);\n return ((address_most*(2^8)) + address_least);\n}\n\nshort indexed_indirect(unsigned char zero_page_address){\n unsigned char least_sig_byte = read_memory(zero_page_address + x_register);\n return (least_sig_byte);\n}\n\nshort indirect_indexed(unsigned char zero_page_address){\n unsigned char least_sig_byte = read_memory(zero_page_address);\n return ((y_register*(2^8)) + least_sig_byte);\n}\n\n\/*status functions*\/\n\/*first set are accessing flags, and the second are for testing if the flags should be set*\/\nvoid set_negative_flag(){\n status |= (1 << 7);\n}\nvoid clear_negative_flag(){\n\tstatus &= ~(1 << 7);\n}\nint get_negative_flag(){\n return (0x80 & status) == 0x80 ? 1 : 0;\n}\nvoid set_overflow_flag(){\n status |= (1 << 6);\n}\nvoid clear_overflow_flag(){\n\tstatus &= ~(1 << 6);\n}\nint get_overflow_flag(){\n return (0x40 & status) == 0x40 ? 1 : 0;\n}\nvoid set_break_flag(){\n status |= (1 << 4);\n}\nvoid clear_break_flag(){\n\tstatus &= ~(1 << 4);\n}\nint get_break_flag(){\n return (0x10 & status) == 0x10 ? 1 : 0;\n}\nvoid set_decimal_mode_flag(){\n status |= (1 << 3);\n}\nvoid clear_decimal_flag(){\n\tstatus &= ~(1 << 3);\n}\nint get_decimal_mode_flag(){\n return (0x08 & status) == 0x08 ? 1 : 0;\n}\nvoid set_interrupt_disable_flag(){\n status |= (1 << 2);\n}\nvoid clear_interrupt_disable_flag(){\n\tstatus &= ~(1 << 2);\n}\nint get_interrupt_disable_flag(){\n return (0x04 & status) == 0x04 ? 1 : 0;\n}\nvoid set_zero_flag(){\n status |= (1 << 1);\n}\nvoid clear_zero_flag(){\n\tstatus &= ~(1 << 1);\n}\nint get_zero_flag(){\n return (0x02 & status) == 0x02 ? 1 : 0;\n}\nvoid set_carry_flag(){\n status |= (1 << 0);\n}\nvoid clear_carry_flag(){\n\tstatus &= ~(1 << 0);\n}\nint get_carry_flag(){\n return (0x01 & status) == 0x01 ? 1 : 0;\n}\n\nvoid check_for_zero(unsigned char value){\n if(!value){\n set_zero_flag();\n }\n\telse\n\t\tclear_zero_flag();\n}\nvoid check_for_negative(unsigned char value){\n if((value & (1 << 7))){\n set_negative_flag();\n }\n\telse\n\t\tclear_negative_flag();\n}\nvoid check_for_overflow(unsigned char value){\n if((value & (1 << 6))){\n set_overflow_flag();\n }\n\telse\n\t\tclear_overflow_flag();\n}\nvoid check_for_carry(unsigned char value1,unsigned char value2){\n\tif( (value1 & (1 << 7))^(value2 & (1 << 7)) ){\n \tset_carry_flag();\n \t}\n\telse\n\t\tclear_carry_flag();\n}\n\n%%{\n machine cpu;\n alphtype unsigned char;\n \n #actions\n ##system functions\n action no_operation {\n cycles -= 2;\n }\n \n action double_no_operation {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0x80 :\n cycles -= 2;\n break;\n case 0x82 :\n cycles -= 2;\n break;\n case 0x89 :\n cycles -= 2;\n break;\n case 0xC2 :\n cycles -= 2;\n break;\n case 0xE2 :\n cycles -= 2;\n break;\n case 0x04 :\n cycles -= 3;\n break;\n case 0x44 :\n cycles -= 3;\n break;\n case 0x64 :\n cycles -= 3;\n break;\n default :\n cycles -= 4;\n }\n }\n \n action triple_no_operation {\n current_op = *(p-arg_count);\n unsigned char most_sig = *(p-arg_count+2);\n unsigned char least_sig = *(p-arg_count+1); \n switch(current_op){\n case 0x0C :\n cycles -= 4;\n break;\n default :\n cycles -= (4 + (absolute_x(most_sig,least_sig) > PAGE_SIZE ? 1 : 0));\n }\n }\n \n action brk {\n \/*push program counter and status*\/\n push(p);\n push(status);\n \/*load interrupt vector*\/\n \/\/p = read_memory(IRQ);\n \/\/status = read_memory(IRQ+1);\n set_break_flag();\n cycles -= 7;\n }\n \n action return_from_interrupt {\n \/*pop status and pc*\/\n status = pop();\n p = pop();\n cycles -= 6;\n }\n \n ##load and store instructions\n action load_accumulator {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0xA9 :\n \/*immediate*\/\n a_register = (*p);\n cycles -= 2;\n break;\n case 0xA5 :\n a_register = read_memory(zero_page(*p));\n cycles -= 3;\n break;\n case 0xB5 :\n a_register = read_memory(zero_page_x(*p));\n cycles -= 4;\n break;\n case 0xAD :\n a_register = read_memory(absolute(*p,*(p-1)));\n cycles -= 4;\n break;\n case 0xBD :\n a_register = read_memory(absolute_x(*p,*(p-1)));\n cycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n break;\n case 0xB9 :\n a_register = read_memory(absolute_y(*p,*(p-1)));\n cycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n break;\n case 0xA1 :\n a_register = read_memory(indexed_indirect(*p));\n cycles -= 6;\n break;\n case 0xB1 :\n a_register = read_memory(indirect_indexed(*p));\n cycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n }\n check_for_zero(a_register);\n check_for_negative(a_register);\n }\n action load_x {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0xA2 :\n \/*immediate*\/\n x_register = (*p);\n cycles -= 2;\n break;\n case 0xA6 :\n x_register = read_memory(zero_page(*p));\n cycles -= 3;\n break;\n case 0xB6 :\n x_register = read_memory(zero_page_y(*p));\n cycles -= 4;\n break;\n case 0xAE :\n x_register = read_memory(absolute(*p,*(p-1)));\n cycles -= 4;\n break;\n case 0xBE :\n x_register = read_memory(absolute_y(*p,*(p-1)));\n cycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n }\n check_for_zero(x_register);\n check_for_negative(x_register);\n }\n action load_y {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0xA0 :\n \/*immediate*\/\n y_register = (*p);\n cycles -= 2;\n break;\n case 0xA4 :\n y_register = read_memory(zero_page(*p));\n cycles -= 3;\n break;\n case 0xB4 :\n y_register = read_memory(zero_page_x(*p));\n cycles -= 4;\n break;\n case 0xAC :\n y_register = read_memory(absolute(*p,*(p-1)));\n cycles -= 4;\n break;\n case 0xBC :\n y_register = read_memory(absolute_x(*p,*(p-1)));\n cycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n }\n check_for_zero(y_register);\n check_for_negative(y_register);\n }\n action store_accumulator {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0x85 :\n write_memory(zero_page(*p),a_register);\n cycles -= 3;\n break;\n case 0x95 :\n write_memory(zero_page_x(*p),a_register);\n cycles -= 4;\n break;\n case 0x8D :\n write_memory(absolute(*p,*(p-1)),a_register);\n cycles -= 4;\n break;\n case 0x9D :\n write_memory(absolute_x(*p,*(p-1)),a_register);\n cycles -= 5;\n break;\n case 0x99 :\n write_memory(absolute_y(*p,*(p-1)),a_register);\n cycles -= 5;\n break;\n case 0x81 :\n write_memory(indexed_indirect(*p),a_register);\n cycles -= 6;\n break;\n case 0x91 :\n write_memory(indirect_indexed(*p),a_register);\n cycles -= 6;\n }\n }\n action store_x {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x86 :\n\t\t\t\twrite_memory(zero_page(*p),x_register);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x96 :\n\t\t\t\twrite_memory(zero_page_y(*p),x_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x8E :;\n\t\t\t\twrite_memory(absolute(*p,*(p-1)),x_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t}\n }\n\taction store_y {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x84 :\n\t\t\t\twrite_memory(zero_page(*p),y_register);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x94 :\n\t\t\t\twrite_memory(zero_page_x(*p),y_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x8C :\n\t\t\t\twrite_memory(absolute(*p,*(p-1)),y_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t}\n }\n\taction load_accumulator_and_x {\n\t\t\/*stores result of memory lookup*\/\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0xA7 :\n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xB7 :\n\t\t\t\ttemp = read_memory(zero_page_y(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xAF :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xBF :\n\t\t\t\ttemp = read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xA3 :\n\t\t\t\ttemp = read_memory(indexed_indirect(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0xB3 :\n\t\t\t\ttemp = read_memory(indirect_indexed(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\n\t##register transfer instructions\n\taction transfer_accumulator_to_x {\n\t\tx_register = a_register;\n\t\t\n\t\tcheck_for_zero(x_register);\n\t\tcheck_for_negative(x_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_accumulator_to_y {\n\t\ty_register = a_register;\n\t\t\n\t\tcheck_for_zero(y_register);\n\t\tcheck_for_negative(y_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_x_to_accumulator {\n\t\ta_register = x_register;\n\t\t\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_y_to_accumulator {\n\t\ta_register = y_register;\n\t\t\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t\tcycles -= 2;\n\t}\n\n\t##stack operation instructions\n\taction transfer_stack_to_x {\n\t\tx_register = pstack;\n\n\t\tcheck_for_zero(x_register);\n\t\tcheck_for_negative(x_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_x_to_stack {\n\t\tpstack = x_register;\n\t\tcycles -= 2;\n\t}\n\taction push_accumulator {\n\t\tpush(a_register);\n\t\tcycles -= 3;\n\t}\n\taction push_status {\n\t\tpush(status);\n\t\tcycles -= 3;\n\t}\n\taction pull_accumulator {\n\t\ta_register = pop();\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t\tcycles -= 4;\n\t}\n\taction pull_status {\n\t\tstatus = pop();\n\t\tcycles -= 4;\n\t}\n\n\t##logical instructions\n\taction logical_and {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x29 :\n\t\t\t\ta_register &= (*p);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x25 :\n\t\t\t\ta_register &= read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x35 :\n\t\t\t\ta_register &= read_memory(zero_page_x(*p));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x2D :\n\t\t\t\ta_register &= read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x3D :\n\t\t\t\ta_register &= read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x39 :\t\t\n\t\t\t\ta_register &= read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x21 :\n\t\t\t\ta_register &= read_memory(indirect_indexed(*p));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x31 :\n\t\t\t\ta_register &= read_memory(indexed_indirect(*p));\n\t\t\t\tcycles -= 5 + (indexed_indirect(*p) > PAGE_SIZE ? 1 : 0);\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction logical_eor {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x49 :\n\t\t\t\ta_register ^= (*p);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x45 :\n\t\t\t\ta_register ^= read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x55 :\n\t\t\t\ta_register ^= read_memory(zero_page_x(*p));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x4D :\n\t\t\t\ta_register ^= read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x5D :\n\t\t\t\ta_register ^= read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x59 :\t\t\n\t\t\t\ta_register ^= read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x41 :\n\t\t\t\ta_register ^= read_memory(indirect_indexed(*p));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x51 :\n\t\t\t\ta_register ^= read_memory(indexed_indirect(*p));\n\t\t\t\tcycles -= 6 + (indexed_indirect(*p) > PAGE_SIZE ? 1 : 0);\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction logical_ora {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x09 :\n\t\t\t\ta_register |= (*p);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x05 :\n\t\t\t\ta_register |= read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x15 :\n\t\t\t\ta_register |= read_memory(zero_page_x(*p));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x0D :\n\t\t\t\ta_register |= read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x1D :\n\t\t\t\ta_register |= read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x19 :\t\t\n\t\t\t\ta_register |= read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x01 :\n\t\t\t\ta_register |= read_memory(indirect_indexed(*p));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x11 :\n\t\t\t\ta_register |= read_memory(indexed_indirect(*p));\n\t\t\t\tcycles -= 6 + (indexed_indirect(*p) > PAGE_SIZE ? 1 : 0);\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction logical_bit {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x24 :\n\t\t\t\ttemp = a_register & read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x2C :\n\t\t\t\ttemp = a_register & read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t}\n\t\tcheck_for_zero(temp);\n\t\tcheck_for_negative(temp);\n\t\tcheck_for_overflow(temp);\n\t}\n\taction logical_and_accumulator_with_byte {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x0B :\n\t\t\t\ttemp = a_register & *p;\n\t\t\t\tbreak;\n\t\t\tcase 0x2B :\n\t\t\t\ttemp = a_register & *p;\n\t\t}\n\t\tcycles -= 2;\n\t\tcheck_for_zero(temp);\n\t\tcheck_for_negative(temp);\n\t\tcheck_for_overflow(temp);\n\t}\n\taction logical_and_accumulator_with_x {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\t\t\n\t\ttemp = a_register & x_register;\n switch(current_op){\n\t\t\tcase 0x87 :\n\t\t\t\twrite_memory(zero_page(*p),temp);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x97 :\n\t\t\t\twrite_memory(zero_page_y(*p),temp);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x93 :\n\t\t\t\twrite_memory(indirect_indexed(*p),temp);\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x8F :\n\t\t\t\twrite_memory(absolute(*p,*(p-1)),temp);\n\t\t\t\tcycles -= 4;\n\t\t}\n\t\tcheck_for_zero(temp);\n\t\tcheck_for_negative(temp);\n\t}\n\taction logical_and_accumulator_with_byte_right_rotate{\n\t\t\/*and with byte*\/\n\t\ta_register &= *p;\n\t\t\/*rotate right*\/\n\t\ta_register = a_register>>1;\n\n\t\t\/*undocumented opcode - check nesdev.parodius.com\/undocumented_opcodes.txt*\/\n\t\tif(a_register & (1 << 6)){\n\t\t\tif(a_register & (1 << 5)){\n\t\t\t\tset_carry_flag();\n\t\t\t\tclear_overflow_flag();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tset_carry_flag();\n\t\t\t\tset_overflow_flag();\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(a_register & (1 << 5)){\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t\tset_overflow_flag();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tclear_carry_flag();\n\t\t\t\tclear_overflow_flag();\n\t\t\t}\n\t\t}\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 2;\n\t}\n\taction logical_and_accumulator_with_byte_right_shift{\n\t\tcheck_for_carry(a_register,*p);\t\n\t\t\/*and with byte*\/\n\t\ta_register &= *p;\n\t\t\/*rotate right*\/\n\t\ta_register = a_register>>1;\n\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 2;\n\t}\n\taction logical_and_accumulator_with_byte_store_x {\n\t\t\/*and with byte*\/\n\t\ta_register &= *p;\n\t\tx_register = a_register;\n\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 2;\n\t}\n\taction logical_and_accumulator_with_x_store_memory {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n\t\ttemp = (a_register & x_register) & 0x07;\n switch(current_op){\n\t\t\tcase 0x9F :\n\t\t\t\twrite_memory(absolute_y(*p,*(p-1)),temp);\n\t\t\t\tcycles -= 5;\n\t\t\t\tbreak;\n\t\t\tcase 0x93 :\n\t\t\t\twrite_memory(indirect_indexed(*p),temp);\n\t\t\t\tcycles -= 6;\n\t\t}\n\t}\n\taction logical_and_accumulator_with_x_sub_byte {\n\t\tcheck_for_carry(x_register,*p);\t\n\t\tx_register &= a_register;\n\t\tx_register -= *p;\n\n\t\tcheck_for_negative(x_register);\n\t\tcheck_for_zero(x_register);\n;\n\t\tcycles -= 2;\n\t}\n\taction logical_and_mem_with_stack_pointer {\n\t\tunsigned char temp;\t\t\n\n\t\ttemp = read_memory(absolute_y(*p,*(p-1)));\n\t\ttemp &= pstack;\n\t\ta_register = temp;\n\t\tx_register = temp;\n\t\tpstack = temp;\n\t\t\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t}\n\taction logical_and_high_byte_with_x {\n\t\tx_register &= *(p);\n\t\twrite_memory(absolute_y(*p,*(p-1)),x_register+1);\n\t\tcycles -= 5;\n\t}\n\taction logical_and_high_byte_with_y {\n\t\ty_register &= *(p);\n\t\twrite_memory(absolute_x(*p,*(p-1)),y_register+1);\n\t\tcycles -= 5;\n\t}\n\taction logical_and_x_with_accumulator_store_in_stack {\n\t\tpstack = x_register & a_register;\n\t\twrite_memory(absolute_y(*p,*(p-1)),(pstack & *p) + 1);\t\t\n\t\tcycles -= 5;\n\t}\n\n\t##arithmetic instructions\n\taction add {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0x69 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,*p + get_carry_flag());\n\t\t\t\ta_register += ( (*p) + temp);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x65 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(zero_page(*p)) + temp);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x75 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page_x(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(zero_page_x(*p)) + temp);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x6D :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute(*p,*(p-1))) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(absolute(*p,*(p-1))) + temp);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x7D :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_x(*p,*(p-1))) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(absolute_x(*p,*(p-1))) + temp);\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x79 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_y(*p,*(p-1))) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(absolute_y(*p,*(p-1))) + temp);\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x61 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indexed_indirect(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(indexed_indirect(*p)) + temp);\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x71 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indirect_indexed(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(indirect_indexed(*p)) + temp);\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_overflow(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction subtract {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xE9 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,*p - (1 - get_carry_flag()));\n\t\t\t\ta_register -= ( (*p) - (1 - temp));\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\t\/*illegal opcode, same as 0xE9*\/\n\t\t\tcase 0xEB :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,*p - (1 - get_carry_flag()));\n\t\t\t\ta_register -= ( (*p) - (1 - temp));\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0xE5 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page(*p)) - (1-get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(zero_page(*p)) - (1 - temp));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xF5 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page_x(*p)) -(1 - get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(zero_page_x(*p)) - (1-temp));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xED :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute(*p,*(p-1))) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(absolute(*p,*(p-1))) - (1-temp));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xFD :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_x(*p,*(p-1))) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(absolute_x(*p,*(p-1))) -(1- temp));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xF9 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_y(*p,*(p-1))) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(absolute_y(*p,*(p-1))) - (1-temp));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xE1 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indexed_indirect(*p)) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(indexed_indirect(*p)) -(1- temp));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0xF1 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indirect_indexed(*p)) -(1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(indirect_indexed(*p)) -(1-temp));\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_overflow(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction compare {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xC9 :\n\t\t\t\tif(a_register >= *p){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == *p){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0xC5 :\n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xD5 :\n\t\t\t\ttemp = read_memory(zero_page_x(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xCD :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xDD :\n\t\t\t\ttemp = read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xD9 :\n\t\t\t\ttemp = read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xC1 :\n\t\t\t\ttemp = read_memory(indexed_indirect(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0xD1 :\n\t\t\t\ttemp = read_memory(indirect_indexed(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\t\tcheck_for_negative(a_register);\n\t}\n\taction compare_x {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xE0 :\n\t\t\t\tif(x_register >= *p){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(x_register == *p){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 2;\t\t\t\t\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase 0xE4 : \n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tif(x_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(x_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xEC :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tif(x_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(x_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\t\tcheck_for_negative(x_register);\n\t}\n\taction compare_y {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xC0 :\n\t\t\t\tif(y_register >= *p){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(y_register == *p){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 2;\t\t\t\t\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase 0xC4 : \n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tif(y_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(y_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xCC :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tif(y_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(y_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\t\tcheck_for_negative(y_register);\n\t}\n \n #special actions\n action cyclic_tasks {\n \/*debug code*\/\n \/*int i;\n for(i = arg_count; i >= 0;i--){\n printf(\"0x%.4X \",*(p-i));\n }\n printf(\"\\n\");*\/\n \/*end*\/\n if(cycles <= 0){\n cycles += interrupt_period;\n }\n if(p >= pe)\n exit(0);\n }\n \n #system functions\n NOP = (0x1A | 0x3A| 0x5A | 0x7A | 0xDA | 0xEA | 0xFA) @{arg_count = 0;} @no_operation;\n DOP = ((0x04 | 0x14 | 0x34 | 0x44 | 0x54 | 0x64 | 0x74 | 0x80 | 0x82 | 0x89 | 0xC2 | 0xD4 | 0xE2 | 0xF4) . extend) @{arg_count = 1;} @double_no_operation;\n TOP = ((0x0C | 0x1C | 0x3C | 0x5C | 0x7C | 0xDC | 0xFC) . extend . extend) @{arg_count = 2;} @triple_no_operation;\n BRK = (0x00) @{arg_count = 0;} @brk;\n RTI = (0x40) @{arg_count = 0;} @return_from_interrupt;\n \n #load and store instructions\n\tLAX = ( ((0xA7 | 0xB7 | 0xA3 | 0xB3) . extend) @{arg_count = 1;} | ((0xAF | 0xBF) . extend . extend) @{arg_count = 2;}) @load_accumulator_and_x;\n LDA = ( (((0xA9 | 0xA5 | 0xB5 | 0xA1 | 0xB1) . extend) @{arg_count = 1;}) | (((0xAD | 0xBD | 0xB9) . extend . extend) @{arg_count = 2;}) ) @load_accumulator;\n LDX = ( (((0xA2 | 0xA6 | 0xB6) . extend) @{arg_count = 1;}) | (((0xAE | 0xBE) . extend .extend) @{arg_count = 2;}) ) @load_x;\n LDY = ( (((0xA0 | 0xA4 | 0xB4) . extend) @{arg_count = 1;}) | (((0xAC | 0xBC) . extend .extend) @{arg_count = 2;}) ) @load_y;\n STA = ( (((0x85 | 0x95 | 0x81 | 0x91) .extend) @{arg_count = 1;}) | (((0x8D | 0x9D | 0x99) . extend . extend) @{arg_count = 2;}) ) @store_accumulator; \n STX = ( ((0x86 | 0x96) . extend) @{arg_count = 1;} | ((0x8E) . extend . extend) @{arg_count = 2;}) @store_x;\n\tSTY = ( ((0x84 | 0x94) . extend) @{arg_count = 1;} | ((0x8C) . extend . extend) @{arg_count = 2;}) @store_y;\n\n\t#register transfer instructions\n\tTAX = (0xAA @{arg_count = 0;}) @transfer_accumulator_to_x;\n\tTAY = (0xA8 @{arg_count = 0;}) @transfer_accumulator_to_y;\n\tTXA = (0x8A @{arg_count = 0;}) @transfer_x_to_accumulator;\n\tTYA = (0x98 @{arg_count = 0;}) @transfer_y_to_accumulator;\n\n\t#stack operation instructions\n\tTSX = (0xBA @{arg_count = 0;}) @transfer_stack_to_x;\n\tTXS = (0x9A @{arg_count = 0;}) @transfer_x_to_stack;\n\tPHA = (0x48 @{arg_count = 0;}) @push_accumulator;\n\tPHP = (0x08 @{arg_count = 0;}) @push_status;\n\tPLA = (0x68 @{arg_count = 0;}) @pull_accumulator;\n\tPLP = (0x28 @{arg_count = 0;}) @pull_status;\n\n\t#logical instructions\n AND = (((0x29 | 0x25 | 0x35 | 0x21 | 0x31) . extend) @{arg_count = 1;} | ((0x2D | 0x3D | 0x39) . extend . extend) @{arg_count = 2;}) @logical_and;\n\tEOR = (((0x49 | 0x45 | 0x55 | 0x41 | 0x51) . extend) @{arg_count = 1;} | ((0x4D | 0x5D | 0x59) . extend . extend) @{arg_count = 2;}) @logical_eor;\n\tORA = (((0x09 | 0x05 | 0x15 | 0x01 | 0x11) . extend) @{arg_count = 1;} | ((0x0D | 0x1D | 0x19) . extend . extend) @{arg_count = 2;}) @logical_ora;\n\tBIT = ((0x24 . extend) @{arg_count = 1;} | (0x2C . extend . extend) @{arg_count = 2;}) @logical_bit;\n\tAAC = (((0x0B | 0x2B) . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte;\n\tAAX = (((0x87 | 0x97 | 0x83) . extend) @{arg_count = 1;} | (0x8F . extend . extend) @{arg_count = 2;}) @logical_and_accumulator_with_x;\n\tARR = ((0x6B . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte_right_rotate;\n\tASR = ((0x4B . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte_right_shift;\n\tATX = ((0xAB . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte_store_x;\n\tAXA = ((0x93 . extend) @{arg_count = 1;} | (0x9F . extend . extend) @{arg_count = 2;}) @logical_and_accumulator_with_x_store_memory;\n\tAXS = (0xCB . extend @{arg_count = 1;}) @logical_and_accumulator_with_x_sub_byte;\n\tLAR = (0xBB . extend . extend @{arg_count = 2;}) @logical_and_mem_with_stack_pointer;\n\tSXA = (0x9E . extend . extend @{arg_count = 2;}) @logical_and_high_byte_with_x;\n\tSYA = (0x9C . extend . extend @{arg_count = 2;}) @logical_and_high_byte_with_y;\n\tXAS = (0x9B . extend . extend @{arg_count = 2;}) @logical_and_x_with_accumulator_store_in_stack;\n\n\t#arithmetic instuctions\n\tADC = ((((0x69 | 0x65 | 0x75 | 0x61 | 0x71) . extend) @{arg_count = 1;}) | ((0x6D | 0x7D | 0x79) . extend . extend) @{arg_count = 2;}) @add;\n\tSBC = ((((0xE9 | 0xE5 | 0xF5 | 0xE1 | 0xF1 | 0xEB) . extend) @{arg_count = 1;}) | ((0xED | 0xFD | 0xF9) . extend . extend) @{arg_count = 2;}) @subtract;\n\tCMP = ((((0xC9 | 0xC5 | 0xD5 | 0xC1 | 0xD1) . extend) @{arg_count = 1;}) | ((0xCD | 0xDD | 0xD9) . extend . extend) @{arg_count = 2;}) @compare;\n\tCPX = (((0xE0 | 0xE4) . extend @{arg_count = 1;}) | ((0xEC) . extend . extend @{arg_count = 2;})) @compare_x;\n\tCPY = (((0xC0 | 0xC4) . extend @{arg_count = 1;}) | ((0xCC) . extend . extend @{arg_count = 2;})) @compare_y;\n\n Lexecute = (\n #system functions\n NOP | DOP | TOP | BRK | RTI |\n #load and store instructions\n LAX | LDA | LDX | LDY | STA | STX | STY |\n\t\t#register transfer instructions\n\t\tTAX | TAY | TXA | TYA |\n\t\t#stack operation instructions\n\t\tTSX | TXS | PHA | PHP | PLA | PLP |\n\t\t#logical instructions\n\t\tAND | EOR | ORA | BIT | AAC | AAX | ARR | ASR | ATX | AXA | AXS | LAR | SXA | SYA | XAS |\n\t\t#arithmetic instructions\n\t\tADC | SBC | CMP | CPX | CPY\n );\n \n main := (Lexecute @cyclic_tasks)+;\n \n}%%\n\n%%write data;\n\nint load_rom(char* fname){\n int fsize;\n FILE* fp = fopen(fname,\"rb\");\n if(!fp){\n printf(\"Unable to open ROM!\\n\");\n exit(1);\n }\n fseek(fp,0,SEEK_END);\n fsize = ftell(fp);\n p = (unsigned char*)malloc(sizeof(unsigned char) * fsize);\n fread(p,sizeof(unsigned char),fsize,fp);\n fclose(fp);\n return(fsize);\n}\n\n\/*debug code*\/\nvoid dump_mem(){\n int i,j;\n\tprintf(\"%.2X\\n\",a_register);\n\tprintf(\"%.2X\\n\",x_register);\n\tprintf(\"%.2X\\n\",y_register);\n\tprintf(\"%.2X\\n\",status);\n\n for(i = 0;i= STACK_OFFSET;i--){\n\t\tfprintf(fp,\"%.2X\\n\",m[i]);\n\t}\n\n for(i = 0;i 2){\n\t\t\/*init*\/\n\t\tcycles = interrupt_period;\n\t\tstatus = 0;\n\t\targ_count = 0;\n\t\tpstack = MY_STACK_SIZE-1;\n\t\n\t\t%%write init;\n\t\t\n\t\tload_it(argv[1]);\n\t\t\/\/unsigned char test[] = {0xA9,0x00};\n\t\t\/\/p = test;\n\t\t\/\/pe = test+2;\n\t\t%%write exec;\n\t\t\/\/dump_mem();\n\t\tpack_it(argv[2]);\n\t}\n return 0;\n}\n","old_contents":"\n#include \n#include \n\n#define PAGE_SIZE 256\n#define MY_STACK_SIZE 256\n#define RAM_SIZE 65535\n#define STACK_OFFSET 4096 \/\/7FFFF?\n\n#define IRQ 65534\n\n\/*memory*\/\nunsigned char m[RAM_SIZE];\n\/*registers*\/\nunsigned char y_register;\nunsigned char x_register;\nunsigned char a_register;\n\/*stack pointer*\/\nunsigned char pstack;\n\/*status flags*\/\nunsigned char status;\n\n\/*ragel specific vars*\/\nint cs;\n\/*pointer to current input*\/\nunsigned char *p;\n\/*pointer to the end of input*\/\nunsigned char *pe;\n \n\/*argugment count for opcodes*\/\nint arg_count = 0;\n\/*current number of cycles*\/\nint cycles = 0;\n\/*current opcode*\/\nunsigned char current_op= 0;\n\/*used for timing*\/\nint interrupt_period = 100;\n\n\/*memory functions*\/\nint read_memory(short address){\n return m[address];\n}\nvoid write_memory(short address,unsigned char value){\n m[address] = value;\n}\n\/*stack functions*\/\nvoid push(unsigned char value){\n m[pstack + STACK_OFFSET] = value;\n pstack -= 1;\n}\nunsigned char pop(){\n\tpstack += 1;\n return m[pstack + STACK_OFFSET];;\n}\n\n\/*addressing modes*\/\n\/*each function returns an adress*\/\nshort zero_page(unsigned char zero_page_address){\n return (zero_page_address);\n}\nshort zero_page_x(unsigned char zero_page_address){\n return ((zero_page_address + x_register));\n}\nshort zero_page_y(unsigned char zero_page_address){\n return ((zero_page_address + y_register));\n}\n\nshort relative(char offset){\n return (p+offset);\n}\n\nshort absolute(unsigned char most_sig_byte, unsigned char least_sig_byte){\n return ((most_sig_byte*(2^8)) + least_sig_byte);\n}\nshort absolute_x(unsigned char most_sig_byte, unsigned char least_sig_byte){\n return ((most_sig_byte*(2^8)) + least_sig_byte + x_register);\n}\nshort absolute_y(unsigned char most_sig_byte, unsigned char least_sig_byte){\n return ((most_sig_byte*(2^8)) + least_sig_byte + y_register);\n}\n\nshort indirect(unsigned char most_sig_byte, unsigned char least_sig_byte){\n unsigned char address_least = read_memory((most_sig_byte*(2^8)) + least_sig_byte);\n unsigned char address_most = read_memory((most_sig_byte*(2^8)) + least_sig_byte + 1);\n return ((address_most*(2^8)) + address_least);\n}\n\nshort indexed_indirect(unsigned char zero_page_address){\n unsigned char least_sig_byte = read_memory(zero_page_address + x_register);\n return (least_sig_byte);\n}\n\nshort indirect_indexed(unsigned char zero_page_address){\n unsigned char least_sig_byte = read_memory(zero_page_address);\n return ((y_register*(2^8)) + least_sig_byte);\n}\n\n\/*status functions*\/\n\/*first set are accessing flags, and the second are for testing if the flags should be set*\/\nvoid set_negative_flag(){\n status |= (1 << 7);\n}\nvoid clear_negative_flag(){\n\tstatus &= ~(1 << 7);\n}\nint get_negative_flag(){\n return (0x80 & status) == 0x80 ? 1 : 0;\n}\nvoid set_overflow_flag(){\n status |= (1 << 6);\n}\nvoid clear_overflow_flag(){\n\tstatus &= ~(1 << 6);\n}\nint get_overflow_flag(){\n return (0x40 & status) == 0x40 ? 1 : 0;\n}\nvoid set_break_flag(){\n status |= (1 << 4);\n}\nvoid clear_break_flag(){\n\tstatus &= ~(1 << 4);\n}\nint get_break_flag(){\n return (0x10 & status) == 0x10 ? 1 : 0;\n}\nvoid set_decimal_mode_flag(){\n status |= (1 << 3);\n}\nvoid clear_decimal_flag(){\n\tstatus &= ~(1 << 3);\n}\nint get_decimal_mode_flag(){\n return (0x08 & status) == 0x08 ? 1 : 0;\n}\nvoid set_interrupt_disable_flag(){\n status |= (1 << 2);\n}\nvoid clear_interrupt_disable_flag(){\n\tstatus &= ~(1 << 2);\n}\nint get_interrupt_disable_flag(){\n return (0x04 & status) == 0x04 ? 1 : 0;\n}\nvoid set_zero_flag(){\n status |= (1 << 1);\n}\nvoid clear_zero_flag(){\n\tstatus &= ~(1 << 1);\n}\nint get_zero_flag(){\n return (0x02 & status) == 0x02 ? 1 : 0;\n}\nvoid set_carry_flag(){\n status |= (1 << 0);\n}\nvoid clear_carry_flag(){\n\tstatus &= ~(1 << 0);\n}\nint get_carry_flag(){\n return (0x01 & status) == 0x01 ? 1 : 0;\n}\n\nvoid check_for_zero(unsigned char value){\n if(!value){\n set_zero_flag();\n }\n\telse\n\t\tclear_zero_flag();\n}\nvoid check_for_negative(unsigned char value){\n if((value & (1 << 7))){\n set_negative_flag();\n }\n\telse\n\t\tclear_negative_flag();\n}\nvoid check_for_overflow(unsigned char value){\n if((value & (1 << 6))){\n set_overflow_flag();\n }\n\telse\n\t\tclear_overflow_flag();\n}\nvoid check_for_carry(unsigned char value1,unsigned char value2){\n\tif( (value1 & (1 << 7))^(value2 & (1 << 7)) ){\n \tset_carry_flag();\n \t}\n\telse\n\t\tclear_carry_flag();\n}\n\n%%{\n machine cpu;\n alphtype unsigned char;\n \n #actions\n ##system functions\n action no_operation {\n cycles -= 2;\n }\n \n action double_no_operation {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0x80 :\n cycles -= 2;\n break;\n case 0x82 :\n cycles -= 2;\n break;\n case 0x89 :\n cycles -= 2;\n break;\n case 0xC2 :\n cycles -= 2;\n break;\n case 0xE2 :\n cycles -= 2;\n break;\n case 0x04 :\n cycles -= 3;\n break;\n case 0x44 :\n cycles -= 3;\n break;\n case 0x64 :\n cycles -= 3;\n break;\n default :\n cycles -= 4;\n }\n }\n \n action triple_no_operation {\n current_op = *(p-arg_count);\n unsigned char most_sig = *(p-arg_count+2);\n unsigned char least_sig = *(p-arg_count+1); \n switch(current_op){\n case 0x0C :\n cycles -= 4;\n break;\n default :\n cycles -= (4 + (absolute_x(most_sig,least_sig) > PAGE_SIZE ? 1 : 0));\n }\n }\n \n action brk {\n \/*push program counter and status*\/\n push(p);\n push(status);\n \/*load interrupt vector*\/\n \/\/p = read_memory(IRQ);\n \/\/status = read_memory(IRQ+1);\n set_break_flag();\n cycles -= 7;\n }\n \n action return_from_interrupt {\n \/*pop status and pc*\/\n status = pop();\n p = pop();\n cycles -= 6;\n }\n \n ##load and store instructions\n action load_accumulator {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0xA9 :\n \/*immediate*\/\n a_register = (*p);\n cycles -= 2;\n break;\n case 0xA5 :\n a_register = read_memory(zero_page(*p));\n cycles -= 3;\n break;\n case 0xB5 :\n a_register = read_memory(zero_page_x(*p));\n cycles -= 4;\n break;\n case 0xAD :\n a_register = read_memory(absolute(*p,*(p-1)));\n cycles -= 4;\n break;\n case 0xBD :\n a_register = read_memory(absolute_x(*p,*(p-1)));\n cycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n break;\n case 0xB9 :\n a_register = read_memory(absolute_y(*p,*(p-1)));\n cycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n break;\n case 0xA1 :\n a_register = read_memory(indexed_indirect(*p));\n cycles -= 6;\n break;\n case 0xB1 :\n a_register = read_memory(indirect_indexed(*p));\n cycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n }\n check_for_zero(a_register);\n check_for_negative(a_register);\n }\n action load_x {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0xA2 :\n \/*immediate*\/\n x_register = (*p);\n cycles -= 2;\n break;\n case 0xA6 :\n x_register = read_memory(zero_page(*p));\n cycles -= 3;\n break;\n case 0xB6 :\n x_register = read_memory(zero_page_y(*p));\n cycles -= 4;\n break;\n case 0xAE :\n x_register = read_memory(absolute(*p,*(p-1)));\n cycles -= 4;\n break;\n case 0xBE :\n x_register = read_memory(absolute_y(*p,*(p-1)));\n cycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n }\n check_for_zero(x_register);\n check_for_negative(x_register);\n }\n action load_y {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0xA0 :\n \/*immediate*\/\n y_register = (*p);\n cycles -= 2;\n break;\n case 0xA4 :\n y_register = read_memory(zero_page(*p));\n cycles -= 3;\n break;\n case 0xB4 :\n y_register = read_memory(zero_page_x(*p));\n cycles -= 4;\n break;\n case 0xAC :\n y_register = read_memory(absolute(*p,*(p-1)));\n cycles -= 4;\n break;\n case 0xBC :\n y_register = read_memory(absolute_x(*p,*(p-1)));\n cycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n }\n check_for_zero(y_register);\n check_for_negative(y_register);\n }\n action store_accumulator {\n current_op = *(p-arg_count);\n switch(current_op){\n case 0x85 :\n write_memory(zero_page(*p),a_register);\n cycles -= 3;\n break;\n case 0x95 :\n write_memory(zero_page_x(*p),a_register);\n cycles -= 4;\n break;\n case 0x8D :\n write_memory(absolute(*p,*(p-1)),a_register);\n cycles -= 4;\n break;\n case 0x9D :\n write_memory(absolute_x(*p,*(p-1)),a_register);\n cycles -= 5;\n break;\n case 0x99 :\n write_memory(absolute_y(*p,*(p-1)),a_register);\n cycles -= 5;\n break;\n case 0x81 :\n write_memory(indexed_indirect(*p),a_register);\n cycles -= 6;\n break;\n case 0x91 :\n write_memory(indirect_indexed(*p),a_register);\n cycles -= 6;\n }\n }\n action store_x {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x86 :\n\t\t\t\twrite_memory(zero_page(*p),x_register);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x96 :\n\t\t\t\twrite_memory(zero_page_y(*p),x_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x8E :;\n\t\t\t\twrite_memory(absolute(*p,*(p-1)),x_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t}\n }\n\taction store_y {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x84 :\n\t\t\t\twrite_memory(zero_page(*p),y_register);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x94 :\n\t\t\t\twrite_memory(zero_page_x(*p),y_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x8C :\n\t\t\t\twrite_memory(absolute(*p,*(p-1)),y_register);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t}\n }\n\taction load_accumulator_and_x {\n\t\t\/*stores result of memory lookup*\/\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0xA7 :\n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xB7 :\n\t\t\t\ttemp = read_memory(zero_page_y(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xAF :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xBF :\n\t\t\t\ttemp = read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xA3 :\n\t\t\t\ttemp = read_memory(indexed_indirect(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0xB3 :\n\t\t\t\ttemp = read_memory(indirect_indexed(*p));\n\t\t\t\tx_register = temp;\n\t\t\t\ta_register = temp;\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\n\t##register transfer instructions\n\taction transfer_accumulator_to_x {\n\t\tx_register = a_register;\n\t\t\n\t\tcheck_for_zero(x_register);\n\t\tcheck_for_negative(x_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_accumulator_to_y {\n\t\ty_register = a_register;\n\t\t\n\t\tcheck_for_zero(y_register);\n\t\tcheck_for_negative(y_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_x_to_accumulator {\n\t\ta_register = x_register;\n\t\t\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_y_to_accumulator {\n\t\ta_register = y_register;\n\t\t\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t\tcycles -= 2;\n\t}\n\n\t##stack operation instructions\n\taction transfer_stack_to_x {\n\t\tx_register = pstack;\n\n\t\tcheck_for_zero(x_register);\n\t\tcheck_for_negative(x_register);\n\t\tcycles -= 2;\n\t}\n\taction transfer_x_to_stack {\n\t\tpstack = x_register;\n\t\tcycles -= 2;\n\t}\n\taction push_accumulator {\n\t\tpush(a_register);\n\t\tcycles -= 3;\n\t}\n\taction push_status {\n\t\tpush(status);\n\t\tcycles -= 3;\n\t}\n\taction pull_accumulator {\n\t\ta_register = pop();\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t\tcycles -= 4;\n\t}\n\taction pull_status {\n\t\tstatus = pop();\n\t\tcycles -= 4;\n\t}\n\n\t##logical instructions\n\taction logical_and {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x29 :\n\t\t\t\ta_register &= (*p);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x25 :\n\t\t\t\ta_register &= read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x35 :\n\t\t\t\ta_register &= read_memory(zero_page_x(*p));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x2D :\n\t\t\t\ta_register &= read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x3D :\n\t\t\t\ta_register &= read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x39 :\t\t\n\t\t\t\ta_register &= read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x21 :\n\t\t\t\ta_register &= read_memory(indirect_indexed(*p));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x31 :\n\t\t\t\ta_register &= read_memory(indexed_indirect(*p));\n\t\t\t\tcycles -= 5 + (indexed_indirect(*p) > PAGE_SIZE ? 1 : 0);\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction logical_eor {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x49 :\n\t\t\t\ta_register ^= (*p);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x45 :\n\t\t\t\ta_register ^= read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x55 :\n\t\t\t\ta_register ^= read_memory(zero_page_x(*p));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x4D :\n\t\t\t\ta_register ^= read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x5D :\n\t\t\t\ta_register ^= read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x59 :\t\t\n\t\t\t\ta_register ^= read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x41 :\n\t\t\t\ta_register ^= read_memory(indirect_indexed(*p));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x51 :\n\t\t\t\ta_register ^= read_memory(indexed_indirect(*p));\n\t\t\t\tcycles -= 6 + (indexed_indirect(*p) > PAGE_SIZE ? 1 : 0);\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction logical_ora {\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x09 :\n\t\t\t\ta_register |= (*p);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x05 :\n\t\t\t\ta_register |= read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x15 :\n\t\t\t\ta_register |= read_memory(zero_page_x(*p));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x0D :\n\t\t\t\ta_register |= read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x1D :\n\t\t\t\ta_register |= read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x19 :\t\t\n\t\t\t\ta_register |= read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x01 :\n\t\t\t\ta_register |= read_memory(indirect_indexed(*p));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x11 :\n\t\t\t\ta_register |= read_memory(indexed_indirect(*p));\n\t\t\t\tcycles -= 6 + (indexed_indirect(*p) > PAGE_SIZE ? 1 : 0);\n\t\t}\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction logical_bit {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x24 :\n\t\t\t\ttemp = a_register & read_memory(zero_page(*p));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x2C :\n\t\t\t\ttemp = a_register & read_memory(absolute(*p,*(p-1)));\n\t\t\t\tcycles -= 4;\n\t\t}\n\t\tcheck_for_zero(temp);\n\t\tcheck_for_negative(temp);\n\t\tcheck_for_overflow(temp);\n\t}\n\taction logical_and_accumulator_with_byte {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n switch(current_op){\n\t\t\tcase 0x0B :\n\t\t\t\ttemp = a_register & *p;\n\t\t\t\tbreak;\n\t\t\tcase 0x2B :\n\t\t\t\ttemp = a_register & *p;\n\t\t}\n\t\tcycles -= 2;\n\t\tcheck_for_zero(temp);\n\t\tcheck_for_negative(temp);\n\t\tcheck_for_overflow(temp);\n\t}\n\taction logical_and_accumulator_with_x {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\t\t\n\t\ttemp = a_register & x_register;\n switch(current_op){\n\t\t\tcase 0x87 :\n\t\t\t\twrite_memory(zero_page(*p),temp);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x97 :\n\t\t\t\twrite_memory(zero_page_y(*p),temp);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x93 :\n\t\t\t\twrite_memory(indirect_indexed(*p),temp);\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x8F :\n\t\t\t\twrite_memory(absolute(*p,*(p-1)),temp);\n\t\t\t\tcycles -= 4;\n\t\t}\n\t\tcheck_for_zero(temp);\n\t\tcheck_for_negative(temp);\n\t}\n\taction logical_and_accumulator_with_byte_right_rotate{\n\t\t\/*and with byte*\/\n\t\ta_register &= *p;\n\t\t\/*rotate right*\/\n\t\ta_register = a_register>>1;\n\n\t\t\/*undocumented opcode - check nesdev.parodius.com\/undocumented_opcodes.txt*\/\n\t\tif(a_register & (1 << 6)){\n\t\t\tif(a_register & (1 << 5)){\n\t\t\t\tset_carry_flag();\n\t\t\t\tclear_overflow_flag();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tset_carry_flag();\n\t\t\t\tset_overflow_flag();\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(a_register & (1 << 5)){\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t\tset_overflow_flag();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tclear_carry_flag();\n\t\t\t\tclear_overflow_flag();\n\t\t\t}\n\t\t}\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 2;\n\t}\n\taction logical_and_accumulator_with_byte_right_shift{\n\t\tcheck_for_carry(a_register,*p);\t\n\t\t\/*and with byte*\/\n\t\ta_register &= *p;\n\t\t\/*rotate right*\/\n\t\ta_register = a_register>>1;\n\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 2;\n\t}\n\taction logical_and_accumulator_with_byte_store_x {\n\t\t\/*and with byte*\/\n\t\ta_register &= *p;\n\t\tx_register = a_register;\n\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 2;\n\t}\n\taction logical_and_accumulator_with_x_store_memory {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n\t\ttemp = (a_register & x_register) & 0x07;\n switch(current_op){\n\t\t\tcase 0x9F :\n\t\t\t\twrite_memory(absolute_y(*p,*(p-1)),temp);\n\t\t\t\tcycles -= 5;\n\t\t\t\tbreak;\n\t\t\tcase 0x93 :\n\t\t\t\twrite_memory(indirect_indexed(*p),temp);\n\t\t\t\tcycles -= 6;\n\t\t}\n\t}\n\taction logical_and_accumulator_with_x_sub_byte {\n\t\tcheck_for_carry(x_register,*p);\t\n\t\tx_register &= a_register;\n\t\tx_register -= *p;\n\n\t\tcheck_for_negative(x_register);\n\t\tcheck_for_zero(x_register);\n;\n\t\tcycles -= 2;\n\t}\n\taction logical_and_mem_with_stack_pointer {\n\t\tunsigned char temp;\t\t\n\n\t\ttemp = read_memory(absolute_y(*p,*(p-1)));\n\t\ttemp &= pstack;\n\t\ta_register = temp;\n\t\tx_register = temp;\n\t\tpstack = temp;\n\t\t\n\t\tcheck_for_negative(a_register);\n\t\tcheck_for_zero(a_register);\n\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t}\n\taction logical_and_high_byte_with_x {\n\t\tx_register &= *(p);\n\t\twrite_memory(absolute_y(*p,*(p-1)),x_register+1);\n\t\tcycles -= 5;\n\t}\n\taction logical_and_high_byte_with_y {\n\t\ty_register &= *(p);\n\t\twrite_memory(absolute_x(*p,*(p-1)),y_register+1);\n\t\tcycles -= 5;\n\t}\n\taction logical_and_x_with_accumulator_store_in_stack {\n\t\tpstack = x_register & a_register;\n\t\twrite_memory(absolute_y(*p,*(p-1)),(pstack & *p) + 1);\t\t\n\t\tcycles -= 5;\n\t}\n\n\t##arithmetic instructions\n\taction add {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0x69 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,*p + get_carry_flag());\n\t\t\t\ta_register += ( (*p) + temp);\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0x65 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(zero_page(*p)) + temp);\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0x75 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page_x(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(zero_page_x(*p)) + temp);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x6D :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute(*p,*(p-1))) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(absolute(*p,*(p-1))) + temp);\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0x7D :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_x(*p,*(p-1))) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(absolute_x(*p,*(p-1))) + temp);\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x79 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_y(*p,*(p-1))) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(absolute_y(*p,*(p-1))) + temp);\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0x61 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indexed_indirect(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(indexed_indirect(*p)) + temp);\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0x71 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indirect_indexed(*p)) + get_carry_flag());\n\t\t\t\ta_register += (read_memory(indirect_indexed(*p)) + temp);\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_overflow(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction subtract {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xE9 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,*p - (1 - get_carry_flag()));\n\t\t\t\ta_register -= ( (*p) - (1 - temp));\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0xE5 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page(*p)) - (1-get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(zero_page(*p)) - (1 - temp));\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xF5 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(zero_page_x(*p)) -(1 - get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(zero_page_x(*p)) - (1-temp));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xED :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute(*p,*(p-1))) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(absolute(*p,*(p-1))) - (1-temp));\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xFD :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_x(*p,*(p-1))) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(absolute_x(*p,*(p-1))) -(1- temp));\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xF9 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(absolute_y(*p,*(p-1))) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(absolute_y(*p,*(p-1))) - (1-temp));\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xE1 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indexed_indirect(*p)) - (1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(indexed_indirect(*p)) -(1- temp));\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0xF1 :\n\t\t\t\ttemp = get_carry_flag();\n\t\t\t\tcheck_for_carry(a_register,read_memory(indirect_indexed(*p)) -(1- get_carry_flag()));\n\t\t\t\ta_register -= (read_memory(indirect_indexed(*p)) -(1-temp));\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\n\t\tcheck_for_zero(a_register);\n\t\tcheck_for_overflow(a_register);\n\t\tcheck_for_negative(a_register);\n\t}\n\taction compare {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xC9 :\n\t\t\t\tif(a_register >= *p){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == *p){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 2;\n\t\t\t\tbreak;\n\t\t\tcase 0xC5 :\n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xD5 :\n\t\t\t\ttemp = read_memory(zero_page_x(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xCD :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tcase 0xDD :\n\t\t\t\ttemp = read_memory(absolute_x(*p,*(p-1)));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4 + (absolute_x(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xD9 :\n\t\t\t\ttemp = read_memory(absolute_y(*p,*(p-1)));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4 + (absolute_y(*p,*(p-1)) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase 0xC1 :\n\t\t\t\ttemp = read_memory(indexed_indirect(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 6;\n\t\t\t\tbreak;\n\t\t\tcase 0xD1 :\n\t\t\t\ttemp = read_memory(indirect_indexed(*p));\n\t\t\t\tif(a_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(a_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 5 + (indirect_indexed(*p) > PAGE_SIZE ? 1 : 0);\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\t\tcheck_for_negative(a_register);\n\t}\n\taction compare_x {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xE0 :\n\t\t\t\tif(x_register >= *p){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(x_register == *p){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 2;\t\t\t\t\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase 0xE4 : \n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tif(x_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(x_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xEC :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tif(x_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(x_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\t\tcheck_for_negative(x_register);\n\t}\n\taction compare_y {\n\t\tunsigned char temp;\n\t\tcurrent_op = *(p-arg_count);\n\n switch(current_op){\n\t\t\tcase 0xC0 :\n\t\t\t\tif(y_register >= *p){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(y_register == *p){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 2;\t\t\t\t\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase 0xC4 : \n\t\t\t\ttemp = read_memory(zero_page(*p));\n\t\t\t\tif(y_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(y_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 3;\n\t\t\t\tbreak;\n\t\t\tcase 0xCC :\n\t\t\t\ttemp = read_memory(absolute(*p,*(p-1)));\n\t\t\t\tif(y_register >= temp){\n\t\t\t\t\tset_carry_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_carry_flag();\n\t\t\t\t}\n\t\t\t\tif(y_register == temp){\n\t\t\t\t\tset_zero_flag();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclear_zero_flag();\n\t\t\t\t}\n\t\t\t\tcycles -= 4;\n\t\t\t\tbreak;\n\t\t\tdefault : break;\n\t\t}\n\t\tcheck_for_negative(y_register);\n\t}\n \n #special actions\n action cyclic_tasks {\n \/*debug code*\/\n \/*int i;\n for(i = arg_count; i >= 0;i--){\n printf(\"0x%.4X \",*(p-i));\n }\n printf(\"\\n\");*\/\n \/*end*\/\n if(cycles <= 0){\n cycles += interrupt_period;\n }\n if(p >= pe)\n exit(0);\n }\n \n #system functions\n NOP = (0x1A | 0x3A| 0x5A | 0x7A | 0xDA | 0xEA | 0xFA) @{arg_count = 0;} @no_operation;\n DOP = ((0x04 | 0x14 | 0x34 | 0x44 | 0x54 | 0x64 | 0x74 | 0x80 | 0x82 | 0x89 | 0xC2 | 0xD4 | 0xE2 | 0xF4) . extend) @{arg_count = 1;} @double_no_operation;\n TOP = ((0x0C | 0x1C | 0x3C | 0x5C | 0x7C | 0xDC | 0xFC) . extend . extend) @{arg_count = 2;} @triple_no_operation;\n BRK = (0x00) @{arg_count = 0;} @brk;\n RTI = (0x40) @{arg_count = 0;} @return_from_interrupt;\n \n #load and store instructions\n\tLAX = ( ((0xA7 | 0xB7 | 0xA3 | 0xB3) . extend) @{arg_count = 1;} | ((0xAF | 0xBF) . extend . extend) @{arg_count = 2;}) @load_accumulator_and_x;\n LDA = ( (((0xA9 | 0xA5 | 0xB5 | 0xA1 | 0xB1) . extend) @{arg_count = 1;}) | (((0xAD | 0xBD | 0xB9) . extend . extend) @{arg_count = 2;}) ) @load_accumulator;\n LDX = ( (((0xA2 | 0xA6 | 0xB6) . extend) @{arg_count = 1;}) | (((0xAE | 0xBE) . extend .extend) @{arg_count = 2;}) ) @load_x;\n LDY = ( (((0xA0 | 0xA4 | 0xB4) . extend) @{arg_count = 1;}) | (((0xAC | 0xBC) . extend .extend) @{arg_count = 2;}) ) @load_y;\n STA = ( (((0x85 | 0x95 | 0x81 | 0x91) .extend) @{arg_count = 1;}) | (((0x8D | 0x9D | 0x99) . extend . extend) @{arg_count = 2;}) ) @store_accumulator; \n STX = ( ((0x86 | 0x96) . extend) @{arg_count = 1;} | ((0x8E) . extend . extend) @{arg_count = 2;}) @store_x;\n\tSTY = ( ((0x84 | 0x94) . extend) @{arg_count = 1;} | ((0x8C) . extend . extend) @{arg_count = 2;}) @store_y;\n\n\t#register transfer instructions\n\tTAX = (0xAA @{arg_count = 0;}) @transfer_accumulator_to_x;\n\tTAY = (0xA8 @{arg_count = 0;}) @transfer_accumulator_to_y;\n\tTXA = (0x8A @{arg_count = 0;}) @transfer_x_to_accumulator;\n\tTYA = (0x98 @{arg_count = 0;}) @transfer_y_to_accumulator;\n\n\t#stack operation instructions\n\tTSX = (0xBA @{arg_count = 0;}) @transfer_stack_to_x;\n\tTXS = (0x9A @{arg_count = 0;}) @transfer_x_to_stack;\n\tPHA = (0x48 @{arg_count = 0;}) @push_accumulator;\n\tPHP = (0x08 @{arg_count = 0;}) @push_status;\n\tPLA = (0x68 @{arg_count = 0;}) @pull_accumulator;\n\tPLP = (0x28 @{arg_count = 0;}) @pull_status;\n\n\t#logical instructions\n AND = (((0x29 | 0x25 | 0x35 | 0x21 | 0x31) . extend) @{arg_count = 1;} | ((0x2D | 0x3D | 0x39) . extend . extend) @{arg_count = 2;}) @logical_and;\n\tEOR = (((0x49 | 0x45 | 0x55 | 0x41 | 0x51) . extend) @{arg_count = 1;} | ((0x4D | 0x5D | 0x59) . extend . extend) @{arg_count = 2;}) @logical_eor;\n\tORA = (((0x09 | 0x05 | 0x15 | 0x01 | 0x11) . extend) @{arg_count = 1;} | ((0x0D | 0x1D | 0x19) . extend . extend) @{arg_count = 2;}) @logical_ora;\n\tBIT = ((0x24 . extend) @{arg_count = 1;} | (0x2C . extend . extend) @{arg_count = 2;}) @logical_bit;\n\tAAC = (((0x0B | 0x2B) . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte;\n\tAAX = (((0x87 | 0x97 | 0x83) . extend) @{arg_count = 1;} | (0x8F . extend . extend) @{arg_count = 2;}) @logical_and_accumulator_with_x;\n\tARR = ((0x6B . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte_right_rotate;\n\tASR = ((0x4B . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte_right_shift;\n\tATX = ((0xAB . extend) @{arg_count = 1;}) @logical_and_accumulator_with_byte_store_x;\n\tAXA = ((0x93 . extend) @{arg_count = 1;} | (0x9F . extend . extend) @{arg_count = 2;}) @logical_and_accumulator_with_x_store_memory;\n\tAXS = (0xCB . extend @{arg_count = 1;}) @logical_and_accumulator_with_x_sub_byte;\n\tLAR = (0xBB . extend . extend @{arg_count = 2;}) @logical_and_mem_with_stack_pointer;\n\tSXA = (0x9E . extend . extend @{arg_count = 2;}) @logical_and_high_byte_with_x;\n\tSYA = (0x9C . extend . extend @{arg_count = 2;}) @logical_and_high_byte_with_y;\n\tXAS = (0x9B . extend . extend @{arg_count = 2;}) @logical_and_x_with_accumulator_store_in_stack;\n\n\t#arithmetic instuctions\n\tADC = ((((0x69 | 0x65 | 0x75 | 0x61 | 0x71) . extend) @{arg_count = 1;}) | ((0x6D | 0x7D | 0x79) . extend . extend) @{arg_count = 2;}) @add;\n\tSBC = ((((0xE9 | 0xE5 | 0xF5 | 0xE1 | 0xF1) . extend) @{arg_count = 1;}) | ((0xED | 0xFD | 0xF9) . extend . extend) @{arg_count = 2;}) @subtract;\n\tCMP = ((((0xC9 | 0xC5 | 0xD5 | 0xC1 | 0xD1) . extend) @{arg_count = 1;}) | ((0xCD | 0xDD | 0xD9) . extend . extend) @{arg_count = 2;}) @compare;\n\tCPX = (((0xE0 | 0xE4) . extend @{arg_count = 1;}) | ((0xEC) . extend . extend @{arg_count = 2;})) @compare_x;\n\tCPY = (((0xC0 | 0xC4) . extend @{arg_count = 1;}) | ((0xCC) . extend . extend @{arg_count = 2;})) @compare_y;\n\n Lexecute = (\n #system functions\n NOP | DOP | TOP | BRK | RTI |\n #load and store instructions\n LAX | LDA | LDX | LDY | STA | STX | STY |\n\t\t#register transfer instructions\n\t\tTAX | TAY | TXA | TYA |\n\t\t#stack operation instructions\n\t\tTSX | TXS | PHA | PHP | PLA | PLP |\n\t\t#logical instructions\n\t\tAND | EOR | ORA | BIT | AAC | AAX | ARR | ASR | ATX | AXA | AXS | LAR | SXA | SYA | XAS |\n\t\t#arithmetic instructions\n\t\tADC | SBC | CMP | CPX | CPY\n );\n \n main := (Lexecute @cyclic_tasks)+;\n \n}%%\n\n%%write data;\n\nint load_rom(char* fname){\n int fsize;\n FILE* fp = fopen(fname,\"rb\");\n if(!fp){\n printf(\"Unable to open ROM!\\n\");\n exit(1);\n }\n fseek(fp,0,SEEK_END);\n fsize = ftell(fp);\n p = (unsigned char*)malloc(sizeof(unsigned char) * fsize);\n fread(p,sizeof(unsigned char),fsize,fp);\n fclose(fp);\n return(fsize);\n}\n\n\/*debug code*\/\nvoid dump_mem(){\n int i,j;\n\tprintf(\"%.2X\\n\",a_register);\n\tprintf(\"%.2X\\n\",x_register);\n\tprintf(\"%.2X\\n\",y_register);\n\tprintf(\"%.2X\\n\",status);\n\n for(i = 0;i= STACK_OFFSET;i--){\n\t\tfprintf(fp,\"%.2X\\n\",m[i]);\n\t}\n\n for(i = 0;i 2){\n\t\t\/*init*\/\n\t\tcycles = interrupt_period;\n\t\tstatus = 0;\n\t\targ_count = 0;\n\t\tpstack = MY_STACK_SIZE-1;\n\t\n\t\t%%write init;\n\t\t\n\t\tload_it(argv[1]);\n\t\t\/\/unsigned char test[] = {0xA9,0x00};\n\t\t\/\/p = test;\n\t\t\/\/pe = test+2;\n\t\t%%write exec;\n\t\t\/\/dump_mem();\n\t\tpack_it(argv[2]);\n\t}\n return 0;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"08a17ec790efb0d20610008d79fa157e0d3a9615","subject":"added some more tests for chunked encoding","message":"added some more tests for chunked encoding\n","repos":"dharmarth\/libebb,dharmarth\/libebb","old_file":"parser.rl","new_file":"parser.rl","new_contents":"\n#include \"parser.h\"\n#include \n#include \n#include \n\n#ifndef TRUE\n# define TRUE 1\n# define FALSE 0\n#endif\n#ifndef MIN\n# define MIN(a,b) (a < b ? a : b)\n#endif\n#define REMAINING (pe - p)\n#define CURRENT (parser->current_request)\n#define CONTENT_LENGTH (parser->current_request->content_length)\n\n#define eip_empty(parser) (parser->eip_stack[0] == NULL)\n\nstatic void eip_push\n ( ebb_parser *parser\n , ebb_element *element\n )\n{\n int i = 0;\n \/* NO BOUNDS CHECKING - LIVING ON THE EDGE! *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {;}\n \/\/printf(\"push! (stack size before: %d)\\n\", i);\n parser->eip_stack[i] = element;\n}\n\nstatic ebb_element* eip_pop\n ( ebb_parser *parser\n )\n{\n int i;\n ebb_element *top = NULL;\n assert( ! eip_empty(parser) ); \n \/* NO BOUNDS CHECKING - LIVING ON THE EDGE! *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {;}\n \/\/printf(\"pop! (stack size before: %d)\\n\", i);\n top = parser->eip_stack[i-1];\n parser->eip_stack[i-1] = NULL;\n return top;\n}\n\n\n%%{\n machine ebb_parser;\n\n action mark {\n \/\/printf(\"mark!\\n\");\n eip = parser->new_element();\n eip->base = p;\n eip_push(parser, eip);\n }\n\n action mmark {\n \/\/printf(\"mmark!\\n\");\n eip = parser->new_element();\n eip->base = p;\n eip_push(parser, eip);\n }\n\n action write_field { \n \/\/printf(\"write_field!\\n\");\n assert(parser->header_field_element == NULL); \n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - last->base;\n parser->header_field_element = eip;\n assert(eip_empty(parser) && \"eip_stack must be empty after header field\");\n }\n\n action write_value {\n \/\/printf(\"write_value!\\n\");\n assert(parser->header_field_element != NULL); \n\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n\n if(parser->header_handler)\n parser->header_handler( parser->data\n , parser->header_field_element\n , eip\n );\n if(parser->header_field_element->free)\n parser->header_field_element->free(parser->header_field_element);\n if(eip->free)\n eip->free(eip);\n eip = parser->header_field_element = NULL;\n }\n\n action request_uri { \n \/\/printf(\"request uri\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->request_uri)\n parser->request_uri(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action fragment { \n \/\/printf(\"fragment\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->fragment)\n parser->fragment(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action query_string { \n \/\/printf(\"query string\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->query_string)\n parser->query_string(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action request_path {\n \/\/printf(\"request path\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->request_path)\n parser->request_path(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action content_length {\n \/\/printf(\"content_length!\\n\");\n CURRENT->content_length *= 10;\n CURRENT->content_length += *p - '0';\n }\n\n action use_identity_encoding {\n \/\/printf(\"use identity encoding\\n\");\n CURRENT->transfer_encoding = EBB_IDENTITY;\n }\n\n action use_chunked_encoding {\n \/\/printf(\"use chunked encoding\\n\");\n CURRENT->transfer_encoding = EBB_CHUNKED;\n }\n\n action trailer {\n \/\/printf(\"trailer\\n\");\n \/* not implemenetd yet. (do requests even have trailing headers?) *\/\n }\n\n\n action request_method { \n \/\/printf(\"request method\\n\");\n eip = eip_pop(parser);\n eip->len = p - eip->base; \n if(parser->request_method)\n parser->request_method(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action version_major {\n CURRENT->version_major *= 10;\n CURRENT->version_major += *p - '0';\n }\n\n action version_minor {\n CURRENT->version_minor *= 10;\n CURRENT->version_minor += *p - '0';\n }\n\n action add_to_chunk_size {\n \/\/printf(\"add to chunk size\\n\");\n parser->chunk_size *= 16;\n \/* XXX: this can be optimized slightly *\/\n if( 'A' <= *p && *p <= 'F') \n parser->chunk_size += *p - 'A' + 10;\n else if( 'a' <= *p && *p <= 'f') \n parser->chunk_size += *p - 'a' + 10;\n else if( '0' <= *p && *p <= '9') \n parser->chunk_size += *p - '0';\n else \n assert(0 && \"bad hex char\");\n }\n\n action skip_chunk_data {\n \/\/printf(\"skip chunk data\\n\");\n \/\/printf(\"chunk_size: %d\\n\", parser->chunk_size);\n if(parser->chunk_size > REMAINING) {\n parser->eating = TRUE;\n parser->chunk_handler(parser->data, p, REMAINING);\n parser->chunk_size -= REMAINING;\n fhold; \n fbreak;\n } else {\n parser->chunk_handler(parser->data, p, parser->chunk_size);\n p += parser->chunk_size;\n parser->chunk_size = 0;\n parser->eating = FALSE;\n fhold; \n fgoto chunk_end; \n }\n }\n\n action end_chunked_body {\n \/\/printf(\"end chunked body\\n\");\n if(parser->request_complete)\n parser->request_complete(parser->data);\n fret; \/\/ goto Request; \n }\n\n action start_req {\n if(parser->first_request) {\n for(request = parser->first_request; request->next; request = request->next) {;}\n request->next = parser->new_request(parser->data);\n request = request->next;\n request->next = NULL;\n CURRENT = request;\n } else {\n parser->first_request = parser->new_request(parser->data);\n CURRENT = parser->first_request;\n }\n }\n\n action body_logic {\n if(CURRENT->transfer_encoding == EBB_CHUNKED) {\n fcall ChunkedBody;\n } else {\n \/*\n * EAT BODY\n * this is very ugly. sorry.\n *\n *\/\n if( CURRENT->content_length == 0) {\n\n if( parser->request_complete )\n parser->request_complete(parser->data);\n\n\n } else if( CURRENT->content_length < REMAINING ) {\n \/* \n * \n * FINISH EATING THE BODY. there is still more \n * on the buffer - so we just let it continue\n * parsing after we're done\n *\n *\/\n p += 1;\n if( parser->chunk_handler )\n parser->chunk_handler(parser->data, p, CURRENT->content_length); \n\n p += CURRENT->content_length;\n CURRENT->body_read = CURRENT->content_length;\n\n assert(0 <= REMAINING);\n\n if( parser->request_complete )\n parser->request_complete(parser->data);\n\n fhold;\n\n } else {\n \/* \n * The body is larger than the buffer\n * EAT REST OF BUFFER\n * there is still more to read though. this will \n * be handled on the next invokion of ebb_parser_execute\n * right before we enter the state machine. \n *\n *\/\n p += 1;\n size_t eat = REMAINING;\n\n if( parser->chunk_handler )\n parser->chunk_handler(parser->data, p, eat); \n\n p += eat;\n CURRENT->body_read += eat;\n\n assert(CURRENT->body_read < CURRENT->content_length);\n assert(REMAINING == 0);\n \n fhold; fbreak; \n }\n }\n }\n\n#\n##\n###\n#### HTTP\/1.1 STATE MACHINE\n###\n## RequestHeaders and character types are from\n# Zed Shaw's beautiful Mongrel parser.\n\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n# qdtext = token -- \"\\\"\"; \n# quoted_pair = \"\\\" ascii;\n# quoted_string = \"\\\"\" (qdtext | quoted_pair )* \"\\\"\";\n\n# headers\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n path = ( pchar+ ( \"\/\" pchar* )* ) ;\n query = ( uchar | reserved )* >mark %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = ( param ( \";\" param )* ) ;\n rel_path = ( path? (\";\" params)? ) ;\n absolute_path = ( \"\/\"+ rel_path ) >mmark %request_path (\"?\" query)?;\n Request_URI = ( \"*\" | absolute_uri | absolute_path ) >mark %request_uri;\n Fragment = ( uchar | reserved )* >mark %fragment;\n Method = ( upper | digit | safe ){1,20} >mark %request_method;\n http_number = (digit+ $version_major \".\" digit+ $version_minor);\n HTTP_Version = ( \"HTTP\/\" http_number );\n\n field_name = ( token -- \":\" )+;\n field_value = ((any - \" \") any*)?;\n\n head_sep = \":\" \" \"**;\n message_header = field_name head_sep field_value :> CRLF;\n\n cl = \"Content-Length\"i %write_field head_sep\n digit+ >mark $content_length %write_value;\n\n te = \"Transfer-Encoding\"i %write_field %use_chunked_encoding head_sep\n \"identity\"i >mark %use_identity_encoding %write_value;\n\n t = \"Trailer\"i %write_field head_sep\n field_value >mark %trailer %write_value;\n\n rest = (field_name %write_field head_sep field_value >mark %write_value);\n\n header = cl @(headers,4)\n | te @(headers,4)\n | t @(headers,4)\n | rest @(headers,1)\n ;\n\n Request_Line = ( Method \" \" Request_URI (\"#\" Fragment)? \" \" HTTP_Version CRLF ) ;\n RequestHeader = Request_Line (header >mark :> CRLF)* :> CRLF;\n\n# chunked message\n trailing_headers = message_header*;\n #chunk_ext_val = token | quoted_string;\n chunk_ext_val = token*;\n chunk_ext_name = token*;\n chunk_extension = ( \";\" \" \"* chunk_ext_name (\"=\" chunk_ext_val)? )*;\n last_chunk = \"0\"+ chunk_extension CRLF;\n chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size;\n chunk_end = CRLF;\n chunk_body = any >skip_chunk_data;\n chunk_begin = chunk_size chunk_extension CRLF;\n chunk = chunk_begin chunk_body chunk_end;\n ChunkedBody := chunk* last_chunk trailing_headers CRLF @end_chunked_body;\n\n Request = RequestHeader >start_req @body_logic;\n\n main := Request+; # sequence of requests (for keep-alive)\n}%%\n\n%% write data;\n\n#define COPYSTACK(dest, src) for(i = 0; i < PARSER_STACK_SIZE; i++) { dest[i] = src[i]; }\n\nvoid ebb_parser_init\n ( ebb_parser *parser\n ) \n{\n int i;\n\n int cs = 0;\n int top = 0;\n int stack[PARSER_STACK_SIZE];\n %% write init;\n parser->cs = cs;\n parser->top = top;\n COPYSTACK(parser->stack, stack);\n\n parser->chunk_size = 0;\n parser->eating = 0;\n \n\n parser->eip_stack[0] = NULL;\n parser->current_request = NULL;\n parser->first_request = NULL;\n parser->header_field_element = NULL;\n\n parser->nread = 0;\n\n parser->new_element = NULL;\n parser->new_request = NULL;\n parser->request_complete = NULL;\n parser->chunk_handler = NULL;\n parser->header_handler = NULL;\n parser->request_method = NULL;\n parser->request_uri = NULL;\n parser->fragment = NULL;\n parser->request_path = NULL;\n parser->query_string = NULL;\n}\n\n\n\/** exec **\/\nsize_t ebb_parser_execute\n ( ebb_parser *parser\n , const char *buffer\n , size_t len\n )\n{\n ebb_element *eip, *last; \n ebb_request *request; \n const char *p, *pe;\n int i, cs = parser->cs;\n\n int top = parser->top;\n int stack[PARSER_STACK_SIZE];\n COPYSTACK(stack, parser->stack);\n\n assert(parser->new_element && \"undefined callback\");\n assert(parser->new_request && \"undefined callback\");\n\n p = buffer;\n pe = buffer+len;\n\n if(0 < parser->chunk_size && parser->eating) {\n \/*\n *\n * eat chunked body\n * \n *\/\n \/\/printf(\"eat chunk body (before parse)\\n\");\n size_t eat = MIN(len, parser->chunk_size);\n if(eat == parser->chunk_size) {\n parser->eating = FALSE;\n }\n parser->chunk_handler(parser->data, p, eat);\n p += eat;\n parser->chunk_size -= eat;\n \/\/printf(\"eat: %d\\n\", eat);\n } else if( parser->current_request && \n CURRENT->content_length > 0 && \n CURRENT->body_read > 0) {\n \/*\n *\n * eat normal body\n * \n *\/\n \/\/printf(\"eat normal body (before parse)\\n\");\n size_t eat = MIN(len, CURRENT->content_length - CURRENT->body_read);\n\n parser->chunk_handler(parser->data, p, eat);\n p += eat;\n CURRENT->body_read += eat;\n\n if(CURRENT->body_read == CURRENT->content_length)\n if(parser->request_complete)\n parser->request_complete(parser->data);\n\n }\n\n\n\n \/* each on the eip stack gets expanded *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {\n last = ebb_element_last(parser->eip_stack[i]);\n last->next = parser->new_element();\n last->next->base = buffer;\n }\n\n %% write exec;\n\n parser->cs = cs;\n parser->top = top;\n COPYSTACK(parser->stack, stack);\n\n parser->nread += p - buffer;\n\n \/* each on the eip stack gets len *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {\n parser->eip_stack[i]->len = pe - parser->eip_stack[i]->base;\n assert( parser->eip_stack[i]->base < pe && \"mark is after buffer end\");\n }\n\n assert(p <= pe && \"buffer overflow after parsing execute\");\n\n return(p - buffer);\n}\n\nint ebb_parser_has_error\n ( ebb_parser *parser\n ) \n{\n return parser->cs == ebb_parser_error;\n}\n\nint ebb_parser_is_finished\n ( ebb_parser *parser\n ) \n{\n return parser->cs == ebb_parser_first_final;\n}\n\nvoid ebb_request_init\n ( ebb_request *request\n )\n{\n request->content_length = 0;\n request->version_major = 0;\n request->version_minor = 0;\n request->transfer_encoding = EBB_IDENTITY;\n request->complete = FALSE;\n request->next = NULL;\n request->free = NULL;\n}\n\nint ebb_element_init\n ( ebb_element *element\n ) \n{\n element->base = NULL;\n element->len = 0;\n element->next = NULL;\n element->free = NULL;\n}\n\nebb_element* ebb_element_last\n ( ebb_element *element\n )\n{\n for( ; element->next; element = element->next) {;}\n return element;\n}\n\nsize_t ebb_element_len\n ( ebb_element *element\n )\n{\n size_t len; \n for(len = 0; element; element = element->next)\n len += element->len;\n return len;\n}\n\nvoid ebb_element_strcpy\n ( ebb_element *element\n , char *dest\n )\n{\n dest[0] = '\\0';\n for( ; element; element = element->next) \n strncat(dest, element->base, element->len);\n}\n\nvoid ebb_element_printf\n ( ebb_element *element\n , const char *format\n )\n{\n char str[1000];\n ebb_element_strcpy(element, str);\n printf(format, str);\n}\n\n#ifdef UNITTEST\n#include \n\nstatic ebb_parser parser;\nstruct request_data {\n char request_method[500];\n char request_path[500];\n char request_uri[500];\n char fragment[500];\n char query_string[500];\n char body[500];\n int num_headers;\n char* header_fields[500];\n char* header_values[500];\n ebb_request request;\n};\nstatic struct request_data requests[5];\nstatic int num_requests;\n\nebb_element* new_element ()\n{\n ebb_element *el = malloc(sizeof(ebb_element));\n ebb_element_init(el);\n return el;\n}\n\nebb_request* new_request ()\n{\n requests[num_requests].num_headers = 0;\n requests[num_requests].request_method[0] = 0;\n requests[num_requests].request_path[0] = 0;\n requests[num_requests].request_uri[0] = 0;\n requests[num_requests].fragment[0] = 0;\n requests[num_requests].query_string[0] = 0;\n requests[num_requests].body[0] = 0;\n ebb_request *r = &requests[num_requests].request ;\n ebb_request_init(r);\n printf(\"new request %d\\n\", num_requests);\n return r;\n}\n\nvoid request_complete()\n{\n printf(\"request complete\\n\");\n num_requests++;\n}\n\nvoid request_method_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].request_method);\n}\n\nvoid request_path_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].request_path);\n}\n\nvoid request_uri_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].request_uri);\n}\n\nvoid fragment_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].fragment);\n}\n\nvoid header_handler(void *data, ebb_element *field, ebb_element *value)\n{\n char *field_s, *value_s;\n\n field_s = malloc( ebb_element_len(field) );\n ebb_element_strcpy( field, field_s);\n\n value_s = malloc( ebb_element_len(value) );\n ebb_element_strcpy( value, value_s);\n\n int nh = requests[num_requests].num_headers;\n\n requests[num_requests].header_fields[nh] = field_s;\n requests[num_requests].header_values[nh] = value_s;\n\n requests[num_requests].num_headers += 1;\n\n printf(\"header %s: %s\\n\", field_s, value_s);\n}\n\n\nvoid query_string_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].query_string);\n}\n\n\nvoid chunk_handler(void *data, const char *p, size_t len)\n{\n strncat(requests[num_requests].body, p, len);\n printf(\"chunk_handler: '%s'\\n\", requests[num_requests].body);\n}\n\nint test_error\n ( const char *buf\n )\n{\n size_t traversed = 0;\n num_requests = 0;\n\n ebb_parser_init(&parser);\n\n parser.new_element = new_element;\n parser.new_request = new_request;\n parser.request_complete = request_complete;\n parser.header_handler = header_handler;\n parser.request_method = request_method_cb;\n parser.request_path = request_path_cb;\n parser.request_uri = request_uri_cb;\n parser.fragment = fragment_cb;\n parser.query_string = query_string_cb;\n parser.chunk_handler = chunk_handler;\n\n traversed = ebb_parser_execute(&parser, buf, strlen(buf));\n\n return ebb_parser_has_error(&parser);\n}\n\nint test_multiple\n ( const char *buf1\n , const char *buf2\n , const char *buf3\n )\n{\n char total[80*1024] = \"\\0\";\n\n strcat(total, buf1); \n strcat(total, buf2); \n strcat(total, buf3); \n\n size_t traversed = 0;\n num_requests = 0;\n\n ebb_parser_init(&parser);\n\n parser.new_element = new_element;\n parser.new_request = new_request;\n parser.request_complete = request_complete;\n parser.header_handler = header_handler;\n parser.request_method = request_method_cb;\n parser.request_path = request_path_cb;\n parser.request_uri = request_uri_cb;\n parser.fragment = fragment_cb;\n parser.query_string = query_string_cb;\n parser.chunk_handler = chunk_handler;\n\n traversed = ebb_parser_execute(&parser, total, strlen(total));\n\n\n if( ebb_parser_has_error(&parser) )\n return -1;\n if(! ebb_parser_is_finished(&parser) )\n return -2;\n\n return traversed;\n}\n\n#define assert_req_str_eql(num, FIELD, expected) \\\n assert(0 == strcmp(requests[num].FIELD, expected))\n\nint main() \n{\n assert(test_error(\"hello world\"));\n assert(test_error(\"GET \/ HTP\/1.1\\r\\n\\r\\n\"));\n\n \/\/ Zed's header tests\n\n const char *dumbfuck = \"GET \/ HTTP\/1.1\\r\\naaaaaaaaaaaaa:++++++++++\\r\\n\\r\\n\";\n assert(!test_error(dumbfuck));\n assert(1 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"GET\");\n assert_req_str_eql(0, request_path, \"\/\");\n assert(1 == requests[0].request.version_major);\n assert(1 == requests[0].request.version_minor);\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"aaaaaaaaaaaaa\");\n assert_req_str_eql(0, header_values[0], \"++++++++++\");\n\n const char *dumbfuck2 = \"GET \/ HTTP\/1.1\\r\\nX-SSL-Bullshit: -----BEGIN CERTIFICATE-----\\r\\n\\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\\r\\n\\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\\r\\n\\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\\r\\n\\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\\r\\n\\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\\r\\n\\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\\r\\n\\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC\/1R64fAcEF\\r\\n\\tW51rEyFYiIeZGx\/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\\r\\n\\tgW7cMA\/s\/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi\/F1SiFlPDxuDfmdiNzL31+sL\\r\\n\\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW\/iaLB0\/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\\r\\n\\tu2MSpFyf+9BbC\/aXgaZuiCvSR+8Snv3xApQY+fULK\/xY8h8Ua51iXoQ5jrgu2SqR\\r\\n\\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\\r\\n\\tA1UdEwEB\/wQCMAAwEQYJYIZIAYb4QgEBBAQDAgWgMA4GA1UdDwEB\/wQEAwID6DAs\\r\\n\\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\\r\\n\\tVR0OBBYEFDTt\/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\\r\\n\\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\\r\\n\\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\\r\\n\\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\\r\\n\\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\\r\\n\\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\\r\\n\\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\\r\\n\\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\\r\\n\\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\\r\\n\\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS\/U4iiooBENGW\/Hwmmd3\\r\\n\\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv\/hmi0qlnlHs+k\/3Iobc3LjS5AMYr5L8\\r\\n\\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\\r\\n\\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\\r\\n\\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7\/ZhW6DqT8UFvsAdjvQbXyhV8Eu\\r\\n\\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0\/ES5gDGsABo4fqovUKlgop3\\r\\n\\tRA==\\r\\n\\t-----END CERTIFICATE-----\\r\\n\\r\\n\";\n assert(test_error(dumbfuck2));\n\n const char *fragment_in_uri = \"GET \/forums\/1\/topics\/2375?page=1#posts-17408 HTTP\/1.1\\r\\n\\r\\n\";\n assert(!test_error(fragment_in_uri));\n assert_req_str_eql(0, fragment, \"posts-17408\");\n assert_req_str_eql(0, query_string, \"page=1\");\n assert_req_str_eql(0, request_method, \"GET\");\n printf(\"request path: %s\\n\", requests[0].request_path);\n assert_req_str_eql(0, request_path, \"\/forums\/1\/topics\/2375\");\n \/* XXX request uri does not include fragment? *\/\n assert_req_str_eql(0, request_uri, \"\/forums\/1\/topics\/2375?page=1\");\n\n\n \/* TODO sending junk and large headers gets rejected *\/\n\n\n \/\/ get - no headers - no body\n const char *req1 = \"GET \/req1\/world HTTP\/1.1\\r\\n\\r\\n\"; \n assert(!test_error(req1));\n assert(1 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"GET\");\n assert_req_str_eql(0, request_path, \"\/req1\/world\");\n assert(1 == requests[0].request.version_major);\n assert(1 == requests[0].request.version_minor);\n assert(0 == requests[0].num_headers);\n\n \/\/ get - one header - no body\n const char *req2 = \"GET \/req2 HTTP\/1.1\\r\\nAccept: *\/*\\r\\n\\r\\n\"; \n assert(!test_error(req2));\n assert(1 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"GET\");\n assert_req_str_eql(0, request_path, \"\/req2\");\n assert_req_str_eql(0, request_uri, \"\/req2\");\n assert(1 == requests[0].request.version_major);\n assert(1 == requests[0].request.version_minor);\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Accept\");\n assert_req_str_eql(0, header_values[0], \"*\/*\");\n\n \/\/ post - one header - no body\n const char *req3 = \"POST \/req3 HTTP\/1.1\\r\\nAccept: *\/*\\r\\n\\r\\n\"; \n assert(!test_error(req3));\n assert_req_str_eql(0, body, \"\");\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Accept\");\n assert_req_str_eql(0, header_values[0], \"*\/*\");\n\n \/\/ no content-length\n const char *bad_req1 = \"GET \/bad_req1\/world HTTP\/1.1\\r\\nAccept: *\/*\\r\\nHELLO\\r\\n\";\n assert(test_error(bad_req1)); \/\/ error if there is a body without content length\n\n \/\/ get - no headers - body \"HELLO\"\n const char *req4 = \"GET \/req4 HTTP\/1.1\\r\\nconTENT-Length: 5\\r\\n\\r\\nHELLO\";\n \/\/ no error if there is a is body with content length\n assert(!test_error(req4));\n assert_req_str_eql(0, body, \"HELLO\");\n assert(1 == num_requests);\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"conTENT-Length\");\n assert_req_str_eql(0, header_values[0], \"5\");\n\n \/\/ post - one header - body \"World\"\n const char *req5 = \"POST \/req5 HTTP\/1.1\\r\\nAccept: *\/*\\r\\nContent-Length: 5\\r\\n\\r\\nWorld\";\n assert(!test_error(req5));\n assert_req_str_eql(0, body, \"World\");\n assert(2 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Accept\");\n assert_req_str_eql(0, header_values[0], \"*\/*\");\n assert_req_str_eql(0, header_fields[1], \"Content-Length\");\n assert_req_str_eql(0, header_values[1], \"5\");\n\n \/\/ post - no headers - chunked body \"all your base are belong to us\"\n const char *req6 = \"POST \/req6 HTTP\/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n1e\\r\\nall your base are belong to us\\r\\n0\\r\\n\\r\\n\";\n assert(!test_error(req6));\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"POST\");\n assert_req_str_eql(0, request_path, \"\/req6\");\n assert_req_str_eql(0, request_uri, \"\/req6\");\n assert_req_str_eql(0, body, \"all your base are belong to us\");\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Transfer-Encoding\");\n assert_req_str_eql(0, header_values[0], \"chunked\");\n\n \/\/ two chunks ; triple zero ending\n const char *req7 = \"POST \/req7 HTTP\/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n5\\r\\nhello\\r\\n6\\r\\n world\\r\\n000\\r\\n\\r\\n\"; \n assert(!test_error(req7));\n assert_req_str_eql(0, request_path, \"\/req7\");\n assert_req_str_eql(0, body, \"hello world\");\n\n \/\/ chunked with trailing headers. blech.\n const char *req8 = \"POST \/req8 HTTP\/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n5\\r\\nhello\\r\\n6\\r\\n world\\r\\n0\\r\\nVary: *\\r\\nContent-Type: text\/plain\\r\\n\\r\\n\"; \n assert(!test_error(req8));\n assert_req_str_eql(0, request_path, \"\/req8\");\n assert_req_str_eql(0, body, \"hello world\");\n\n \/\/ with bullshit after the length\n const char *req9 = \"POST \/req9 HTTP\/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n5; ihatew3;whatthefuck=aretheseparametersfor\\r\\nhello\\r\\n6; blahblah; blah\\r\\n world\\r\\n0\\r\\n\\r\\n\";\n assert(!test_error(req9));\n assert_req_str_eql(0, body, \"hello world\");\n\n\n\n \/\/ three requests - no bodies\n assert(0 < test_multiple(req1, req2, req3));\n assert(3 == num_requests);\n\n \/\/ three requests - one body\n assert(0 < test_multiple(req1, req4, req3));\n assert(3 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(1, body, \"HELLO\");\n assert_req_str_eql(2, body, \"\");\n\n \/\/ three requests with bodies -- last is chunked\n assert(0 < test_multiple(req4, req5, req6));\n assert_req_str_eql(0, body, \"HELLO\");\n assert_req_str_eql(1, body, \"World\");\n assert_req_str_eql(2, body, \"all your base are belong to us\");\n assert(3 == num_requests);\n\n \/\/ three chunked requests\n assert(0 < test_multiple(req6, req6, req6));\n assert_req_str_eql(0, body, \"all your base are belong to us\");\n assert_req_str_eql(1, body, \"all your base are belong to us\");\n assert_req_str_eql(2, body, \"all your base are belong to us\");\n assert(3 == num_requests);\n\n\n printf(\"okay\\n\");\n return 0;\n}\n\n#endif\n\n","old_contents":"\n#include \"parser.h\"\n#include \n#include \n#include \n\n#ifndef TRUE\n# define TRUE 1\n# define FALSE 0\n#endif\n#ifndef MIN\n# define MIN(a,b) (a < b ? a : b)\n#endif\n#define REMAINING (pe - p)\n#define CURRENT (parser->current_request)\n#define CONTENT_LENGTH (parser->current_request->content_length)\n\n#define eip_empty(parser) (parser->eip_stack[0] == NULL)\n\nstatic void eip_push\n ( ebb_parser *parser\n , ebb_element *element\n )\n{\n int i = 0;\n \/* NO BOUNDS CHECKING - LIVING ON THE EDGE! *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {;}\n \/\/printf(\"push! (stack size before: %d)\\n\", i);\n parser->eip_stack[i] = element;\n}\n\nstatic ebb_element* eip_pop\n ( ebb_parser *parser\n )\n{\n int i;\n ebb_element *top = NULL;\n assert( ! eip_empty(parser) ); \n \/* NO BOUNDS CHECKING - LIVING ON THE EDGE! *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {;}\n \/\/printf(\"pop! (stack size before: %d)\\n\", i);\n top = parser->eip_stack[i-1];\n parser->eip_stack[i-1] = NULL;\n return top;\n}\n\n\n%%{\n machine ebb_parser;\n\n action mark {\n \/\/printf(\"mark!\\n\");\n eip = parser->new_element();\n eip->base = p;\n eip_push(parser, eip);\n }\n\n action mmark {\n \/\/printf(\"mmark!\\n\");\n eip = parser->new_element();\n eip->base = p;\n eip_push(parser, eip);\n }\n\n action write_field { \n \/\/printf(\"write_field!\\n\");\n assert(parser->header_field_element == NULL); \n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - last->base;\n parser->header_field_element = eip;\n assert(eip_empty(parser) && \"eip_stack must be empty after header field\");\n }\n\n action write_value {\n \/\/printf(\"write_value!\\n\");\n assert(parser->header_field_element != NULL); \n\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n\n if(parser->header_handler)\n parser->header_handler( parser->data\n , parser->header_field_element\n , eip\n );\n if(parser->header_field_element->free)\n parser->header_field_element->free(parser->header_field_element);\n if(eip->free)\n eip->free(eip);\n eip = parser->header_field_element = NULL;\n }\n\n action request_uri { \n \/\/printf(\"request uri\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->request_uri)\n parser->request_uri(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action fragment { \n \/\/printf(\"fragment\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->fragment)\n parser->fragment(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action query_string { \n \/\/printf(\"query string\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->query_string)\n parser->query_string(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action request_path {\n \/\/printf(\"request path\\n\");\n eip = eip_pop(parser);\n last = ebb_element_last(eip);\n last->len = p - eip->base; \n if(parser->request_path)\n parser->request_path(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action content_length {\n \/\/printf(\"content_length!\\n\");\n CURRENT->content_length *= 10;\n CURRENT->content_length += *p - '0';\n }\n\n action use_identity_encoding {\n \/\/printf(\"use identity encoding\\n\");\n CURRENT->transfer_encoding = EBB_IDENTITY;\n }\n\n action use_chunked_encoding {\n \/\/printf(\"use chunked encoding\\n\");\n CURRENT->transfer_encoding = EBB_CHUNKED;\n }\n\n action trailer {\n \/\/printf(\"trailer\\n\");\n \/* not implemenetd yet. (do requests even have trailing headers?) *\/\n }\n\n\n action request_method { \n \/\/printf(\"request method\\n\");\n eip = eip_pop(parser);\n eip->len = p - eip->base; \n if(parser->request_method)\n parser->request_method(parser->data, eip);\n if(eip->free)\n eip->free(eip);\n }\n\n action version_major {\n CURRENT->version_major *= 10;\n CURRENT->version_major += *p - '0';\n }\n\n action version_minor {\n CURRENT->version_minor *= 10;\n CURRENT->version_minor += *p - '0';\n }\n\n action add_to_chunk_size {\n \/\/printf(\"add to chunk size\\n\");\n parser->chunk_size *= 16;\n \/* XXX: this can be optimized slightly *\/\n if( 'A' <= *p && *p <= 'F') \n parser->chunk_size += *p - 'A' + 10;\n else if( 'a' <= *p && *p <= 'f') \n parser->chunk_size += *p - 'a' + 10;\n else if( '0' <= *p && *p <= '9') \n parser->chunk_size += *p - '0';\n else \n assert(0 && \"bad hex char\");\n }\n\n action skip_chunk_data {\n \/\/printf(\"skip chunk data\\n\");\n \/\/printf(\"chunk_size: %d\\n\", parser->chunk_size);\n if(parser->chunk_size > REMAINING) {\n parser->eating = TRUE;\n parser->chunk_handler(parser->data, p, REMAINING);\n parser->chunk_size -= REMAINING;\n fhold; \n fbreak;\n } else {\n parser->chunk_handler(parser->data, p, parser->chunk_size);\n p += parser->chunk_size;\n parser->chunk_size = 0;\n parser->eating = FALSE;\n fhold; \n fgoto chunk_end; \n }\n }\n\n action end_chunked_body {\n \/\/printf(\"end chunked body\\n\");\n if(parser->request_complete)\n parser->request_complete(parser->data);\n fret; \/\/ goto Request; \n }\n\n action start_req {\n if(parser->first_request) {\n for(request = parser->first_request; request->next; request = request->next) {;}\n request->next = parser->new_request(parser->data);\n request = request->next;\n request->next = NULL;\n CURRENT = request;\n } else {\n parser->first_request = parser->new_request(parser->data);\n CURRENT = parser->first_request;\n }\n }\n\n#\n##\n###\n#### HTTP\/1.1 STATE MACHINE\n###\n## RequestHeaders and character types are from\n# Zed Shaw's beautiful Mongrel parser.\n\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n# qdtext = token -- \"\\\"\"; \n# quoted_pair = \"\\\" ascii;\n# quoted_string = \"\\\"\" (qdtext | quoted_pair )* \"\\\"\";\n\n# headers\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n path = ( pchar+ ( \"\/\" pchar* )* ) ;\n query = ( uchar | reserved )* >mark %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = ( param ( \";\" param )* ) ;\n rel_path = ( path? (\";\" params)? ) ;\n absolute_path = ( \"\/\"+ rel_path ) >mmark %request_path (\"?\" query)?;\n Request_URI = ( \"*\" | absolute_uri | absolute_path ) >mark %request_uri;\n Fragment = ( uchar | reserved )* >mark %fragment;\n Method = ( upper | digit | safe ){1,20} >mark %request_method;\n http_number = (digit+ $version_major \".\" digit+ $version_minor);\n HTTP_Version = ( \"HTTP\/\" http_number );\n\n field_name = ( token -- \":\" )+ %write_field;\n field_value = ((any - \" \") any*)? >mark %write_value;\n\n head_sep = \":\" \" \"**;\n message_header = field_name head_sep field_value :> CRLF;\n\n cl = \"Content-Length\"i %write_field head_sep\n digit+ >mark $content_length %write_value;\n\n te = \"Transfer-Encoding\"i %write_field %use_chunked_encoding head_sep\n \"identity\"i >mark %use_identity_encoding %write_value;\n\n t = \"Trailer\"i %write_field head_sep\n field_value %trailer;\n\n rest = (field_name head_sep field_value);\n\n header = cl @(headers,4)\n | te @(headers,4)\n | t @(headers,4)\n | rest @(headers,1)\n ;\n\n Request_Line = ( Method \" \" Request_URI (\"#\" Fragment)? \" \" HTTP_Version CRLF ) ;\n RequestHeader = Request_Line (header >mark :> CRLF)* :> CRLF;\n\n# chunked message\n trailing_headers = message_header*;\n #chunk_ext_val = token | quoted_string;\n chunk_ext_val = token*;\n chunk_ext_name = token*;\n chunk_extension = ( \";\" \" \"* chunk_ext_name (\"=\" chunk_ext_val)? )*;\n last_chunk = \"0\"+ chunk_extension CRLF;\n chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size;\n chunk_end = CRLF;\n chunk_body = any >skip_chunk_data;\n chunk_begin = chunk_size chunk_extension CRLF;\n chunk = chunk_begin chunk_body chunk_end;\n ChunkedBody := chunk* last_chunk trailing_headers CRLF @end_chunked_body;\n\n Request = RequestHeader @{\n if(CURRENT->transfer_encoding == EBB_CHUNKED) {\n fcall ChunkedBody;\n } else {\n \/*\n * EAT BODY\n * this is very ugly. sorry.\n *\n *\/\n if( CURRENT->content_length == 0) {\n\n if( parser->request_complete )\n parser->request_complete(parser->data);\n\n\n } else if( CURRENT->content_length < REMAINING ) {\n \/* \n * \n * FINISH EATING THE BODY. there is still more \n * on the buffer - so we just let it continue\n * parsing after we're done\n *\n *\/\n p += 1;\n if( parser->chunk_handler )\n parser->chunk_handler(parser->data, p, CURRENT->content_length); \n\n p += CURRENT->content_length;\n CURRENT->body_read = CURRENT->content_length;\n\n assert(0 <= REMAINING);\n\n if( parser->request_complete )\n parser->request_complete(parser->data);\n\n fhold;\n\n } else {\n \/* \n * The body is larger than the buffer\n * EAT REST OF BUFFER\n * there is still more to read though. this will \n * be handled on the next invokion of ebb_parser_execute\n * right before we enter the state machine. \n *\n *\/\n p += 1;\n size_t eat = REMAINING;\n\n if( parser->chunk_handler )\n parser->chunk_handler(parser->data, p, eat); \n\n p += eat;\n CURRENT->body_read += eat;\n\n assert(CURRENT->body_read < CURRENT->content_length);\n assert(REMAINING == 0);\n \n fhold; fbreak; \n }\n }\n };\n\n \n# sequence of requests (for keep-alive)\n main := (Request >start_req)+;\n}%%\n\n%% write data;\n\n#define COPYSTACK(dest, src) for(i = 0; i < PARSER_STACK_SIZE; i++) { dest[i] = src[i]; }\n\nvoid ebb_parser_init\n ( ebb_parser *parser\n ) \n{\n int i;\n\n int cs = 0;\n int top = 0;\n int stack[PARSER_STACK_SIZE];\n %% write init;\n parser->cs = cs;\n parser->top = top;\n COPYSTACK(parser->stack, stack);\n\n parser->chunk_size = 0;\n parser->eating = 0;\n \n\n parser->eip_stack[0] = NULL;\n parser->current_request = NULL;\n parser->first_request = NULL;\n parser->header_field_element = NULL;\n\n parser->nread = 0;\n\n parser->new_element = NULL;\n parser->new_request = NULL;\n parser->request_complete = NULL;\n parser->chunk_handler = NULL;\n parser->header_handler = NULL;\n parser->request_method = NULL;\n parser->request_uri = NULL;\n parser->fragment = NULL;\n parser->request_path = NULL;\n parser->query_string = NULL;\n}\n\n\n\/** exec **\/\nsize_t ebb_parser_execute\n ( ebb_parser *parser\n , const char *buffer\n , size_t len\n )\n{\n ebb_element *eip, *last; \n ebb_request *request; \n const char *p, *pe;\n int i, cs = parser->cs;\n\n int top = parser->top;\n int stack[PARSER_STACK_SIZE];\n COPYSTACK(stack, parser->stack);\n\n assert(parser->new_element && \"undefined callback\");\n assert(parser->new_request && \"undefined callback\");\n\n p = buffer;\n pe = buffer+len;\n\n if(0 < parser->chunk_size && parser->eating) {\n \/*\n *\n * eat chunked body\n * \n *\/\n \/\/printf(\"eat chunk body (before parse)\\n\");\n size_t eat = MIN(len, parser->chunk_size);\n if(eat == parser->chunk_size) {\n parser->eating = FALSE;\n }\n parser->chunk_handler(parser->data, p, eat);\n p += eat;\n parser->chunk_size -= eat;\n \/\/printf(\"eat: %d\\n\", eat);\n } else if( parser->current_request && \n CURRENT->content_length > 0 && \n CURRENT->body_read > 0) {\n \/*\n *\n * eat normal body\n * \n *\/\n \/\/printf(\"eat normal body (before parse)\\n\");\n size_t eat = MIN(len, CURRENT->content_length - CURRENT->body_read);\n\n parser->chunk_handler(parser->data, p, eat);\n p += eat;\n CURRENT->body_read += eat;\n\n if(CURRENT->body_read == CURRENT->content_length)\n if(parser->request_complete)\n parser->request_complete(parser->data);\n\n }\n\n\n\n \/* each on the eip stack gets expanded *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {\n last = ebb_element_last(parser->eip_stack[i]);\n last->next = parser->new_element();\n last->next->base = buffer;\n }\n\n %% write exec;\n\n parser->cs = cs;\n parser->top = top;\n COPYSTACK(parser->stack, stack);\n\n parser->nread += p - buffer;\n\n \/* each on the eip stack gets len *\/\n for(i = 0; parser->eip_stack[i] != NULL; i++) {\n parser->eip_stack[i]->len = pe - parser->eip_stack[i]->base;\n assert( parser->eip_stack[i]->base < pe && \"mark is after buffer end\");\n }\n\n assert(p <= pe && \"buffer overflow after parsing execute\");\n\n return(p - buffer);\n}\n\nint ebb_parser_has_error\n ( ebb_parser *parser\n ) \n{\n return parser->cs == ebb_parser_error;\n}\n\nint ebb_parser_is_finished\n ( ebb_parser *parser\n ) \n{\n return parser->cs == ebb_parser_first_final;\n}\n\nvoid ebb_request_init\n ( ebb_request *request\n )\n{\n request->content_length = 0;\n request->version_major = 0;\n request->version_minor = 0;\n request->transfer_encoding = EBB_IDENTITY;\n request->complete = FALSE;\n request->next = NULL;\n request->free = NULL;\n}\n\nint ebb_element_init\n ( ebb_element *element\n ) \n{\n element->base = NULL;\n element->len = 0;\n element->next = NULL;\n element->free = NULL;\n}\n\nebb_element* ebb_element_last\n ( ebb_element *element\n )\n{\n for( ; element->next; element = element->next) {;}\n return element;\n}\n\nsize_t ebb_element_len\n ( ebb_element *element\n )\n{\n size_t len; \n for(len = 0; element; element = element->next)\n len += element->len;\n return len;\n}\n\nvoid ebb_element_strcpy\n ( ebb_element *element\n , char *dest\n )\n{\n dest[0] = '\\0';\n for( ; element; element = element->next) \n strncat(dest, element->base, element->len);\n}\n\nvoid ebb_element_printf\n ( ebb_element *element\n , const char *format\n )\n{\n char str[1000];\n ebb_element_strcpy(element, str);\n printf(format, str);\n}\n\n#ifdef UNITTEST\n#include \n\nstatic ebb_parser parser;\nstruct request_data {\n char request_method[500];\n char request_path[500];\n char request_uri[500];\n char fragment[500];\n char query_string[500];\n char body[500];\n int num_headers;\n char* header_fields[500];\n char* header_values[500];\n ebb_request request;\n};\nstatic struct request_data requests[5];\nstatic int num_requests;\n\nebb_element* new_element ()\n{\n ebb_element *el = malloc(sizeof(ebb_element));\n ebb_element_init(el);\n return el;\n}\n\nebb_request* new_request ()\n{\n requests[num_requests].num_headers = 0;\n requests[num_requests].request_method[0] = 0;\n requests[num_requests].request_path[0] = 0;\n requests[num_requests].request_uri[0] = 0;\n requests[num_requests].fragment[0] = 0;\n requests[num_requests].query_string[0] = 0;\n requests[num_requests].body[0] = 0;\n ebb_request *r = &requests[num_requests].request ;\n ebb_request_init(r);\n printf(\"new request %d\\n\", num_requests);\n return r;\n}\n\nvoid request_complete()\n{\n printf(\"request complete\\n\");\n num_requests++;\n}\n\nvoid request_method_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].request_method);\n}\n\nvoid request_path_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].request_path);\n}\n\nvoid request_uri_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].request_uri);\n}\n\nvoid fragment_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].fragment);\n}\n\nvoid header_handler(void *data, ebb_element *field, ebb_element *value)\n{\n char *field_s, *value_s;\n\n field_s = malloc( ebb_element_len(field) );\n ebb_element_strcpy( field, field_s);\n\n value_s = malloc( ebb_element_len(value) );\n ebb_element_strcpy( value, value_s);\n\n int nh = requests[num_requests].num_headers;\n\n requests[num_requests].header_fields[nh] = field_s;\n requests[num_requests].header_values[nh] = value_s;\n\n requests[num_requests].num_headers += 1;\n\n printf(\"header %s: %s\\n\", field_s, value_s);\n}\n\n\nvoid query_string_cb(void *data, ebb_element *el)\n{\n ebb_element_strcpy(el, requests[num_requests].query_string);\n}\n\n\nvoid chunk_handler(void *data, const char *p, size_t len)\n{\n strncat(requests[num_requests].body, p, len);\n printf(\"chunk_handler: '%s'\\n\", requests[num_requests].body);\n}\n\nint test_error\n ( const char *buf\n )\n{\n size_t traversed = 0;\n num_requests = 0;\n\n ebb_parser_init(&parser);\n\n parser.new_element = new_element;\n parser.new_request = new_request;\n parser.request_complete = request_complete;\n parser.header_handler = header_handler;\n parser.request_method = request_method_cb;\n parser.request_path = request_path_cb;\n parser.request_uri = request_uri_cb;\n parser.fragment = fragment_cb;\n parser.query_string = query_string_cb;\n parser.chunk_handler = chunk_handler;\n\n traversed = ebb_parser_execute(&parser, buf, strlen(buf));\n\n return ebb_parser_has_error(&parser);\n}\n\nint test_multiple\n ( const char *buf1\n , const char *buf2\n , const char *buf3\n )\n{\n char total[80*1024] = \"\\0\";\n\n strcat(total, buf1); \n strcat(total, buf2); \n strcat(total, buf3); \n\n size_t traversed = 0;\n num_requests = 0;\n\n ebb_parser_init(&parser);\n\n parser.new_element = new_element;\n parser.new_request = new_request;\n parser.request_complete = request_complete;\n parser.header_handler = header_handler;\n parser.request_method = request_method_cb;\n parser.request_path = request_path_cb;\n parser.request_uri = request_uri_cb;\n parser.fragment = fragment_cb;\n parser.query_string = query_string_cb;\n parser.chunk_handler = chunk_handler;\n\n traversed = ebb_parser_execute(&parser, total, strlen(total));\n\n\n if( ebb_parser_has_error(&parser) )\n return -1;\n if(! ebb_parser_is_finished(&parser) )\n return -2;\n\n return traversed;\n}\n\n#define assert_req_str_eql(num, FIELD, expected) \\\n assert(0 == strcmp(requests[num].FIELD, expected))\n\nint main() \n{\n\n assert(test_error(\"hello world\"));\n assert(test_error(\"GET \/ HTP\/1.1\\r\\n\\r\\n\"));\n\n\n \/\/ Zed's header tests\n\n\n const char *dumbfuck = \"GET \/ HTTP\/1.1\\r\\naaaaaaaaaaaaa:++++++++++\\r\\n\\r\\n\";\n assert(!test_error(dumbfuck));\n assert(1 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"GET\");\n assert_req_str_eql(0, request_path, \"\/\");\n assert(1 == requests[0].request.version_major);\n assert(1 == requests[0].request.version_minor);\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"aaaaaaaaaaaaa\");\n assert_req_str_eql(0, header_values[0], \"++++++++++\");\n\n\n const char *dumbfuck2 = \"GET \/ HTTP\/1.1\\r\\nX-SSL-Bullshit: -----BEGIN CERTIFICATE-----\\r\\n\\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\\r\\n\\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\\r\\n\\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\\r\\n\\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\\r\\n\\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\\r\\n\\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\\r\\n\\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC\/1R64fAcEF\\r\\n\\tW51rEyFYiIeZGx\/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\\r\\n\\tgW7cMA\/s\/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi\/F1SiFlPDxuDfmdiNzL31+sL\\r\\n\\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW\/iaLB0\/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\\r\\n\\tu2MSpFyf+9BbC\/aXgaZuiCvSR+8Snv3xApQY+fULK\/xY8h8Ua51iXoQ5jrgu2SqR\\r\\n\\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\\r\\n\\tA1UdEwEB\/wQCMAAwEQYJYIZIAYb4QgEBBAQDAgWgMA4GA1UdDwEB\/wQEAwID6DAs\\r\\n\\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\\r\\n\\tVR0OBBYEFDTt\/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\\r\\n\\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\\r\\n\\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\\r\\n\\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\\r\\n\\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\\r\\n\\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\\r\\n\\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\\r\\n\\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\\r\\n\\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\\r\\n\\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS\/U4iiooBENGW\/Hwmmd3\\r\\n\\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv\/hmi0qlnlHs+k\/3Iobc3LjS5AMYr5L8\\r\\n\\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\\r\\n\\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\\r\\n\\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7\/ZhW6DqT8UFvsAdjvQbXyhV8Eu\\r\\n\\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0\/ES5gDGsABo4fqovUKlgop3\\r\\n\\tRA==\\r\\n\\t-----END CERTIFICATE-----\\r\\n\\r\\n\";\n assert(test_error(dumbfuck2));\n\n\n const char *fragment_in_uri = \"GET \/forums\/1\/topics\/2375?page=1#posts-17408 HTTP\/1.1\\r\\n\\r\\n\";\n assert(!test_error(fragment_in_uri));\n assert_req_str_eql(0, fragment, \"posts-17408\");\n assert_req_str_eql(0, query_string, \"page=1\");\n assert_req_str_eql(0, request_method, \"GET\");\n printf(\"request path: %s\\n\", requests[0].request_path);\n assert_req_str_eql(0, request_path, \"\/forums\/1\/topics\/2375\");\n \/* XXX request uri does not include fragment? *\/\n assert_req_str_eql(0, request_uri, \"\/forums\/1\/topics\/2375?page=1\");\n\n\n \/* TODO sending junk and large headers gets rejected *\/\n\n\n \/\/ get - no headers - no body\n const char *req1 = \"GET \/req1\/world HTTP\/1.1\\r\\n\\r\\n\"; \n assert(!test_error(req1));\n assert(1 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"GET\");\n assert_req_str_eql(0, request_path, \"\/req1\/world\");\n assert(1 == requests[0].request.version_major);\n assert(1 == requests[0].request.version_minor);\n assert(0 == requests[0].num_headers);\n\n \/\/ get - one header - no body\n const char *req2 = \"GET \/req2 HTTP\/1.1\\r\\nAccept: *\/*\\r\\n\\r\\n\"; \n\n \/\/ post - one header - no body\n const char *req3 = \"POST \/req3 HTTP\/1.1\\r\\nAccept: *\/*\\r\\n\\r\\n\"; \n\n \/\/ get - no headers - body \"HELLO\"\n const char *req4 = \"GET \/req4 HTTP\/1.1\\r\\nconTENT-Length: 5\\r\\n\\r\\nHELLO\";\n\n \/\/ post - one header - body \"World\"\n const char *req5 = \"POST \/req5 HTTP\/1.1\\r\\nAccept: *\/*\\r\\nContent-Length: 5\\r\\n\\r\\nWorld\";\n\n \/\/ post - no headers - chunked body \"all your base are belong to us\"\n const char *req6 = \"POST \/req6 HTTP\/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n1e\\r\\nall your base are belong to us\\r\\n0\\r\\n\\r\\n\";\n\n \/\/ no content-length\n const char *bad_req1 = \"GET \/bad_req1\/world HTTP\/1.1\\r\\nAccept: *\/*\\r\\nHELLO\\r\\n\";\n\n\n assert(!test_error(req2));\n assert(1 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"GET\");\n assert_req_str_eql(0, request_path, \"\/req2\");\n assert_req_str_eql(0, request_uri, \"\/req2\");\n assert(1 == requests[0].request.version_major);\n assert(1 == requests[0].request.version_minor);\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Accept\");\n assert_req_str_eql(0, header_values[0], \"*\/*\");\n\n assert(!test_error(req3));\n assert_req_str_eql(0, body, \"\");\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Accept\");\n assert_req_str_eql(0, header_values[0], \"*\/*\");\n\n \/\/ error if there is a body without content length\n assert(test_error(bad_req1));\n\n \/\/ no error if there is a is body with content length\n assert(!test_error(req4));\n assert_req_str_eql(0, body, \"HELLO\");\n assert(1 == num_requests);\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"conTENT-Length\");\n assert_req_str_eql(0, header_values[0], \"5\");\n\n assert(!test_error(req5));\n assert_req_str_eql(0, body, \"World\");\n assert(2 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Accept\");\n assert_req_str_eql(0, header_values[0], \"*\/*\");\n assert_req_str_eql(0, header_fields[1], \"Content-Length\");\n assert_req_str_eql(0, header_values[1], \"5\");\n\n \/\/ chunked body\n assert(!test_error(req6));\n assert_req_str_eql(0, fragment, \"\");\n assert_req_str_eql(0, query_string, \"\");\n assert_req_str_eql(0, request_method, \"POST\");\n assert_req_str_eql(0, request_path, \"\/req6\");\n assert_req_str_eql(0, request_uri, \"\/req6\");\n assert_req_str_eql(0, body, \"all your base are belong to us\");\n assert(1 == requests[0].num_headers);\n assert_req_str_eql(0, header_fields[0], \"Transfer-Encoding\");\n assert_req_str_eql(0, header_values[0], \"chunked\");\n\n \/\/ three requests - no bodies\n assert(0 < test_multiple(req1, req2, req3));\n assert(3 == num_requests);\n\n \/\/ three requests - one body\n assert(0 < test_multiple(req1, req4, req3));\n assert(3 == num_requests);\n assert_req_str_eql(0, body, \"\");\n assert_req_str_eql(1, body, \"HELLO\");\n assert_req_str_eql(2, body, \"\");\n\n\n \/\/ three requests with bodies -- last is chunked\n assert(0 < test_multiple(req4, req5, req6));\n assert_req_str_eql(0, body, \"HELLO\");\n assert_req_str_eql(1, body, \"World\");\n assert_req_str_eql(2, body, \"all your base are belong to us\");\n assert(3 == num_requests);\n\n \/\/ three chunked requests\n assert(0 < test_multiple(req6, req6, req6));\n assert_req_str_eql(0, body, \"all your base are belong to us\");\n assert_req_str_eql(1, body, \"all your base are belong to us\");\n assert_req_str_eql(2, body, \"all your base are belong to us\");\n assert(3 == num_requests);\n\n\n\n\n printf(\"okay\\n\");\n return 0;\n}\n\n#endif\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"4ab5dc9086dbbfac07bc49441eef8d9d5f5dd2e0","subject":"[mfilescanner] improved line counting, not perfect, but good","message":"[mfilescanner] improved line counting, not perfect, but good\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner_parser.rl","new_file":"src\/mfilescanner_parser.rl","new_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n @{ fout_ << \"\\n\";\n fout_.write(tmp_p, p - tmp_p);\n tmp_p = p+1; fout_ << \" *\";\n }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p); }\n )*\n $!{\n fout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n fhold;\n while (*p == ' ')\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # RAGEL comment: else: a regular comment\n ( (default - '|')\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( ([ \\t]+ \n @{\n {\n int i=0;\n if (*(p+1) != ' ' && *(p+1) != '\\t')\n {\n while (*(p-i) == ' ' || *(p-i) == '\\t')\n i++;\n if (*(p-i) == '\\n')\n fout_ << std::string(i, ' ');\n }\n }\n })\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # white space or line continuation\n WS =\n ( [ \\t]+\n | ('...'.[\\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | ',' | EOL\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n \n matrix_or_cell := (\n '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n ( (WSOC | EOL )+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (IDENT %{tmp_string.assign(ts,p-ts);})\n . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n varargin_parser_candidate_ = tmp_string;\n };\n\n ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n\n\n ('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n ('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL ) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n \n ('\\'')\n => { fout_ << \"^t\"; };\n\n # simply output all other characters\n (default - [\\n{}\\'])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # things that could end the function body {{{4\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n tmp_string.assign(ts,p-ts+1);\n p = ts-1;\n\n if (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # RAGEL comment: ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # RAGEL comment: ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.abstr = true;\n } )\n | ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.abortSet = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n fout_ << string(ts, ts+funcindent_);\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n fgoto methods;\n }\n );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n {\n char *i = tmp_p-1;\n for (; *i == ' ' || *i == '\\t'; --i)\n fout_ << *i;\n }\n \n end_of_property_doc();\n string s(tmp_p, p - tmp_p);\n if (s == \"end\")\n fgoto classbody;\n if (propertyparams_.dependent)\n specifier_[s].dependent = true;\n property_list_.push_back(s);\n \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n undoced_prop_ = true;\n }\n )\n . WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n |\n ( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n @{\n defaultprop_ = string(tmp_p2, p - tmp_p2);\n string::size_type last_elem = defaultprop_.length() -1;\n if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n {\n defaultprop_[0] = '\\\"';\n defaultprop_[last_elem] = '\\\"';\n }\n string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n string::size_type last_paren;\n if (first_paren == string::npos)\n {\n first_paren = 1;\n last_paren = last_elem;\n }\n else\n {\n last_paren = defaultprop_.find_last_of(\")]}\");\n if (last_paren == string::npos)\n last_paren=last_elem-1;\n else\n {\n if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n {\n first_paren++;\n last_paren--;\n }\n defaultprop_.insert(first_paren, 1,'\"');\n defaultprop_.insert(last_paren+2, 1,'\"');\n first_paren++;\n last_paren++;\n }\n }\n for (unsigned int i = first_paren; i < last_paren; ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = ' ';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n else if(defaultprop_[i] == '\\\"')\n defaultprop_[i] = '\\'';\n else if(defaultprop_[i] == '@')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n else if(defaultprop_[i] == '\\n')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n }\n }\n )\n );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n (prop)\n |\n ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (WSOC); # => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n std::map::iterator specIt;\n for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n {\n fout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n if ( (*specIt).second.dependent)\n {\n if( (*specIt).second.getter && ! (*specIt).second.setter )\n {\n fout_ << \"@note [readonly]\\n *\";\n }\n }\n else\n {\n fout_ << \"@note This property has custom functionality when its value is \";\n if ((*specIt).second.getter)\n {\n fout_ << \"retrieved\";\n if ((*specIt).second.setter)\n fout_ << \" or changed\";\n }\n else if ((*specIt).second.setter)\n fout_ << \"changed\";\n fout_ << \".\";\n }\n fout_ << \"\\n *\/\\n\";\n }\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Event;\n fgoto properties;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n {\n int i = 0;\n for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n ;\n std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any\n @{\n fhold;\n tmp_p = p;\n }\n .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p-=8;\n char *tp;\n for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n ;\n funcindent_ = (int)(p - tp);\n#if DEBUG\n {\n ostringstream oss;\n oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n debug_output(oss.str(), p);\n }\n#endif\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p-=8;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string, tmp_string2, tmp_string3;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","old_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n @{ fout_ << \"\\n\";\n fout_.write(tmp_p, p - tmp_p);\n tmp_p = p+1; fout_ << \" *\";\n }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p); }\n )*\n $!{\n fout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n fhold;\n while (*p == ' ')\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # RAGEL comment: else: a regular comment\n ( (default - '|')\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( ([ \\t]+ \n @{\n {\n int i=0;\n if (*(p+1) != ' ' && *(p+1) != '\\t')\n {\n while (*(p-i) == ' ' || *(p-i) == '\\t')\n i++;\n if (*(p-i) == '\\n')\n fout_ << std::string(i, ' ');\n }\n }\n })\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # white space or line continuation\n WS =\n ( [ \\t]+\n | ('...'.[\\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n \n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (IDENT %{tmp_string.assign(ts,p-ts);})\n . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n varargin_parser_candidate_ = tmp_string;\n };\n\n ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n\n\n ('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . [;\\n] )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . [;\\n] )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n ('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . [;\\n] )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . [;\\n] )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n \n ('\\'')\n => { fout_ << \"^t\"; };\n\n # simply output all other characters\n (default - [\\n{}\\'])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # things that could end the function body {{{4\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n tmp_string.assign(ts,p-ts+1);\n p = ts-1;\n\n if (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # RAGEL comment: ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # RAGEL comment: ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n | ( ( 'AbortSet' . [^,)]* )\n @{\n propertyparams_.abortSet = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n fout_ << string(ts, ts+funcindent_);\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n fgoto methods;\n }\n );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n {\n char *i = tmp_p-1;\n for (; *i == ' ' || *i == '\\t'; --i)\n fout_ << *i;\n }\n \n end_of_property_doc();\n string s(tmp_p, p - tmp_p);\n if (s == \"end\")\n fgoto classbody;\n if (propertyparams_.dependent)\n specifier_[s].dependent = true;\n property_list_.push_back(s);\n \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n undoced_prop_ = true;\n }\n )\n . WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n |\n ( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n @{\n defaultprop_ = string(tmp_p2, p - tmp_p2);\n string::size_type last_elem = defaultprop_.length() -1;\n if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n {\n defaultprop_[0] = '\\\"';\n defaultprop_[last_elem] = '\\\"';\n }\n string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n string::size_type last_paren;\n if (first_paren == string::npos)\n {\n first_paren = 1;\n last_paren = last_elem;\n }\n else\n {\n last_paren = defaultprop_.find_last_of(\")]}\");\n if (last_paren == string::npos)\n last_paren=last_elem-1;\n else\n {\n if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n {\n first_paren++;\n last_paren--;\n }\n defaultprop_.insert(first_paren, 1,'\"');\n defaultprop_.insert(last_paren+2, 1,'\"');\n first_paren++;\n last_paren++;\n }\n }\n for (unsigned int i = first_paren; i < last_paren; ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = ' ';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n else if(defaultprop_[i] == '\\\"')\n defaultprop_[i] = '\\'';\n else if(defaultprop_[i] == '@')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n else if(defaultprop_[i] == '\\n')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n }\n }\n )\n );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n (prop)\n |\n ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (WSOC); # => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n std::map::iterator specIt;\n for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n {\n fout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n if ( (*specIt).second.dependent)\n {\n if( (*specIt).second.getter && ! (*specIt).second.setter )\n {\n fout_ << \"@note [readonly]\\n *\";\n }\n }\n else\n {\n fout_ << \"@note This property has custom functionality when its value is \";\n if ((*specIt).second.getter)\n {\n fout_ << \"retrieved\";\n if ((*specIt).second.setter)\n fout_ << \" or changed\";\n }\n else if ((*specIt).second.setter)\n fout_ << \"changed\";\n fout_ << \".\";\n }\n fout_ << \"\\n *\/\\n\";\n }\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Event;\n fgoto properties;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n {\n int i = 0;\n for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n ;\n std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any\n @{\n fhold;\n tmp_p = p;\n }\n .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p-=8;\n char *tp;\n for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n ;\n funcindent_ = (int)(p - tp);\n#if DEBUG\n {\n ostringstream oss;\n oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n debug_output(oss.str(), p);\n }\n#endif\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p-=8;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string, tmp_string2, tmp_string3;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"c6acef74aba4f94325970c300c53da3cdacfb44f","subject":"Interpolation?","message":"Interpolation?","repos":"medcat\/liquidscript,medcat\/liquidscript","old_file":"lib\/liquidscript\/scanner\/lexer.rl","new_file":"lib\/liquidscript\/scanner\/lexer.rl","new_contents":"%%{\n\n machine lexer;\n\n variable data @data;\n variable p @p;\n variable pe @pe;\n variable eof @eof;\n access @;\n \n action mark {\n @start = p\n }\n\n number_integer = '-'? [0-9][1-9]*;\n number_frac = '.' [0-9]+;\n number_e = ('e' | 'E') ('+' | '-' | '');\n number_exp = number_e [0-9]+;\n number = number_integer number_frac? number_exp?;\n\n string_double = '\"' ( \n any -- '\"' | \n '\\\\\"' \n )* '\"';\n identifier = [A-Za-z_$][A-Za-z0-9_$]*;\n string_single = \"'\" [A-Za-z0-9_$\\-]+;\n keywords = 'undefined' | 'null' | 'true' | 'false';\n unops = '!' | '++' | '--' | '~' | 'new' | 'return' |\n 'typeof';\n binops = '+' | '-' | '*' | '\/' | '&' | '|' | '^' | '<<' | '>>' |\n '>>>' | '==' | '!=' | '===' | '!==' | '>' | '>=' | '<' | '<=' |\n '&&' | '||' | 'instanceof' | 'or' | 'and';\n \n istring_part = ( any -- '\"' | '\\\\\"' );\n istring_start = '\"' ( istring_part* ) '#{';\n istring_middle = '}' ( istring_part* ) '#{';\n istring_end = '}' ( istring_part* ) '\"';\n \n body = (\n ( >mark number %{ emit :number } ) |\n ( >mark string_double %{ emit :dstring } ) |\n ( >mark string_single %{ emit :sstring } ) |\n ( >mark istring_start %{ emit :istart } ) |\n ( >mark istring_middle %{ emit :imiddle } ) |\n ( >mark istring_end %{ emit :iend } ) |\n ( 'class' %{ emit :class } ) |\n ( 'module' %{ emit :module } ) |\n ( 'if' %{ emit :if } ) |\n ( 'unless' %{ emit :unless } ) |\n ( 'elsif' %{ emit :elsif } ) |\n ( 'else' %{ emit :else } ) |\n ( >mark unops %{ emit :unop } ) |\n ( >mark binops %{ emit :binop } ) |\n ( >mark keywords %{ emit :keyword } ) |\n ( >mark identifier %{ emit :identifier } ) |\n ( '->' %{ emit :arrow } ) |\n ( '=' %{ emit :equal } ) |\n ( '{' %{ emit :lbrack } ) |\n ( '(' %{ emit :lparen } ) |\n ( '[' %{ emit :lbrace } ) |\n ( '}' %{ emit :rbrack } ) |\n ( ')' %{ emit :rparen } ) |\n ( ']' %{ emit :rbrace } ) |\n ( ':' %{ emit :colon } ) |\n ( '.' %{ emit :prop } ) |\n ( ',' %{ emit :comma } ) |\n ( '\\n' %{ line.call } )\n );\n \n loop = ( body** );\n \n\n main := loop;\n}%%\n\nmodule Liquidscript\n class Scanner\n\n # A lexer, built from ragel.\n #\n # @private\n class Lexer\n\n attr_reader :tokens\n\n def initialize\n %% write data;\n # %% # fix\n @tokens = []\n clean!\n end\n\n def clean!\n @p = nil\n @pe = nil\n @te = nil\n @ts = nil\n @act = nil\n @eof = nil\n @top = nil\n @line = { :start => 0, :num => 0 }\n @data = nil\n @stack = nil\n @start = nil\n end\n\n def emit(type)\n @tokens << if @start\n Token.new(type, @data[@start..(@p - 1)],\n @line[:num], @p - @line[:start])\n else\n Token.new(type, nil, @line[:num], @p - @line[:start])\n end\n \n @start = nil\n end\n\n def error\n raise SyntaxError, \"Unexpected #{@data[@start..(@p-1)].pack('c*')}\"\n end\n\n def perform(data)\n @data = data.unpack(\"c*\") if data.is_a? String\n @eof = data.length\n\n @tokens = []\n\n line = proc do\n @line[:start] = @ts\n @line[:num] += 1\n emit :newline\n end\n\n %% write init;\n %% write exec;\n\n clean!\n\n @tokens\n end\n end\n end\nend\n","old_contents":"%%{\n\n machine lexer;\n\n variable data @data;\n variable p @p;\n variable pe @pe;\n variable eof @eof;\n access @;\n \n action mark {\n @start = p\n }\n\n number_integer = '-'? [0-9][1-9]*;\n number_frac = '.' [0-9]+;\n number_e = ('e' | 'E') ('+' | '-' | '');\n number_exp = number_e [0-9]+;\n number = number_integer number_frac? number_exp?;\n\n string_double = '\"' ( any -- '\"' | '\\\\\"' )* '\"';\n identifier = [A-Za-z_$][A-Za-z0-9_$]*;\n string_single = \"'\" [A-Za-z0-9_$\\-]+;\n keywords = 'undefined' | 'null' | 'true' | 'false';\n unops = '!' | '++' | '--' | '~' | 'new' | 'return' |\n 'typeof';\n binops = '+' | '-' | '*' | '\/' | '&' | '|' | '^' | '<<' | '>>' |\n '>>>' | '==' | '!=' | '===' | '!==' | '>' | '>=' | '<' | '<=' |\n '&&' | '||' | 'instanceof' | 'or' | 'and';\n \n body = ( >mark number %{ emit :number } ) |\n ( >mark string_double %{ emit :dstring } ) |\n ( >mark string_single %{ emit :sstring } ) |\n ( 'class' %{ emit :class } ) |\n ( 'module' %{ emit :module } ) |\n ( 'if' %{ emit :if } ) |\n ( 'unless' %{ emit :unless } ) |\n ( 'elsif' %{ emit :elsif } ) |\n ( 'else' %{ emit :else } ) |\n ( >mark unops %{ emit :unop } ) |\n ( >mark binops %{ emit :binop } ) |\n ( >mark keywords %{ emit :keyword } ) |\n ( >mark identifier %{ emit :identifier } ) |\n ( '->' %{ emit :arrow } ) |\n ( '=' %{ emit :equal } ) |\n ( '{' %{ emit :lbrack } ) |\n ( '(' %{ emit :lparen } ) |\n ( '[' %{ emit :lbrace } ) |\n ( '}' %{ emit :rbrack } ) |\n ( ')' %{ emit :rparen } ) |\n ( ']' %{ emit :rbrace } ) |\n ( ':' %{ emit :colon } ) |\n ( '.' %{ emit :prop } ) |\n ( ',' %{ emit :comma } ) |\n ( '\\n' %{ line.call } )\n ;\n\n main := body**;\n}%%\n\nmodule Liquidscript\n class Scanner\n\n # A lexer, built from ragel.\n #\n # @private\n class Lexer\n\n attr_reader :tokens\n\n def initialize\n %% write data;\n # %% # fix\n @tokens = []\n clean!\n end\n\n def clean!\n @p = nil\n @pe = nil\n @te = nil\n @ts = nil\n @act = nil\n @eof = nil\n @top = nil\n @line = { :start => 0, :num => 0 }\n @data = nil\n @stack = nil\n @start = nil\n end\n\n def emit(type, cur = nil)\n @tokens << if cur\n Token.new(type, @data[@start..(@cur - 1)],\n @line[:num], @p - @line[:start])\n else\n Token.new(type, nil, @line[:num], @p - @line[:start])\n end\n end\n\n def error\n raise SyntaxError, \"Unexpected #{@data[@ts..(@te-1)].pack('c*')}\"\n end\n\n def perform(data)\n @data = data.unpack(\"c*\") if data.is_a? String\n @eof = data.length\n\n @tokens = []\n\n line = proc do\n @line[:start] = @ts\n @line[:num] += 1\n emit :newline\n end\n\n %% write init;\n %% write exec;\n\n clean!\n\n @tokens\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"3519fb6c48b1d268daba30677cebbaec2db15624","subject":"Remove admin.rl inherited with merge.","message":"Remove admin.rl inherited with merge.\n","repos":"guard163\/tarantool,ocelot-inc\/tarantool,rtsisyk\/tarantool,condor-the-bird\/tarantool,vasilenkomike\/tarantool,nvoron23\/tarantool,mejedi\/tarantool,condor-the-bird\/tarantool,ocelot-inc\/tarantool,guard163\/tarantool,Sannis\/tarantool,Sannis\/tarantool,rtsisyk\/tarantool,Sannis\/tarantool,rtsisyk\/tarantool,condor-the-bird\/tarantool,Sannis\/tarantool,vasilenkomike\/tarantool,nvoron23\/tarantool,nvoron23\/tarantool,nvoron23\/tarantool,guard163\/tarantool,KlonD90\/tarantool,dkorolev\/tarantool,dkorolev\/tarantool,mejedi\/tarantool,nvoron23\/tarantool,KlonD90\/tarantool,dkorolev\/tarantool,guard163\/tarantool,Sannis\/tarantool,vasilenkomike\/tarantool,dkorolev\/tarantool,dkorolev\/tarantool,KlonD90\/tarantool,KlonD90\/tarantool,mejedi\/tarantool,nvoron23\/tarantool,condor-the-bird\/tarantool,KlonD90\/tarantool,mejedi\/tarantool,condor-the-bird\/tarantool,ocelot-inc\/tarantool,vasilenkomike\/tarantool,rtsisyk\/tarantool,vasilenkomike\/tarantool,ocelot-inc\/tarantool,guard163\/tarantool","old_file":"src\/admin.rl","new_file":"src\/admin.rl","new_contents":"","old_contents":"\/*\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * 1. Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the\n * following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"lua\/init.h\"\n#include \n#include \n#include \"tarantool\/util.h\"\n#include \n#include \"coio_buf.h\"\n\nextern \"C\" {\n#include \n#include \n#include \n}\n\n#include \"box\/box.h\"\n#include \"lua\/init.h\"\n#include \"session.h\"\n#include \"scoped_guard.h\"\n\nstatic const char *help =\n\t\"available commands:\" CRLF\n\t\" - help\" CRLF\n\t\" - exit\" CRLF\n\t\" - show info\" CRLF\n\t\" - show fiber\" CRLF\n\t\" - show configuration\" CRLF\n\t\" - show slab\" CRLF\n\t\" - show palloc\" CRLF\n\t\" - show stat\" CRLF\n\t\" - show plugins\" CRLF\n\t\" - save coredump\" CRLF\n\t\" - save snapshot\" CRLF\n\t\" - lua command\" CRLF\n\t\" - reload configuration\" CRLF\n\t\" - show injections (debug mode only)\" CRLF\n\t\" - set injection (debug mode only)\" CRLF;\n\nstatic const char *unknown_command = \"unknown command. try typing help.\" CRLF;\n\n%%{\n\tmachine admin;\n\twrite data;\n}%%\n\nstruct salloc_stat_admin_cb_ctx {\n\tint64_t total_used;\n\tstruct tbuf *out;\n};\n\nstatic int\nsalloc_stat_admin_cb(const struct slab_cache_stats *cstat, void *cb_ctx)\n{\n\tstruct salloc_stat_admin_cb_ctx *ctx = (struct salloc_stat_admin_cb_ctx *) cb_ctx;\n\n\ttbuf_printf(ctx->out,\n\t\t \" - { item_size: %- 5i, slabs: %- 3i, items: %- 11\" PRIi64\n\t\t \", bytes_used: %- 12\" PRIi64\n\t\t \", bytes_free: %- 12\" PRIi64 \" }\" CRLF,\n\t\t (int)cstat->item_size,\n\t\t (int)cstat->slabs,\n\t\t cstat->items,\n\t\t cstat->bytes_used,\n\t\t cstat->bytes_free);\n\n\tctx->total_used += cstat->bytes_used;\n\treturn 0;\n}\n\nstatic void\nshow_slab(struct tbuf *out)\n{\n\tstruct salloc_stat_admin_cb_ctx cb_ctx;\n\tstruct slab_arena_stats astat;\n\n\tcb_ctx.total_used = 0;\n\tcb_ctx.out = out;\n\n\ttbuf_printf(out, \"slab statistics:\\n classes:\" CRLF);\n\n\tsalloc_stat(salloc_stat_admin_cb, &astat, &cb_ctx);\n\n\ttbuf_printf(out, \" items_used: %.2f%%\" CRLF,\n\t\t(double)cb_ctx.total_used \/ astat.size * 100);\n\ttbuf_printf(out, \" arena_used: %.2f%%\" CRLF,\n\t\t(double)astat.used \/ astat.size * 100);\n}\n\nstatic void\nend(struct tbuf *out)\n{\n\ttbuf_printf(out, \"...\" CRLF);\n}\n\nstatic void\nstart(struct tbuf *out)\n{\n\ttbuf_printf(out, \"---\" CRLF);\n}\n\nstatic void\nok(struct tbuf *out)\n{\n\tstart(out);\n\ttbuf_printf(out, \"ok\" CRLF);\n\tend(out);\n}\n\nstatic void\nfail(struct tbuf *out, struct tbuf *err)\n{\n\tstart(out);\n\ttbuf_printf(out, \"fail:%.*s\" CRLF, err->size, (char *)err->data);\n\tend(out);\n}\n\nstatic void\ntarantool_info(struct tbuf *out)\n{\n\ttbuf_printf(out, \"info:\" CRLF);\n\ttbuf_printf(out, \" version: \\\"%s\\\"\" CRLF, tarantool_version());\n\ttbuf_printf(out, \" uptime: %i\" CRLF, (int)tarantool_uptime());\n\ttbuf_printf(out, \" pid: %i\" CRLF, getpid());\n\ttbuf_printf(out, \" logger_pid: %i\" CRLF, logger_pid);\n\ttbuf_printf(out, \" snapshot_pid: %i\" CRLF, snapshot_pid);\n\ttbuf_printf(out, \" lsn: %\" PRIi64 CRLF,\n\t\t recovery_state->confirmed_lsn);\n\ttbuf_printf(out, \" recovery_lag: %.3f\" CRLF,\n\t\t recovery_state->remote ?\n\t\t recovery_state->remote->recovery_lag : 0);\n\ttbuf_printf(out, \" recovery_last_update: %.3f\" CRLF,\n\t\t recovery_state->remote ?\n\t\t recovery_state->remote->recovery_last_update_tstamp :0);\n\tbox_info(out);\n\tconst char *path = cfg_filename_fullpath;\n\tif (path == NULL)\n\t\tpath = cfg_filename;\n\ttbuf_printf(out, \" config: \\\"%s\\\"\" CRLF, path);\n}\n\nstatic int\nshow_stat_item(const char *name, int rps, int64_t total, void *ctx)\n{\n\tstruct tbuf *buf = (struct tbuf *) ctx;\n\tint name_len = strlen(name);\n\ttbuf_printf(buf,\n\t\t \" %s:%*s{ rps: %- 6i, total: %- 12\" PRIi64 \" }\" CRLF,\n\t\t name, 1 + stat_max_name_len - name_len, \" \", rps, total);\n\treturn 0;\n}\n\nvoid\nshow_stat(struct tbuf *buf)\n{\n\ttbuf_printf(buf, \"statistics:\" CRLF);\n\tstat_foreach(show_stat_item, buf);\n}\n\nstatic int\nadmin_dispatch(struct ev_io *coio, struct iobuf *iobuf, lua_State *L)\n{\n\tstruct ibuf *in = &iobuf->in;\n\tstruct tbuf *out = tbuf_new(fiber->gc_pool);\n\tstruct tbuf *err = tbuf_new(fiber->gc_pool);\n\tint cs;\n\tchar *p, *pe;\n\tchar *strstart, *strend;\n\tbool state;\n\n\twhile ((pe = (char *) memchr(in->pos, '\\n', in->end - in->pos)) == NULL) {\n\t\tif (coio_bread(coio, in, 1) <= 0)\n\t\t\treturn -1;\n\t}\n\n\tpe++;\n\tp = in->pos;\n\n\t%%{\n\t action show_plugins {\n\t\t start(out);\n show_plugins_stat(out);\n\t\t end(out);\n }\n\n\t\taction show_configuration {\n\t\t\tstart(out);\n\t\t\tshow_cfg(out);\n\t\t\tend(out);\n\t\t}\n\n\t\taction show_injections {\n\t\t\tstart(out);\n\t\t\terrinj_info(out);\n\t\t\tend(out);\n\t\t}\n\n\t\taction help {\n\t\t\tstart(out);\n\t\t\ttbuf_append(out, help, strlen(help));\n\t\t\tend(out);\n\t\t}\n\n\t\taction lua {\n\t\t\tstrstart[strend-strstart]='\\0';\n\t\t\tstart(out);\n\t\t\ttarantool_lua(L, out, strstart);\n\t\t\tend(out);\n\t\t}\n\n\t\taction reload_configuration {\n\t\t\tif (reload_cfg(err))\n\t\t\t\tfail(out, err);\n\t\t\telse\n\t\t\t\tok(out);\n\t\t}\n\n\t\taction save_snapshot {\n\t\t\tint ret = snapshot();\n\n\t\t\tif (ret == 0)\n\t\t\t\tok(out);\n\t\t\telse {\n\t\t\t\ttbuf_printf(err, \" can't save snapshot, errno %d (%s)\",\n\t\t\t\t\t ret, strerror(ret));\n\n\t\t\t\tfail(out, err);\n\t\t\t}\n\t\t}\n\n\t\taction set_injection {\n\t\t\tstrstart[strend-strstart] = '\\0';\n\t\t\tif (errinj_set_byname(strstart, state)) {\n\t\t\t\ttbuf_printf(err, \"can't find error injection '%s'\", strstart);\n\t\t\t\tfail(out, err);\n\t\t\t} else {\n\t\t\t\tok(out);\n\t\t\t}\n\t\t}\n\n\t\teol = \"\\n\" | \"\\r\\n\";\n\t\tshow = \"sh\"(\"o\"(\"w\")?)?;\n\t\tinfo = \"in\"(\"f\"(\"o\")?)?;\n\t\tcheck = \"ch\"(\"e\"(\"c\"(\"k\")?)?)?;\n\t\tconfiguration = \"co\"(\"n\"(\"f\"(\"i\"(\"g\"(\"u\"(\"r\"(\"a\"(\"t\"(\"i\"(\"o\"(\"n\")?)?)?)?)?)?)?)?)?)?)?;\n\t\tfiber = \"fi\"(\"b\"(\"e\"(\"r\")?)?)?;\n\t\tslab = \"sl\"(\"a\"(\"b\")?)?;\n\t\tmod = \"mo\"(\"d\")?;\n\t\tpalloc = \"pa\"(\"l\"(\"l\"(\"o\"(\"c\")?)?)?)?;\n\t\tstat = \"st\"(\"a\"(\"t\")?)?;\n\t\tplugins = \"plugins\";\n\n\t\thelp = \"h\"(\"e\"(\"l\"(\"p\")?)?)?;\n\t\texit = \"e\"(\"x\"(\"i\"(\"t\")?)?)? | \"q\"(\"u\"(\"i\"(\"t\")?)?)?;\n\t\tsave = \"sa\"(\"v\"(\"e\")?)?;\n\t\tcoredump = \"co\"(\"r\"(\"e\"(\"d\"(\"u\"(\"m\"(\"p\")?)?)?)?)?)?;\n\t\tsnapshot = \"sn\"(\"a\"(\"p\"(\"s\"(\"h\"(\"o\"(\"t\")?)?)?)?)?)?;\n\t\tstring = [^\\r\\n]+ >{strstart = p;} %{strend = p;};\n\t\treload = \"re\"(\"l\"(\"o\"(\"a\"(\"d\")?)?)?)?;\n\t\tlua = \"lu\"(\"a\")?;\n\n\t\tset = \"se\"(\"t\")?;\n\t\tinjection = \"in\"(\"j\"(\"e\"(\"c\"(\"t\"(\"i\"(\"o\"(\"n\")?)?)?)?)?)?)?;\n\t\tinjections = injection\"s\";\n\t\tnamech = alnum | punct;\n\t\tname = namech+ >{ strstart = p; } %{ strend = p; };\n\t\tstate_on = \"on\" %{ state = true; };\n\t\tstate_off = \"of\"(\"f\")? %{ state = false; };\n\t\tstate = state_on | state_off;\n\n\t\tcommands = (help\t\t\t%help\t\t\t\t\t\t|\n\t\t\t exit\t\t\t%{return -1;}\t\t\t\t\t|\n\t\t\t lua \" \"+ string\t\t%lua\t\t\t\t\t\t|\n\t\t\t show \" \"+ info\t\t%{start(out); tarantool_info(out); end(out);}\t|\n\t\t\t show \" \"+ fiber\t\t%{start(out); fiber_info(out); end(out);}\t|\n\t\t\t show \" \"+ configuration \t%show_configuration\t\t\t\t|\n\t\t\t show \" \"+ slab\t\t%{start(out); show_slab(out); end(out);}\t|\n\t\t\t show \" \"+ palloc\t\t%{start(out); palloc_stat(out); end(out);}\t|\n\t\t\t show \" \"+ stat\t\t%{start(out); show_stat(out);end(out);}\t\t|\n\t\t\t show \" \"+ injections\t%show_injections |\n\t\t\t show \" \"+ plugins %show_plugins |\n\t\t\t set \" \"+ injection \" \"+ name \" \"+ state\t%set_injection |\n\t\t\t save \" \"+ coredump\t\t%{coredump(60); ok(out);}\t\t\t|\n\t\t\t save \" \"+ snapshot\t\t%save_snapshot\t\t\t\t\t|\n\t\t\t check \" \"+ slab\t\t%{slab_validate(); ok(out);}\t\t\t|\n\t\t\t reload \" \"+ configuration\t%reload_configuration);\n\n\t\tmain := commands eol;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\n\tin->pos = pe;\n\n\tif (p != pe) {\n\t\tstart(out);\n\t\ttbuf_append(out, unknown_command, strlen(unknown_command));\n\t\tend(out);\n\t}\n\n\tcoio_write(coio, out->data, out->size);\n\treturn 0;\n}\n\nstatic void\nadmin_handler(va_list ap)\n{\n\tstruct ev_io coio = va_arg(ap, struct ev_io);\n\tstruct sockaddr_in *addr = va_arg(ap, struct sockaddr_in *);\n\tstruct iobuf *iobuf = va_arg(ap, struct iobuf *);\n\tlua_State *L = lua_newthread(tarantool_L);\n\tint coro_ref = luaL_ref(tarantool_L, LUA_REGISTRYINDEX);\n\n\tauto scoped_guard = make_scoped_guard([&] {\n\t\tluaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);\n\t\tevio_close(&coio);\n\t\tiobuf_delete(iobuf);\n\t\tsession_destroy(fiber->sid);\n\t});\n\n\t\/*\n\t * Admin and iproto connections must have a\n\t * session object, representing the state of\n\t * a remote client: it's used in Lua\n\t * stored procedures.\n\t *\/\n\tsession_create(coio.fd, *(uint64_t *) addr);\n\tfor (;;) {\n\t\tif (admin_dispatch(&coio, iobuf, L) < 0)\n\t\t\treturn;\n\t\tiobuf_gc(iobuf);\n\t\tfiber_gc();\n\t}\n}\n\nvoid\nadmin_init(const char *bind_ipaddr, int admin_port)\n{\n\tstatic struct coio_service admin;\n\tcoio_service_init(&admin, \"admin\", bind_ipaddr,\n\t\t\t admin_port, admin_handler, NULL);\n\tevio_service_start(&admin.evio_service);\n}\n\n\/*\n * Local Variables:\n * mode: c\n * End:\n * vim: syntax=objc\n *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"f153ef82ca3699ec9161cb2805f8e7cd53e3c806","subject":"Parse all tag types","message":"Parse all tag types","repos":"wezm\/OCMustache,wezm\/OCMustache","old_file":"MustacheParserMachine.m.rl","new_file":"MustacheParserMachine.m.rl","new_contents":"#import \"MustacheParserMachine.h\"\n#import \n#import \n#import \n#import \n#import \n\n#define LEN(AT, FPC) (FPC - buffer - AT)\n#define MARK(M,FPC) (M = (FPC) - buffer)\n#define PTR_TO(F) (buffer + F)\n\n\/** Machine **\/\n%%{\n\n\tmachine mustache_parser;\n\n\t# Line endings\n\tnewline = ( \"\\r\" | \"\\r\\n\" | \"\\n\" );\n\n\t# Character classes\n\twhite = [ \\t]*;\n\topen = '{' :> '{';\n\tclose = '}' :> '}';\n\n\t# Action\n # # After these types of tags, all whitespace will be skipped.\n # SKIP_WHITESPACE = [ '#', '^', '\/' ]\n #\n # # The content allowed in a tag name.\n # ALLOWED_CONTENT = \/(\\w|[?!\\\/-])*\/\n #\n # # These types of tags allow any content,\n # # the rest only allow ALLOWED_CONTENT.\n # ANY_CONTENT = [ '!', '=' ]\n\n\tidentifier = ( alnum | [?!\/_] | '-')+;\n\t# [a-zA-Z_0-9?!\/]*;\n\t# \/(\\w|[?!\\\/-])*\/;\n\n\t# Tags\n\t#type = [#^\/=<>&{];\n\n\t# var = ( open white identifier white close );\n\t#\n\t# enum = ( open '#' white identifier white close );\n\t#\n\t# inverted = ( open '^' white identifier white close );\n\t#\n\t# end_enum = ( open '\/' white identifier white close );\n\t#\n\t# comment = ( open '!' (any* -- close) close );\n\n\t#body = ( comment | var | enum | nl );\n\n\taction mark { MARK(mark, fpc); }\n\n\taction start_identifier {\n\t\tMARK(identifier_start, fpc);\n\t\tprintf(\"Start of %c tag\\n\", tag_type);\n\t}\n\n\taction got_identifier {\n\t\t\/\/ NSLog(@\"mark %d, len: %d\\n\", mark, LEN(mark, fpc));\n\n\t\tprintf(\"Tag: \");\n\t\tfwrite(PTR_TO(identifier_start), sizeof(char), LEN(identifier_start, fpc), stdout);\n\t\tprintf(\"\\n\");\n\t}\n\n\taction write_static {\n\t\t\/\/ Write out all the static text up to this tag\n\t\tprintf(\"Static text: \");\n\t\tfwrite(PTR_TO(mark), sizeof(char), LEN(mark, fpc), stdout);\n\t\tprintf(\"\\n\");\n\t}\n\n\taction set_type {\n\t\ttag_type = *fpc;\n\t}\n\n\taction init_type {\n\t\ttag_type = '\\0';\n\t}\n\n\ttype = [#^\/=!<>&];\n\n\tvar = (\n\t\topen\n\t\ttype? >init_type $set_type <:\n\t\twhite\n\t\tidentifier >start_identifier %got_identifier\n\t\twhite\n\t\tclose %mark\n\t) >write_static;\n\n\t# Special case for triple mustache\n\tunescaped = (\n\t\topen\n\t\t'{'\n\t\twhite\n\t\tidentifier >start_identifier %got_identifier\n\t\twhite\n\t\t'}'\n\t\tclose %mark\n\t) >write_static;\n\n\ttext = (any+ -- open) ;\n\n\tbody = (\n\t\tvar\n\t\t| text\n\t\t| unescaped\n\t);\n\n\tmain := body* %eof(write_static);\n\n}%%\n\n\/** Data **\/\n%% write data;\n\n@implementation MustacheParserMachine\n\n\/\/int http_parser_init(http_parser *parser) {\n- (id)initWithDelegate:(id)parser_delegate\n{\n\tif((self = [super init]) != nil)\n\t{\n\t\tmark = 0; \/\/ Mark the start of the text\n\t\t%% write init;\n\t\t\/\/delegate = [parser_delegate retain];\n\t}\n\n\treturn self;\n}\n\n\n\/** exec **\/\n\/\/size_t http_parser_execute(http_parser *parser, const char *buffer, size_t len, size_t off) {\n- (size_t)execute:(const char *)buffer length:(size_t)len offset:(size_t)off\n{\n const char *p, *pe, *eof;\n \/\/int cs = parser->cs;\n char tag_type = '\\0';\n\n assert(off <= len && \"offset past end of buffer\");\n\n p = buffer+off;\n pe = buffer+len;\n eof = pe;\n\n assert(*pe == '\\0' && \"pointer does not end on NUL\");\n assert(pe - p == len - off && \"pointers aren't same distance\");\n\n\n %% write exec;\n\n \/\/parser->cs = cs;\n nread += p - (buffer + off);\n\/\/\n\/\/ assert(p <= pe && \"buffer overflow after parsing execute\");\n assert(nread <= len && \"nread longer than length\");\n\/\/ assert(body_start <= len && \"body starts after buffer end\");\n\/\/ assert(mark < len && \"mark is after buffer end\");\n\/\/ assert(field_len <= len && \"field has length longer than whole buffer\");\n\/\/ assert(field_start < len && \"field starts after buffer end\");\n\n\/\/ if(body_start) {\n\/\/ \/* final \\r\\n combo encountered so stop right here *\/\n\/\/ \/\/%%write eof;\n\/\/ nread++;\n\/\/ }\n\n \/\/return nread;\n return 0;\n}\n\n- (int)finish {\n if ([self hasError]) {\n return -1;\n } else if ([self isFinished]) {\n return 1;\n } else {\n return 0;\n }\n}\n\n- (BOOL)hasError\n{\n return cs == mustache_parser_error ? YES : NO;\n}\n\n- (BOOL)isFinished\n{\n return cs == mustache_parser_first_final ? YES : NO;\n}\n\n- (size_t)bytesRead\n{\n\treturn nread;\n}\n\n\/\/- (void)dealloc\n\/\/{\n\/\/\t[delegate release];\n\/\/\t[super dealloc];\n\/\/}\n\n@end\n","old_contents":"#import \"MustacheParserMachine.h\"\n#import \n#import \n#import \n#import \n#import \n\n#define LEN(AT, FPC) (FPC - buffer - AT)\n#define MARK(M,FPC) (M = (FPC) - buffer)\n#define PTR_TO(F) (buffer + F)\n\n\/** Machine **\/\n%%{\n\n\tmachine mustache_parser;\n\n\t# Line endings\n\tnewline = ( \"\\r\" | \"\\r\\n\" | \"\\n\" );\n\n\t# Character classes\n\twhite = [ \\t]*;\n\topen = '{' :> '{';\n\tclose = '}' :> '}';\n\n\t# Action\n # # After these types of tags, all whitespace will be skipped.\n # SKIP_WHITESPACE = [ '#', '^', '\/' ]\n #\n # # The content allowed in a tag name.\n # ALLOWED_CONTENT = \/(\\w|[?!\\\/-])*\/\n #\n # # These types of tags allow any content,\n # # the rest only allow ALLOWED_CONTENT.\n # ANY_CONTENT = [ '!', '=' ]\n\n\tidentifier = ( alnum | [?!\/] | '-')+;\n\t# [a-zA-Z_0-9?!\/]*;\n\t# \/(\\w|[?!\\\/-])*\/;\n\n\t# Tags\n\t#type = [#^\/=<>&{];\n\n\t# var = ( open white identifier white close );\n\t#\n\t# enum = ( open '#' white identifier white close );\n\t#\n\t# inverted = ( open '^' white identifier white close );\n\t#\n\t# end_enum = ( open '\/' white identifier white close );\n\t#\n\t# comment = ( open '!' (any* -- close) close );\n\n\t#body = ( comment | var | enum | nl );\n\n\taction mark { MARK(mark, fpc); }\n\n\taction start_identifier {\n\t\tMARK(identifier_start, fpc);\n\t}\n\n\taction got_identifier {\n\t\t\/\/ NSLog(@\"mark %d, len: %d\\n\", mark, LEN(mark, fpc));\n\n\t\tprintf(\"Tag: \");\n\t\tfwrite(PTR_TO(identifier_start), sizeof(char), LEN(identifier_start, fpc), stdout);\n\t\tprintf(\"\\n\");\n\t}\n\n\taction write_static {\n\t\t\/\/ Write out all the static text up to this tag\n\t\tprintf(\"Static text: \");\n\t\tfwrite(PTR_TO(mark), sizeof(char), LEN(mark, fpc), stdout);\n\t\tprintf(\"\\n\");\n\t}\n\n\t#tag_type = [&\/<>{^];\n\n\ttag = (\n\t\topen\n\t\twhite\n\t\tidentifier >start_identifier %got_identifier\n\t\twhite\n\t\tclose %mark\n\t) >write_static;\n\n\ttext = (any+ -- open) ;\n\n\tmain := (\n\t\ttag |\n\t\ttext\n\t)* %eof(write_static);\n\n}%%\n\n\/** Data **\/\n%% write data;\n\n@implementation MustacheParserMachine\n\n\/\/int http_parser_init(http_parser *parser) {\n- (id)initWithDelegate:(id)parser_delegate\n{\n\tif((self = [super init]) != nil)\n\t{\n\t\tmark = 0; \/\/ Mark the start of the text\n\t\t%% write init;\n\t\t\/\/delegate = [parser_delegate retain];\n\t}\n\n\treturn self;\n}\n\n\n\/** exec **\/\n\/\/size_t http_parser_execute(http_parser *parser, const char *buffer, size_t len, size_t off) {\n- (size_t)execute:(const char *)buffer length:(size_t)len offset:(size_t)off\n{\n const char *p, *pe, *eof;\n \/\/int cs = parser->cs;\n\n assert(off <= len && \"offset past end of buffer\");\n\n p = buffer+off;\n pe = buffer+len;\n eof = pe;\n\n assert(*pe == '\\0' && \"pointer does not end on NUL\");\n assert(pe - p == len - off && \"pointers aren't same distance\");\n\n\n %% write exec;\n\n \/\/parser->cs = cs;\n nread += p - (buffer + off);\n\/\/\n\/\/ assert(p <= pe && \"buffer overflow after parsing execute\");\n assert(nread <= len && \"nread longer than length\");\n\/\/ assert(body_start <= len && \"body starts after buffer end\");\n\/\/ assert(mark < len && \"mark is after buffer end\");\n\/\/ assert(field_len <= len && \"field has length longer than whole buffer\");\n\/\/ assert(field_start < len && \"field starts after buffer end\");\n\n\/\/ if(body_start) {\n\/\/ \/* final \\r\\n combo encountered so stop right here *\/\n\/\/ \/\/%%write eof;\n\/\/ nread++;\n\/\/ }\n\n \/\/return nread;\n return 0;\n}\n\n- (int)finish {\n if ([self hasError]) {\n return -1;\n } else if ([self isFinished]) {\n return 1;\n } else {\n return 0;\n }\n}\n\n- (BOOL)hasError\n{\n return cs == mustache_parser_error ? YES : NO;\n}\n\n- (BOOL)isFinished\n{\n return cs == mustache_parser_first_final ? YES : NO;\n}\n\n- (size_t)bytesRead\n{\n\treturn nread;\n}\n\n\/\/- (void)dealloc\n\/\/{\n\/\/\t[delegate release];\n\/\/\t[super dealloc];\n\/\/}\n\n@end\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"88c11c323ab1b3a784861dc2f96f83a542e1d43e","subject":"Avoid leaking the strdup'd segments pushed to the queue.","message":"Avoid leaking the strdup'd segments pushed to the queue.\n","repos":"lscube\/feng,lscube\/feng,winlinvip\/feng,lscube\/feng,winlinvip\/feng,winlinvip\/feng","old_file":"src\/network\/ragel_uri.rl","new_file":"src\/network\/ragel_uri.rl","new_contents":"\/* -*-c-*- *\/\n\/* This file is part of liberis\n *\n * Copyright (C) 2008 by LScube team \n * See AUTHORS for more details\n *\n * liberis is free software: you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * liberis is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with liberis. If not, see\n * .\n *\/\n\n#include \n#include \n#include \"uri.h\"\n\n%%{\n machine uri_parser;\n\tinclude common \"common.rl\";\n\n action collapse_path {\n if ( ! g_queue_is_empty(stack) ) {\n GString *uri_path = g_string_new(\"\");\n g_queue_foreach(stack, append_to_string, uri_path);\n uri->path = g_string_free(uri_path, FALSE);\n }\n }\n\n\treg_name = ( unreserved | pct_encoded | sub_delims )*;\n\thost = IP_literal | IPv4address | reg_name;\n\tauthority = ( userinfo >mark\n %{uri->userinfo = g_strndup(mark, fpc-mark);}\n \"@\" )?\n host >mark\n %{uri->host = g_strndup(mark, fpc-mark);}\n ( \":\" digit* >mark\n %{uri->port = g_strndup(mark, fpc-mark);})?;\n\tpchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n\tsegment = ( pchar+ - \"..\" - \".\" ) >mark\n %{mark = g_strndup(mark, fpc-mark);\n g_queue_push_tail(stack, mark);}|\n \"..\" %{g_queue_pop_tail(stack);}|\n zlen | \".\";\n\tpath_abempty = ( \"\/\" segment )*;\n\tsegment_nz = ( pchar+ - \"..\" ) | \"..\";\n\tpath_absolute = \"\/\" ( segment_nz ( \"\/\" segment )* )?;\n\tpath_rootless = segment_nz ( \"\/\" segment )*;\n\tpath_empty = empty;\n\thier_part = ( \"\/\/\" authority path_abempty ) | path_absolute | path_rootless | path_empty;\n\tquery = ( pchar | \"\/\" | \"?\" )*;\n\tfragment = ( pchar | \"\/\" | \"?\" )*;\n\tURI = scheme >mark\n %{uri->scheme = g_strndup(mark, fpc-mark);}\n \":\" hier_part ( \"?\" query >mark\n %{uri->query = g_strndup(mark, fpc-mark);}\n )? ( \"#\" fragment >mark\n %{uri->fragment = g_strndup(mark, fpc-mark);} )?\n %(collapse_path);\n\tsegment_nz_nc = ( unreserved | pct_encoded | sub_delims | \"@\" )+;\n\tpath_noscheme = segment_nz_nc ( \"\/\" segment )*;\n\trelative_part = ( \"\/\/\" authority path_abempty ) | path_absolute | path_noscheme | path_empty;\n\trelative_ref = relative_part ( \"?\" query )? ( \"#\" fragment )?;\n\tURI_reference = URI | relative_ref;\n\tabsolute_URI = scheme \":\" hier_part ( \"?\" query )?;\n\tpath = path_abempty | path_absolute | path_noscheme | path_rootless | path_empty;\n\tgen_delims = \":\" | \"\/\" | \"?\" | \"#\" | \"[\" | \"]\" | \"@\";\n\treserved = gen_delims | sub_delims;\n\n # instantiate machine rules\n main:= URI 0;\n}%%\n\nstatic void append_to_string(gpointer data, gpointer user_data)\n{\n GString *path = (GString*)user_data;\n char *segment = (char *)data;\n g_string_append_printf(path, \"\/%s\", segment);\n}\n\nstatic void segment_free(gpointer data, ATTR_UNUSED gpointer unused)\n{\n g_free(data);\n}\n\n\/**\n * @brief Parse and split an URI string into an URI structure\n *\n * @param uri_string The URI string to parse and split\n *\n * @return A pointer to a newly-allocated URI structure.\n *\n * This function parses an URI, as defined by RFC1738, and splits it\n * into its components in the given structure.\n *\/\nURI *uri_parse(const char *uri_string)\n{\n const char *p = uri_string, *pe = p + strlen(p) + 1, *mark;\n GQueue *stack = g_queue_new();\n URI *uri = g_slice_new0(URI);\n int cs;\n\n %% write data;\n %% write init;\n %% write exec;\n\n g_queue_foreach(stack, segment_free, NULL);\n g_queue_free(stack);\n\n if (cs < uri_parser_first_final) {\n uri_free(uri);\n return NULL;\n }\n\n return uri;\n}\n","old_contents":"\/* -*-c-*- *\/\n\/* This file is part of liberis\n *\n * Copyright (C) 2008 by LScube team \n * See AUTHORS for more details\n *\n * liberis is free software: you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * liberis is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with liberis. If not, see\n * .\n *\/\n\n#include \n#include \n#include \"uri.h\"\n\n%%{\n machine uri_parser;\n\tinclude common \"common.rl\";\n\n action collapse_path {\n if ( ! g_queue_is_empty(stack) ) {\n GString *uri_path = g_string_new(\"\");\n g_queue_foreach(stack, append_to_string, uri_path);\n uri->path = g_string_free(uri_path, FALSE);\n }\n }\n\n\treg_name = ( unreserved | pct_encoded | sub_delims )*;\n\thost = IP_literal | IPv4address | reg_name;\n\tauthority = ( userinfo >mark\n %{uri->userinfo = g_strndup(mark, fpc-mark);}\n \"@\" )?\n host >mark\n %{uri->host = g_strndup(mark, fpc-mark);}\n ( \":\" digit* >mark\n %{uri->port = g_strndup(mark, fpc-mark);})?;\n\tpchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n\tsegment = ( pchar+ - \"..\" - \".\" ) >mark\n %{mark = g_strndup(mark, fpc-mark);\n g_queue_push_tail(stack, mark);}|\n \"..\" %{g_queue_pop_tail(stack);}|\n zlen | \".\";\n\tpath_abempty = ( \"\/\" segment )*;\n\tsegment_nz = ( pchar+ - \"..\" ) | \"..\";\n\tpath_absolute = \"\/\" ( segment_nz ( \"\/\" segment )* )?;\n\tpath_rootless = segment_nz ( \"\/\" segment )*;\n\tpath_empty = empty;\n\thier_part = ( \"\/\/\" authority path_abempty ) | path_absolute | path_rootless | path_empty;\n\tquery = ( pchar | \"\/\" | \"?\" )*;\n\tfragment = ( pchar | \"\/\" | \"?\" )*;\n\tURI = scheme >mark\n %{uri->scheme = g_strndup(mark, fpc-mark);}\n \":\" hier_part ( \"?\" query >mark\n %{uri->query = g_strndup(mark, fpc-mark);}\n )? ( \"#\" fragment >mark\n %{uri->fragment = g_strndup(mark, fpc-mark);} )?\n %(collapse_path);\n\tsegment_nz_nc = ( unreserved | pct_encoded | sub_delims | \"@\" )+;\n\tpath_noscheme = segment_nz_nc ( \"\/\" segment )*;\n\trelative_part = ( \"\/\/\" authority path_abempty ) | path_absolute | path_noscheme | path_empty;\n\trelative_ref = relative_part ( \"?\" query )? ( \"#\" fragment )?;\n\tURI_reference = URI | relative_ref;\n\tabsolute_URI = scheme \":\" hier_part ( \"?\" query )?;\n\tpath = path_abempty | path_absolute | path_noscheme | path_rootless | path_empty;\n\tgen_delims = \":\" | \"\/\" | \"?\" | \"#\" | \"[\" | \"]\" | \"@\";\n\treserved = gen_delims | sub_delims;\n\n # instantiate machine rules\n main:= URI 0;\n}%%\n\nstatic void append_to_string(gpointer data, gpointer user_data)\n{\n GString *path = (GString*)user_data;\n char *segment = (char *)data;\n g_string_append_printf(path, \"\/%s\", segment);\n}\n\n\/**\n * @brief Parse and split an URI string into an URI structure\n *\n * @param uri_string The URI string to parse and split\n *\n * @return A pointer to a newly-allocated URI structure.\n *\n * This function parses an URI, as defined by RFC1738, and splits it\n * into its components in the given structure.\n *\/\nURI *uri_parse(const char *uri_string)\n{\n const char *p = uri_string, *pe = p + strlen(p) + 1, *mark;\n GQueue *stack = g_queue_new();\n URI *uri = g_slice_new0(URI);\n int cs;\n\n %% write data;\n %% write init;\n %% write exec;\n\n g_queue_free(stack);\n\n if (cs < uri_parser_first_final) {\n uri_free(uri);\n return NULL;\n }\n\n return uri;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"dfdd5335adfee7e74c06f8adb91417edaea25832","subject":"went on commenting mtoc","message":"went on commenting mtoc\n\nConflicts:\n\n\t3rd_party\/mtoc\/confscanner.rl\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"confscanner.rl","new_file":"confscanner.rl","new_contents":"#include \"confscanner.h\"\n\nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::set;\nusing std::ifstream;\n\n%%{\n machine ConfFileScanner;\n write data;\n\n # store current char pointer p in tmp_p\n action st_tok { tmp_p = p; }\n\n # assign a string token to tmp_string variable\n action string_tok {\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # add groupname to groupset_ if glob expression matches\n action group_add\n {\n \/\/ check wether glob expression matches\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/ clear groupset_ first, if we did not use '+='\n if(!arg_to_be_added_)\n groupset_.clear();\n\n groupset_.insert(tmp_string);\n }\n }\n\n # set cblock_ to selected documentation block as specified in an expression\n # \"add(specifier)\"\n action set_docu_block\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"brief\")\n cblock_ = &docuheader_;\n else if(tmp_string == \"doc\")\n cblock_ = &docubody_;\n else if(tmp_string == \"extra\")\n cblock_ = &docuextra_;\n }\n\n # set clist_ to selected documentation block list as specified in an\n # expression \"add(params)\" or \"add(return)\"\n action set_docu_list\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"docu_list: \" << tmp_string << \"\\n\";\n if(tmp_string == \"params\")\n {\n \/\/cerr << \"paramlist\\n\";\n clist_ = ¶m_list_;\n }\n else if(tmp_string == \"return\")\n clist_ = &return_list_;\n }\n\n # set clistmap_ to selected documentation block list map as specified in an\n # expression \"add(fields)\"\n action set_docu_list_map\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"fields\")\n clistmap_ = &field_docu_;\n }\n\n # add line of a block to the cblock structure which can be one of\n # docublock, docuheader, docuextra or clist[] or clistmap[][]\n action add_block_line\n {\n \/\/ check wether glob expression matches\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n string :: size_type found = tmp_string.find_first_not_of(\" \\t\");\n if(found == string::npos || string(tmp_string.substr(found)) != \"\\\"\\\"\")\n {\n found = tmp_string.rfind(\"\\\"\");\n if(found != string::npos && string(tmp_string.substr(found-1)) == \"\\\"\\\"\")\n {\n \/\/cerr << \"a1: \" << tmp_string.substr(0, found-1) + '\\n';\n (*cblock_).push_back(tmp_string.substr(0, found-1) + '\\n');\n \/\/cerr << \"after a1: \" << param_list_[\"detailed_data\"][0];\n }\n else\n {\n \/\/cerr << \"a2: \" << tmp_string + '\\n';\n (*cblock_).push_back(tmp_string + '\\n');\n }\n }\n opt = true;\n }\n }\n\n # set the cblock pointer to clist_[value]\n action set_block_from_list\n {\n \/\/ check wether glob expression matches\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"ts:\" << tmp_string << \":ets\\n\";\/\/<< \" \" << tmp_p << \"p: \" << p << \"\\n\";\n cblock_ = &((*clist_)[tmp_string]);\n }\n }\n\n # set the cblock pointer to clist_[value1][value2]\n action set_block_from_listmap\n {\n string s(tmp_p, p-tmp_p);\n cblock_ = &((*clistmap_)[tmp_string][s]);\n }\n\n action reg_glob\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"glob: \" << tmp_string << endl;\n \/\/ TODO: use globlist_map\n globlist_stack_.back().push_back(tmp_string);\n }\n\n # end of file\n EOF = 0;\n\n # end of line (CRLF, LF)\n EOL = '\\r'? . '\\n';\n\n # any not end of file character\n default = ^0;\n\n # identifier\n IDENT = [A-Z]+;\n\n # matlab identifier\n MIDENT = [A-Za-z][A-Za-z0-9_]*;\n\n # glob expression\n GLOB = (default - [\\n \\t;\\{])+;\n\n # swallow till the end of line\n garbling := (default - '\\n')* . EOL @{line++;fret;};\n\n # parameter values for single documentation blocks\n add_param_docu_block = ('brief'|'doc'|'extra');\n # parameter values for lists of documentation blocks\n add_param_docu_list = ('params'|'return');\n # parameter values for a map of lists of documentation blocks\n add_param_docu_list_map = ('fields');\n\n # matlab white space or comment\n MWSOC = (\n [ \\t]\n | EOL @{line++;}\n | (('#'. any) -'##') @{ \/*cerr << \"l: \" << line << \"\\n\";*\/ fhold;fcall garbling; }\n );\n# MWSOC = ( [ \\t\\n]);\n\n # equal sign or += sign\n EQ = ('+'? @{arg_to_be_added_ = true;} . '=');\n\n # end of a rule sign\n ENDRULE = ';' @{arg_to_be_added_ = false;};\n\n # add line in a documentation block\n docu_block_line :=\n (\n # default action (just copy text to tmp_p)\n ( ( default - [\"\\n] )+ >{ if(opt) { tmp_p = p; } } )\n |\n # end line in documenation block (calls add_block_line)\n EOL @(add_block_line) @{line++;}\n |\n # end of documentation block (calls add_block_line)\n '\"\"\"' @(add_block_line) @{fret;}\n |\n # ignore quotes (less than 3 in a row)\n ('\"'{1,2} . (default - [\"\\n])) @{ fhold; opt=false; }\n )**;\n\n # begin documentation block\n docu_block = ('\"\"\"'\n @{\n opt=true;\n if(!arg_to_be_added_)\n (*cblock_).clear();\n fcall docu_block_line;\n }\n );\n\n # documentation list item (something like key => value)\n docu_list_item =\n (\n ( MIDENT\n >{tmp_p = p;}\n %(set_block_from_list)\n ) . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n # a list of documentation block lists\n docu_list = (\n (\n '('\n . ( MWSOC* . docu_list_item . MWSOC* . ',')*\n . MWSOC* . docu_list_item . MWSOC* . ')'\n )\n |\n docu_list_item\n );\n\n # documentation list map item\n docu_list_map_item =\n (\n # matlab identifier (structure)\n (MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi\\n\";*\/} %(string_tok)\n )\n . '.'\n # matlab identifer (fieldname)\n .(MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi2\\n\";*\/} %(set_block_from_listmap)\n )\n . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n # a map of documentation block lists\n docu_list_map = (\n (\n '('\n . ( MWSOC* . docu_list_map_item . MWSOC* . ',')*\n . MWSOC* . docu_list_map_item . MWSOC* . ')'\n )\n |\n docu_list_map_item\n );\n\n # list of file matching words\n globlist =\n (GLOB >{\/*cerr << \"glob_list\";*\/ tmp_p = p;} %(reg_glob))\n . (MWSOC* . [ \\t]+ . MWSOC*\n . (GLOB >{\/*cerr << \"glob list2\";*\/ tmp_p = p;} %(reg_glob)))*;\n\n # list of group names\n grouplist = (\n # matlab identifier (group name)\n ((MIDENT >(st_tok)\n %(group_add))\n . ',')*\n # matlab identifier (group name)\n .(MIDENT >(st_tok)\n %(group_add))\n );\n\n # specify all possible rules\n rules := (\n # glob list\n ('glob' .MWSOC* . '=' . MWSOC* . globlist . MWSOC* . '{')\n @{ check_glob_level_up(); fcall rules; }\n |\n (MWSOC)\n |\n # groups rule\n ('groups'. MWSOC* . EQ\n . MWSOC* . grouplist . MWSOC* . ENDRULE)\n |\n # add rule\n ('add(' %{\/*cerr << \"add:\" << '\\n';*\/ tmp_p = p;}\n . (\n # add documentation block (brief, docu, extra)\n ((add_param_docu_block\n %(set_docu_block)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* . docu_block . MWSOC* . ENDRULE )\n |\n # add documentation list (documentation block for a parameter or a\n # parameter or a return value)\n ((add_param_docu_list\n %(set_docu_list)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list . MWSOC* . ENDRULE )\n |\n # add a map of documentation lists (documentation blocks for structure\n # fields of parameters or return values)\n ((add_param_docu_list_map\n %(set_docu_list_map)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list_map . MWSOC* ENDRULE )\n )\n )\n |\n # go level down (end of a glob match block)\n ('}') @{ go_level_down(); fret; }\n )*;\n\n # main parser (first entry point) This block comprises variable definitions.\n main := (\n # ignored characters\n MWSOC\n | (\n # variable definitions (not yet implemented)\n (IDENT\n >(st_tok)\n %(string_tok)\n ). MWSOC* . ':=' . MWSOC*\n . (GLOB >st_tok @{\/*TODO*\/})\n . (MWSOC* . (GLOB >st_tok @{\/*TODO*\/}))*\n . MWSOC*\n . ';'\n )\n |\n # end variable definitions\n '##' . [ \\t]* . EOL @{ line++; \/*cerr<<\"-> rules\\n\";*\/ fgoto rules; }\n )**;\n}%%\n\n\/\/ this method is called when a glob ... {} block ends\nvoid ConfFileScanner :: go_level_down()\n{\n globlist_stack_.pop_back();\n globlist_stack_.back().clear();\n level_--;\n}\n\n\/\/ checks wether the string ist matched by a glob from the globlist_stack_ at\n\/\/ level \\a l\nbool ConfFileScanner :: check_for_match(int l, const char * str,\n bool match_path_sep)\n{\n typedef GlobList :: iterator iterator;\n \/\/ get globlist at stack level \\a l\n GlobList & gl = globlist_stack_[l];\n\n iterator endit = gl.end();\n int flags = (match_path_sep? FNM_PATHNAME : 0);\n \/\/ iterate over all globs\n for( iterator it = gl.begin(); it != endit; it++ )\n {\n \/\/ check wether str matches glob\n if(fnmatch((*it).c_str(), str, flags) == 0)\n {\n return true;\n }\n }\n return false;\n}\n\n\/\/ check recursively wether file named \\a s is matched by a glob from the\n\/\/ globlist_stack_\nbool ConfFileScanner :: check_glob_rec(int l, const string & s)\n{\n string str;\n string :: size_type found;\n \/\/ exit condition (if filename ist matched up to level level_+1 the check was\n \/\/ successful.\n if(l == level_+1)\n return true;\n\n found = s.find(\"\/\"); \/\/ try to match dir in path\n while(found != string :: npos)\n {\n str = s.substr(0, found);\n \/\/ first try to match the prepended path by a glob at this level, ...\n if(check_for_match(l, str.c_str())\n \/\/ ... then try to match the rest of the substring at a higher level.\n && check_glob_rec(l+1, s.substr(found+1)))\n return true;\n\n found = s.find(\"\/\", found+1); \/\/ try to match more dirs\n }\n if(l == level_) \/\/ try also to match the entire string at this level\n {\n if(check_for_match(l, s.c_str()))\n return true;\n }\n\n return false;\n}\n\n\/\/ this method is called after a glob ... = {} block begins\n\/\/ and sets the match_at_level_ structure for the active file named \n\/\/ \\a filename_\nvoid ConfFileScanner :: check_glob_level_up()\n{\n \/\/ update match_at_level_\n match_at_level_[level_+1] = check_glob_rec(0, filename_);\n\n \/\/ add empty glob list\n globlist_stack_.push_back(GlobList());\n level_++;\n}\n\n\/\/ constructor\nConfFileScanner\n:: ConfFileScanner(const std::string & filename, const std::string & conffilename)\n : line(1), have(0), top(0), opt(true),\n filename_(filename),\n conffile_(conffilename == \"\" ? \"doxygen\/mtoc.conf\" : conffilename),\n confistream_(get_conffile()),\n level_(0),\n arg_to_be_added_(false)\n{\n if ( (confistream_.rdstate() & ifstream::failbit ) != 0 )\n {\n cerr << \"Error opening configuration file '\" << conffilename << \"'\\n\";\n exit(-2);\n }\n globlist_stack_.push_back(GlobList());\n \/\/ at level 0 every file is matched ( no glob checking )\n match_at_level_[0] = true;\n}\n\n\/\/ returns the name of the configuration file\nconst char * ConfFileScanner ::\nget_conffile()\n{\n return conffile_.c_str();\n}\n\n\/\/ run the conffile scanner\nint ConfFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p;\/\/ *tmp_p2 = p;\n \/\/ string for temporary tokens\n string tmp_string;\n \/\/ spare space in buffer\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(1);\n }\n\n \/\/ read configuration file chunk in buffer\n confistream_.read( p, space );\n int len = confistream_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( confistream_.eof() )\n {\n eof = pe;\n done = true;\n }\n else\n {\n \/* Find the last semicolon by searching backwards. This\n * is where we will stop processing on this iteration. *\/\n while ( *pe!= ';' && pe > p )\n pe--;\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == ConfFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"in conffile: PARSE ERROR in line \" << line << endl;\n exit(1);\n }\n\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n\n return 0;\n}\n\/* vim: set et sw=2 ft=ragel: *\/\n","old_contents":"#include \"confscanner.h\"\n\nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::set;\nusing std::ifstream;\n\n%%{\n machine ConfFileScanner;\n write data;\n\n # store current char pointer p in tmp_p\n action st_tok { tmp_p = p; }\n\n # assign a string token to tmp_string variable\n action string_tok {\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # add groupname to groupset_ if glob expression matches\n action group_add\n {\n \/\/ check wether glob expression matches\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/ clear groupset_ first, if we did not use '+='\n if(!arg_to_be_added_)\n groupset_.clear();\n\n groupset_.insert(tmp_string);\n }\n }\n\n # set cblock_ to selected documentation block as specified in an expression\n # \"add(specifier)\"\n action set_docu_block\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"brief\")\n cblock_ = &docuheader_;\n else if(tmp_string == \"doc\")\n cblock_ = &docubody_;\n else if(tmp_string == \"extra\")\n cblock_ = &docuextra_;\n }\n\n # set clist_ to selected documentation block list as specified in an\n # expression \"add(params)\" or \"add(return)\"\n action set_docu_list\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"docu_list: \" << tmp_string << \"\\n\";\n if(tmp_string == \"params\")\n {\n \/\/cerr << \"paramlist\\n\";\n clist_ = ¶m_list_;\n }\n else if(tmp_string == \"return\")\n clist_ = &return_list_;\n }\n\n # set clistmap_ to selected documentation block list map as specified in an\n # expression \"add(fields)\"\n action set_docu_list_map\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"fields\")\n clistmap_ = &field_docu_;\n }\n\n # add line of a block to the cblock structure which can be one of\n # docublock, docuheader, docuextra or clist[] or clistmap[][]\n action add_block_line\n {\n \/\/ check wether glob expression matches\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n string :: size_type found = tmp_string.find_first_not_of(\" \\t\");\n if(found == string::npos || string(tmp_string.substr(found)) != \"\\\"\\\"\")\n {\n found = tmp_string.rfind(\"\\\"\");\n if(found != string::npos && string(tmp_string.substr(found-1)) == \"\\\"\\\"\")\n {\n \/\/cerr << \"a1: \" << tmp_string.substr(0, found-1) + '\\n';\n (*cblock_).push_back(tmp_string.substr(0, found-1) + '\\n');\n \/\/cerr << \"after a1: \" << param_list_[\"detailed_data\"][0];\n }\n else\n {\n \/\/cerr << \"a2: \" << tmp_string + '\\n';\n (*cblock_).push_back(tmp_string + '\\n');\n }\n }\n opt = true;\n }\n }\n\n # set the cblock pointer to clist_[value]\n action set_block_from_list\n {\n \/\/ check wether glob expression matches\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"ts:\" << tmp_string << \":ets\\n\";\/\/<< \" \" << tmp_p << \"p: \" << p << \"\\n\";\n cblock_ = &((*clist_)[tmp_string]);\n }\n }\n\n # set the cblock pointer to clist_[value1][value2]\n action set_block_from_listmap\n {\n string s(tmp_p, p-tmp_p);\n cblock_ = &((*clistmap_)[tmp_string][s]);\n }\n\n action reg_glob\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"glob: \" << tmp_string << endl;\n \/\/ TODO: use globlist_map\n globlist_stack_.back().push_back(tmp_string);\n }\n\n # end of file\n EOF = 0;\n\n # end of line (CRLF, LF)\n EOL = '\\r'? . '\\n';\n\n # any not end of file character\n default = ^0;\n\n # identifier\n IDENT = [A-Z]+;\n\n # matlab identifier\n MIDENT = [A-Za-z][A-Za-z0-9_]*;\n\n # glob expression\n GLOB = (default - [\\n \\t;\\{])+;\n\n # swallow till the end of line\n garbling := (default - '\\n')* . EOL @{line++;fret;};\n\n # parameter values for single documentation blocks\n add_param_docu_block = ('brief'|'doc'|'extra');\n # parameter values for lists of documentation blocks\n add_param_docu_list = ('params'|'return');\n # parameter values for a map of lists of documentation blocks\n add_param_docu_list_map = ('fields');\n\n # matlab white space or comment\n MWSOC = (\n [ \\t]\n | EOL @{line++;}\n | (('#'. any) -'##') @{ \/*cerr << \"l: \" << line << \"\\n\";*\/ fhold;fcall garbling; }\n );\n# MWSOC = ( [ \\t\\n]);\n\n # equal sign or += sign\n EQ = ('+'? @{arg_to_be_added_ = true;} . '=');\n\n # end of a rule sign\n ENDRULE = ';' @{arg_to_be_added_ = false;};\n\n # line in documentation block\n docu_block_line :=\n (\n ( ( default - [\"\\n] )+ >{ if(opt) { tmp_p = p; } } )\n |\n EOL @(add_block_line) @{line++;}\n |\n '\"\"\"' @(add_block_line) @{fret;}\n |\n ('\"'{1,2} . (default - [\"\\n])) @{ fhold; opt=false; }\n )**;\n\n # begin documentation block\n docu_block = ('\"\"\"'\n @{\n opt=true;\n if(!arg_to_be_added_)\n (*cblock_).clear();\n fcall docu_block_line;\n }\n );\n\n # documentation list item (something like key => value)\n docu_list_item =\n (\n ( MIDENT\n >{tmp_p = p;}\n %(set_block_from_list)\n ) . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n # a list of documentation block lists\n docu_list = (\n (\n '('\n . ( MWSOC* . docu_list_item . MWSOC* . ',')*\n . MWSOC* . docu_list_item . MWSOC* . ')'\n )\n |\n docu_list_item\n );\n\n # documentation list map item\n docu_list_map_item =\n (\n # matlab identifier (structure)\n (MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi\\n\";*\/} %(string_tok)\n )\n . '.'\n # matlab identifer (fieldname)\n .(MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi2\\n\";*\/} %(set_block_from_listmap)\n )\n . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n # a map of documentation block lists\n docu_list_map = (\n (\n '('\n . ( MWSOC* . docu_list_map_item . MWSOC* . ',')*\n . MWSOC* . docu_list_map_item . MWSOC* . ')'\n )\n |\n docu_list_map_item\n );\n\n # list of file matching words\n globlist =\n (GLOB >{\/*cerr << \"glob_list\";*\/ tmp_p = p;} %(reg_glob))\n . (MWSOC* . [ \\t]+ . MWSOC*\n . (GLOB >{\/*cerr << \"glob list2\";*\/ tmp_p = p;} %(reg_glob)))*;\n\n # list of group names\n grouplist = (\n # matlab identifier (group name)\n ((MIDENT >(st_tok)\n %(group_add))\n . ',')*\n # matlab identifier (group name)\n .(MIDENT >(st_tok)\n %(group_add))\n );\n\n # specify all possible rules\n rules := (\n # glob list\n ('glob' .MWSOC* . '=' . MWSOC* . globlist . MWSOC* . '{')\n @{ check_glob_level_up(); fcall rules; }\n |\n (MWSOC)\n |\n # groups rule\n ('groups'. MWSOC* . EQ\n . MWSOC* . grouplist . MWSOC* . ENDRULE)\n |\n # add rule\n ('add(' %{\/*cerr << \"add:\" << '\\n';*\/ tmp_p = p;}\n . (\n ((add_param_docu_block\n %(set_docu_block)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* . docu_block . MWSOC* . ENDRULE )\n |\n ((add_param_docu_list\n %(set_docu_list)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list . MWSOC* . ENDRULE )\n |\n ((add_param_docu_list_map\n %(set_docu_list_map)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list_map . MWSOC* ENDRULE )\n )\n )\n |\n # go level down\n ('}') @{ go_level_down(); fret; }\n )*;\n\n main := (\n MWSOC\n | (\n (IDENT\n >(st_tok)\n %(string_tok)\n ). MWSOC* . ':=' . MWSOC*\n . (GLOB >st_tok @{\/*TODO*\/})\n . (MWSOC* . (GLOB >st_tok @{\/*TODO*\/}))*\n . MWSOC*\n . ';'\n )\n |\n '##' . [ \\t]* . EOL @{ line++; \/*cerr<<\"-> rules\\n\";*\/ fgoto rules; }\n )**;\n}%%\n\n\/\/ this method is called when a glob ... {} block ends\nvoid ConfFileScanner :: go_level_down()\n{\n globlist_stack_.pop_back();\n globlist_stack_.back().clear();\n level_--;\n}\n\n\/\/ checks wether the string ist matched by a glob from the globlist_stack_ at\n\/\/ level \\a l\nbool ConfFileScanner :: check_for_match(int l, const char * str,\n bool match_path_sep)\n{\n typedef GlobList :: iterator iterator;\n \/\/ get globlist at stack level \\a l\n GlobList & gl = globlist_stack_[l];\n\n iterator endit = gl.end();\n int flags = (match_path_sep? FNM_PATHNAME : 0);\n \/\/ iterate over all globs\n for( iterator it = gl.begin(); it != endit; it++ )\n {\n \/\/ check wether str matches glob\n if(fnmatch((*it).c_str(), str, flags) == 0)\n {\n return true;\n }\n }\n return false;\n}\n\n\/\/ check recursively wether file named \\a s is matched by a glob from the\n\/\/ globlist_stack_\nbool ConfFileScanner :: check_glob_rec(int l, const string & s)\n{\n string str;\n string :: size_type found;\n \/\/ exit condition (if filename ist matched up to level level_+1 the check was\n \/\/ successful.\n if(l == level_+1)\n return true;\n\n found = s.find(\"\/\"); \/\/ try to match dir in path\n while(found != string :: npos)\n {\n str = s.substr(0, found);\n \/\/ first try to match the prepended path by a glob at this level, ...\n if(check_for_match(l, str.c_str())\n \/\/ ... then try to match the rest of the substring at a higher level.\n && check_glob_rec(l+1, s.substr(found+1)))\n return true;\n\n found = s.find(\"\/\", found+1); \/\/ try to match more dirs\n }\n if(l == level_) \/\/ try also to match the entire string at this level\n {\n if(check_for_match(l, s.c_str()))\n return true;\n }\n\n return false;\n}\n\n\/\/ this method is called after a glob ... = {} block begins\n\/\/ and sets the match_at_level_ structure for the active file named \n\/\/ \\a filename_\nvoid ConfFileScanner :: check_glob_level_up()\n{\n \/\/ update match_at_level_\n match_at_level_[level_+1] = check_glob_rec(0, filename_);\n\n \/\/ add empty glob list\n globlist_stack_.push_back(GlobList());\n level_++;\n}\n\n\/\/ constructor\nConfFileScanner\n:: ConfFileScanner(const std::string & filename, const std::string & conffilename)\n : line(1), have(0), top(0), opt(true),\n filename_(filename),\n conffile_(conffilename == \"\" ? \"doxygen\/mtoc.conf\" : conffilename),\n confistream_(get_conffile()),\n level_(0),\n arg_to_be_added_(false)\n{\n if ( (confistream_.rdstate() & ifstream::failbit ) != 0 )\n {\n cerr << \"Error opening configuration file '\" << conffilename << \"'\\n\";\n exit(-2);\n }\n globlist_stack_.push_back(GlobList());\n \/\/ at level 0 every file is matched ( no glob checking )\n match_at_level_[0] = true;\n}\n\n\/\/ returns the name of the configuration file\nconst char * ConfFileScanner ::\nget_conffile()\n{\n return conffile_.c_str();\n}\n\n\/\/ run the conffile scanner\nint ConfFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p;\/\/ *tmp_p2 = p;\n \/\/ string for temporary tokens\n string tmp_string;\n \/\/ spare space in buffer\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(1);\n }\n\n \/\/ read configuration file chunk in buffer\n confistream_.read( p, space );\n int len = confistream_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( confistream_.eof() )\n {\n eof = pe;\n done = true;\n }\n else\n {\n \/* Find the last semicolon by searching backwards. This\n * is where we will stop processing on this iteration. *\/\n while ( *pe!= ';' && pe > p )\n pe--;\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == ConfFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"in conffile: PARSE ERROR in line \" << line << endl;\n exit(1);\n }\n\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n\n return 0;\n}\n\/* vim: set et sw=2 ft=ragel: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"a6c9bcb78e6a605ff950e9a5be46c9625482bbaa","subject":"Fix leading\/trailing whitespace for JSON parser","message":"Fix leading\/trailing whitespace for JSON parser\n\nOperator precedence meant it was either leading whitespace + an object, or an\narray + trailing whitespace, not leading + (object or array) + trailing.\nJust let it be any type of value.\n\nChange-Id: I537d2cceee53a75c1ef79c36337e7dc655b028ef\nReviewed-on: https:\/\/gerrit.dechocorp.com\/6346\nReviewed-by: Jeremy Stanley <8cc48e55af0ea00a29d3ccf3190022dccfb4961b@decho.com>\n","repos":"mtanski\/mordor,cgaebel\/mordor,mozy\/mordor,adfin\/mordor,cgaebel\/mordor,mtanski\/mordor,mozy\/mordor,adfin\/mordor,ccutrer\/mordor,mozy\/mordor,ccutrer\/mordor,mtanski\/mordor,ccutrer\/mordor,adfin\/mordor","old_file":"mordor\/json.rl","new_file":"mordor\/json.rl","new_contents":"\/\/ Copyright (c) 2009 - Mozy, Inc.\n\n#include \"mordor\/pch.h\"\n\n#include \"mordor\/json.h\"\n\n#include \"mordor\/assert.h\"\n\nnamespace Mordor {\nnamespace JSON {\n\nstd::string unquote(const std::string &string)\n{\n MORDOR_ASSERT(string.size() >= 2);\n MORDOR_ASSERT(string[0] == '\"');\n MORDOR_ASSERT(string[string.size() - 1] == '\"');\n std::string result = string.substr(1, string.size() - 2);\n\n const char *c = string.c_str() + 1;\n const char *end = c + string.size() - 2;\n bool differed = false;\n int utf16;\n while (c < end)\n {\n if (*c == '\\\\') {\n MORDOR_ASSERT(c + 1 < end);\n if (!differed) {\n result.resize(c - (string.c_str() + 1));\n differed = true;\n }\n ++c;\n switch (*c) {\n case '\"':\n case '\\\\':\n case '\/':\n result.append(1, *c);\n break;\n case 'b':\n result.append(1, '\\b');\n break;\n case 'f':\n result.append(1, '\\f');\n break;\n case 'n':\n result.append(1, '\\n');\n break;\n case 'r':\n result.append(1, '\\r');\n break;\n case 't':\n result.append(1, '\\t');\n break;\n case 'u':\n MORDOR_ASSERT(c + 4 < end);\n utf16 = 0;\n ++c;\n for (int i = 0; i < 4; ++i) {\n utf16 *= 16;\n if (*c >= '0' && *c <= '9')\n utf16 += *c - '0';\n else if (*c >= 'a' && *c <= 'f')\n utf16 += *c - 'a' + 10;\n else if (*c >= 'A' && *c <= 'F')\n utf16 += *c - 'A' + 10;\n else\n MORDOR_NOTREACHED();\n ++c;\n }\n \/\/ Utf16->Utf8 conversion not supported yet\n MORDOR_ASSERT(utf16 < 255);\n result.append(1, (char)utf16);\n break;\n default:\n MORDOR_NOTREACHED();\n }\n } else if (differed) {\n result.append(1, *c);\n }\n ++c;\n }\n return result;\n}\n\n%%{\n machine json_parser;\n\n action mark { mark = fpc;}\n action done { fbreak; }\n prepush {\n prepush();\n }\n postpop {\n postpop();\n }\n\n ws = ' ' | '\\t' | '\\r' | '\\n';\n\n unescaped = (any - ('\"' | '\\\\') - cntrl);\n char = unescaped | ('\\\\' ('\"' | '\\\\' | 'b' | 'f' | 'n' | 'r' | 't' | ('u' [0-9A-Za-z]{4})));\n string = '\"' char* '\"';\n\n action begin_number\n {\n m_nonIntegral = false;\n }\n action set_non_integral\n {\n m_nonIntegral = true;\n }\n action parse_number\n {\n if (m_nonIntegral) {\n *m_stack.top() = strtod(mark, NULL);\n } else {\n *m_stack.top() = strtoll(mark, NULL, 10);\n }\n }\n\n int = (digit | ([1-9] digit*));\n frac = '.' >set_non_integral digit+;\n exp = 'e'i >set_non_integral ('+' | '-')? digit+;\n number = ('-'? int frac? exp?) >mark >begin_number %parse_number;\n\n action parse_string\n {\n *m_stack.top() = unquote(std::string(mark, fpc - mark));\n }\n action call_parse_object\n {\n *m_stack.top() = Object();\n fcall *json_parser_en_parse_object;\n }\n action call_parse_array\n {\n *m_stack.top() = Array();\n fcall *json_parser_en_parse_array;\n }\n action parse_true\n {\n *m_stack.top() = true;\n }\n action parse_false\n {\n *m_stack.top() = false;\n }\n action parse_null\n {\n *m_stack.top() = boost::blank();\n }\n value = string >mark %parse_string | number | '{' @call_parse_object |\n '[' @call_parse_array | 'true' @parse_true | 'false' @parse_false |\n 'null' @parse_null;\n\n object = '{' ws* string ws* ':' ws* value ws* (',' ws* string ws* ':' ws* value ws*)* '}';\n array = '[' ws* value ws* (',' ws* value ws*)* ']';\n\n action new_key\n {\n m_stack.push(&boost::get(*m_stack.top()).insert(std::make_pair(unquote(std::string(mark, fpc - mark)), Value()))->second);\n }\n action new_element\n {\n boost::get(*m_stack.top()).push_back(Value());\n m_stack.push(&boost::get(*m_stack.top()).back());\n }\n action pop_stack\n {\n m_stack.pop();\n }\n action ret {\n fret;\n }\n\n parse_object := parse_object_lbl: ws* string >mark %new_key ws* ':' ws* value %pop_stack ws* (',' ws* string >mark %new_key ws* ':' ws* value %pop_stack ws*)* '}' @ret;\n parse_array := parse_array_lbl: ws* value >new_element %pop_stack ws* (',' ws* value >new_element %pop_stack ws*)* ']' @ret;\n\n main := ws* value ws*;\n write data;\n}%%\n\nvoid\nParser::init()\n{\n while (m_stack.size() > 1)\n m_stack.pop();\n *m_stack.top() = boost::blank();\n RagelParserWithStack::init();\n %% write init;\n}\n\nvoid\nParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\nbool\nParser::final() const\n{\n return cs >= json_parser_first_final;\n}\n\nbool\nParser::error() const\n{\n return cs == json_parser_error;\n}\n\nstd::string\nquote(const std::string &str)\n{\n std::string result;\n result.reserve(str.length() + 2);\n result.append(1, '\"');\n\n static const char *escaped =\n \"\\0\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\"\n \"\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\"\n \"\\\\\\\"\";\n\n size_t lastEscape = 0;\n size_t nextEscape = str.find_first_of(escaped, 0, 34);\n std::ostringstream os;\n os.fill('0');\n os << std::hex << std::setw(4);\n while (nextEscape != std::string::npos) {\n result.append(str.substr(lastEscape, nextEscape - lastEscape));\n result.append(1, '\\\\');\n switch (str[nextEscape]) {\n case '\"':\n case '\\\\':\n result.append(1, str[nextEscape]);\n break;\n case '\\b':\n result.append(1, 'b');\n break;\n case '\\f':\n result.append(1, 'f');\n break;\n case '\\n':\n result.append(1, 'n');\n break;\n case '\\r':\n result.append(1, 'r');\n break;\n case '\\t':\n result.append(1, 't');\n break;\n default:\n result.append(1, 'u');\n os.str();\n os << (int)str[nextEscape];\n result.append(os.str());\n break;\n }\n lastEscape = nextEscape + 1;\n nextEscape = str.find_first_of(escaped, lastEscape, 34);\n }\n result.append(str.substr(lastEscape));\n result.append(1, '\"');\n return result;\n}\n\nnamespace {\nclass JSONVisitor : public boost::static_visitor<>\n{\npublic:\n JSONVisitor(std::ostream &os)\n : os(os),\n depth(0)\n {}\n\n void operator()(const boost::blank &b)\n {\n os << \"null\";\n }\n void operator()(const bool &b)\n {\n os << (b ? \"true\" : \"false\");\n }\n template \n void operator()(const T &t)\n {\n os << t;\n }\n void operator()(const std::string &str)\n {\n os << quote(str);\n }\n void operator()(const Object &object)\n {\n if (object.empty()) {\n os << \"{ }\";\n } else {\n ++depth;\n std::string prefix(depth * 4, ' ');\n os << \"{\\n\";\n for (Object::const_iterator it(object.begin());\n it != object.end();\n ++it) {\n if (it != object.begin())\n os << \",\\n\";\n os << prefix << quote(it->first) << \" : \";\n boost::apply_visitor(*this, it->second);\n }\n --depth;\n prefix.clear();\n prefix.append(depth * 4, ' ');\n os << '\\n' << prefix << \"}\";\n }\n }\n void operator()(const Array &array)\n {\n if (array.empty()) {\n os << \"[ ]\";\n } else {\n ++depth;\n std::string prefix(depth * 4, ' ');\n os << \"[\\n\";\n for (Array::const_iterator it(array.begin());\n it != array.end();\n ++it) {\n if (it != array.begin())\n os << \",\\n\";\n os << prefix;\n boost::apply_visitor(*this, *it);\n }\n --depth;\n prefix.clear();\n prefix.append(depth * 4, ' ');\n os << '\\n' << prefix << \"]\";\n }\n }\n\n std::ostream &os;\n int depth;\n};\n}\n\nstd::ostream &operator <<(std::ostream &os, const Value &json)\n{\n JSONVisitor visitor(os);\n boost::apply_visitor(visitor, json);\n return os;\n}\n\n}}\n","old_contents":"\/\/ Copyright (c) 2009 - Mozy, Inc.\n\n#include \"mordor\/pch.h\"\n\n#include \"mordor\/json.h\"\n\n#include \"mordor\/assert.h\"\n\nnamespace Mordor {\nnamespace JSON {\n\nstd::string unquote(const std::string &string)\n{\n MORDOR_ASSERT(string.size() >= 2);\n MORDOR_ASSERT(string[0] == '\"');\n MORDOR_ASSERT(string[string.size() - 1] == '\"');\n std::string result = string.substr(1, string.size() - 2);\n\n const char *c = string.c_str() + 1;\n const char *end = c + string.size() - 2;\n bool differed = false;\n int utf16;\n while (c < end)\n {\n if (*c == '\\\\') {\n MORDOR_ASSERT(c + 1 < end);\n if (!differed) {\n result.resize(c - (string.c_str() + 1));\n differed = true;\n }\n ++c;\n switch (*c) {\n case '\"':\n case '\\\\':\n case '\/':\n result.append(1, *c);\n break;\n case 'b':\n result.append(1, '\\b');\n break;\n case 'f':\n result.append(1, '\\f');\n break;\n case 'n':\n result.append(1, '\\n');\n break;\n case 'r':\n result.append(1, '\\r');\n break;\n case 't':\n result.append(1, '\\t');\n break;\n case 'u':\n MORDOR_ASSERT(c + 4 < end);\n utf16 = 0;\n ++c;\n for (int i = 0; i < 4; ++i) {\n utf16 *= 16;\n if (*c >= '0' && *c <= '9')\n utf16 += *c - '0';\n else if (*c >= 'a' && *c <= 'f')\n utf16 += *c - 'a' + 10;\n else if (*c >= 'A' && *c <= 'F')\n utf16 += *c - 'A' + 10;\n else\n MORDOR_NOTREACHED();\n ++c;\n }\n \/\/ Utf16->Utf8 conversion not supported yet\n MORDOR_ASSERT(utf16 < 255);\n result.append(1, (char)utf16);\n break;\n default:\n MORDOR_NOTREACHED();\n }\n } else if (differed) {\n result.append(1, *c);\n }\n ++c;\n }\n return result;\n}\n\n%%{\n machine json_parser;\n\n action mark { mark = fpc;}\n action done { fbreak; }\n prepush {\n prepush();\n }\n postpop {\n postpop();\n }\n\n ws = ' ' | '\\t' | '\\r' | '\\n';\n\n unescaped = (any - ('\"' | '\\\\') - cntrl);\n char = unescaped | ('\\\\' ('\"' | '\\\\' | 'b' | 'f' | 'n' | 'r' | 't' | ('u' [0-9A-Za-z]{4})));\n string = '\"' char* '\"';\n\n action begin_number\n {\n m_nonIntegral = false;\n }\n action set_non_integral\n {\n m_nonIntegral = true;\n }\n action parse_number\n {\n if (m_nonIntegral) {\n *m_stack.top() = strtod(mark, NULL);\n } else {\n *m_stack.top() = strtoll(mark, NULL, 10);\n }\n }\n\n int = (digit | ([1-9] digit*));\n frac = '.' >set_non_integral digit+;\n exp = 'e'i >set_non_integral ('+' | '-')? digit+;\n number = ('-'? int frac? exp?) >mark >begin_number %parse_number;\n\n action parse_string\n {\n *m_stack.top() = unquote(std::string(mark, fpc - mark));\n }\n action call_parse_object\n {\n *m_stack.top() = Object();\n fcall *json_parser_en_parse_object;\n }\n action call_parse_array\n {\n *m_stack.top() = Array();\n fcall *json_parser_en_parse_array;\n }\n action parse_true\n {\n *m_stack.top() = true;\n }\n action parse_false\n {\n *m_stack.top() = false;\n }\n action parse_null\n {\n *m_stack.top() = boost::blank();\n }\n value = string >mark %parse_string | number | '{' @call_parse_object |\n '[' @call_parse_array | 'true' @parse_true | 'false' @parse_false |\n 'null' @parse_null;\n\n object = '{' ws* string ws* ':' ws* value ws* (',' ws* string ws* ':' ws* value ws*)* '}';\n array = '[' ws* value ws* (',' ws* value ws*)* ']';\n\n action new_key\n {\n m_stack.push(&boost::get(*m_stack.top()).insert(std::make_pair(unquote(std::string(mark, fpc - mark)), Value()))->second);\n }\n action new_element\n {\n boost::get(*m_stack.top()).push_back(Value());\n m_stack.push(&boost::get(*m_stack.top()).back());\n }\n action pop_stack\n {\n m_stack.pop();\n }\n action ret {\n fret;\n }\n\n parse_object := parse_object_lbl: ws* string >mark %new_key ws* ':' ws* value %pop_stack ws* (',' ws* string >mark %new_key ws* ':' ws* value %pop_stack ws*)* '}' @ret;\n parse_array := parse_array_lbl: ws* value >new_element %pop_stack ws* (',' ws* value >new_element %pop_stack ws*)* ']' @ret;\n\n main := ws* '{' @call_parse_object | '[' @call_parse_array ws*;\n write data;\n}%%\n\nvoid\nParser::init()\n{\n while (m_stack.size() > 1)\n m_stack.pop();\n *m_stack.top() = boost::blank();\n RagelParserWithStack::init();\n %% write init;\n}\n\nvoid\nParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\nbool\nParser::final() const\n{\n return cs >= json_parser_first_final;\n}\n\nbool\nParser::error() const\n{\n return cs == json_parser_error;\n}\n\nstd::string\nquote(const std::string &str)\n{\n std::string result;\n result.reserve(str.length() + 2);\n result.append(1, '\"');\n\n static const char *escaped =\n \"\\0\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\"\n \"\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\"\n \"\\\\\\\"\";\n\n size_t lastEscape = 0;\n size_t nextEscape = str.find_first_of(escaped, 0, 34);\n std::ostringstream os;\n os.fill('0');\n os << std::hex << std::setw(4);\n while (nextEscape != std::string::npos) {\n result.append(str.substr(lastEscape, nextEscape - lastEscape));\n result.append(1, '\\\\');\n switch (str[nextEscape]) {\n case '\"':\n case '\\\\':\n result.append(1, str[nextEscape]);\n break;\n case '\\b':\n result.append(1, 'b');\n break;\n case '\\f':\n result.append(1, 'f');\n break;\n case '\\n':\n result.append(1, 'n');\n break;\n case '\\r':\n result.append(1, 'r');\n break;\n case '\\t':\n result.append(1, 't');\n break;\n default:\n result.append(1, 'u');\n os.str();\n os << (int)str[nextEscape];\n result.append(os.str());\n break;\n }\n lastEscape = nextEscape + 1;\n nextEscape = str.find_first_of(escaped, lastEscape, 34);\n }\n result.append(str.substr(lastEscape));\n result.append(1, '\"');\n return result;\n}\n\nnamespace {\nclass JSONVisitor : public boost::static_visitor<>\n{\npublic:\n JSONVisitor(std::ostream &os)\n : os(os),\n depth(0)\n {}\n\n void operator()(const boost::blank &b)\n {\n os << \"null\";\n }\n void operator()(const bool &b)\n {\n os << (b ? \"true\" : \"false\");\n }\n template \n void operator()(const T &t)\n {\n os << t;\n }\n void operator()(const std::string &str)\n {\n os << quote(str);\n }\n void operator()(const Object &object)\n {\n if (object.empty()) {\n os << \"{ }\";\n } else {\n ++depth;\n std::string prefix(depth * 4, ' ');\n os << \"{\\n\";\n for (Object::const_iterator it(object.begin());\n it != object.end();\n ++it) {\n if (it != object.begin())\n os << \",\\n\";\n os << prefix << quote(it->first) << \" : \";\n boost::apply_visitor(*this, it->second);\n }\n --depth;\n prefix.clear();\n prefix.append(depth * 4, ' ');\n os << '\\n' << prefix << \"}\";\n }\n }\n void operator()(const Array &array)\n {\n if (array.empty()) {\n os << \"[ ]\";\n } else {\n ++depth;\n std::string prefix(depth * 4, ' ');\n os << \"[\\n\";\n for (Array::const_iterator it(array.begin());\n it != array.end();\n ++it) {\n if (it != array.begin())\n os << \",\\n\";\n os << prefix;\n boost::apply_visitor(*this, *it);\n }\n --depth;\n prefix.clear();\n prefix.append(depth * 4, ' ');\n os << '\\n' << prefix << \"]\";\n }\n }\n\n std::ostream &os;\n int depth;\n};\n}\n\nstd::ostream &operator <<(std::ostream &os, const Value &json)\n{\n JSONVisitor visitor(os);\n boost::apply_visitor(visitor, json);\n return os;\n}\n\n}}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"2e1fc2692ee5d66dc6e24bdb49e96a31f37f6fde","subject":"Add error messages to parse_tokens.","message":"Add error messages to parse_tokens.\n","repos":"orodley\/chessboard,orodley\/chessboard,orodley\/chessboard","old_file":"src\/pgn.rl","new_file":"src\/pgn.rl","new_contents":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"board.h\"\n#include \"moves.h\"\n#include \"pgn.h\"\n\n\/\/ TODO: error messages\n\n%%{\n\tmachine pgn_tokenizer;\n\twrite data;\n}%%\n\ntypedef enum Token_type\n{\n\t\/\/ Tokens with different values\n\tSTRING, INTEGER, NAG, SYMBOL,\n\t\/\/ Fixed tokens - always just a single character\n\tDOT, ASTERISK, L_SQUARE_BRACKET, R_SQUARE_BRACKET,\n\tL_BRACKET, R_BRACKET, L_ANGLE_BRACKET, R_ANGLE_BRACKET, \n} Token_type;\n\ntypedef union Token_value {\n\tchar *string;\n\tuint integer;\n} Token_value;\n\ntypedef struct Token\n{\n\tToken_type type;\n\tToken_value value;\n} Token;\n\nvoid print_token(Token *t)\n{\n\tswitch (t->type) {\n\tcase STRING: printf(\"STRING: %s\\n\", t->value.string); break;\n\tcase SYMBOL: printf(\"SYMBOL: %s\\n\", t->value.string); break;\n\tcase NAG: printf(\"NAG: %s\\n\", t->value.string); break;\n\tcase INTEGER: printf(\"INTEGER: %d\\n\", t->value.integer); break;\n\tcase DOT: puts(\"DOT\"); break;\n\tcase ASTERISK: puts(\"DOT\"); break;\n\tcase L_SQUARE_BRACKET: puts(\"L_SQUARE_BRACKET\"); break;\n\tcase R_SQUARE_BRACKET: puts(\"R_SQUARE_BRACKET\"); break;\n\tcase L_BRACKET: puts(\"L_BRACKET\"); break;\n\tcase R_BRACKET: puts(\"R_BRACKET\"); break;\n\tcase L_ANGLE_BRACKET: puts(\"L_ANGLE_BRACKET\"); break;\n\tcase R_ANGLE_BRACKET: puts(\"R_ANGLE_BRACKET\"); break;\n\t}\n}\n\nbool symbol_is_integer(Token *t)\n{\n\tchar *str = t->value.string;\n\tfor (size_t i = 0; str[i] != '\\0'; i++)\n\t\tif (!isdigit(str[i]))\n\t\t\treturn false;\n\n\treturn true;\n}\n\t\t\n\nchar *escape_string(char *str, size_t length)\n{\n\tchar *out = malloc(length + 1);\n\tsize_t j = 0;\n\tbool escaping = false;\n\n\tfor (size_t i = 0; i < length; i++) {\n\t\tchar c = str[i];\n\t\tswitch (c) {\n\t\tcase '\\\\':\n\t\t\tif (escaping) {\n\t\t\t\tout[j++] = '\\\\';\n\t\t\t\tescaping = false;\n\t\t\t} else {\n\t\t\t\tescaping = true;\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\t\/\/ We should never come across an unescaped quote in a string, as\n\t\t\t\/\/ the tokenizer should have terminated the string in this case.\n\t\t\tassert(escaping);\n\n\t\t\tout[j++] = '\"';\n\t\t\tescaping = false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tout[j++] = c;\n\t\t\tescaping = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tout[j] = '\\0';\n\n\treturn out;\n}\n\nstatic GArray *tokenize_pgn(char *buf, gsize length)\n{\n\t\/\/ The initial size (140) is just a rough estimate of the average number of\n\t\/\/ tokens, based on 4 tokens for each of the 7 required tags, and 4 tokens\n\t\/\/ for each of 30 moves.\n\tGArray *tokens = g_array_sized_new(FALSE, FALSE, sizeof(Token), 140);\n\n\t\/\/ Variables that Ragel needs\n\tchar *p = buf, *pe = buf + length;\n\tchar *eof = NULL;\n\tchar *ts, *te;\n\tint cs, act;\n\t\/\/ act is initialized for scanners, so it must be declared, but in this\n\t\/\/ scanner we don't actually use it. This silences the compiler warning.\n\tIGNORE(act);\n\n\t%%write init;\n\t%%{\n\t\taction add_string {\n\t\t\t\/\/ - 2 for quotes\n\t\t\tsize_t length = te - ts - 2;\n\t\t\tchar *token = escape_string(ts + 1, length);\n\n\t\t\tToken t = { STRING, { token } };\n\n\t\t\tg_array_append_val(tokens, t);\n\t\t}\n\n\t\taction add_symbol {\n\t\t\t\/\/ + 1 for null terminator\n\t\t\tsize_t length = te - ts + 1;\n\t\t\tchar *token = malloc(length); \n\t\t\tstrncpy(token, ts, length - 1);\n\t\t\ttoken[length - 1] = '\\0';\n\n\t\t\tToken t = { SYMBOL, { token } };\n\n\t\t\tg_array_append_val(tokens, t);\n\t\t}\n\n\t\taction add_nag {\n\t\t\t\/\/ + 1 for null terminator\n\t\t\tsize_t length = te - ts + 1;\n\t\t\tchar *token = malloc(length); \n\t\t\tstrncpy(token, ts, length - 1);\n\t\t\ttoken[length - 1] = '\\0';\n\n\t\t\tToken t = { NAG, { token } };\n\n\t\t\tg_array_append_val(tokens, t);\n\t\t}\n\n\t\t# Token types, as per PGN spec section 7\n\t\t# Integers are read as symbols, and we convert them in the second pass\n\n\t\t# We cheat a little bit here.\n\t\t# According to the PGN spec, game termination markers are simply symbols.\n\t\t# However, according to the definition of the symbol token, symbols\n\t\t# cannot contain the '\/' character. This seems like a contradiction, so\n\t\t# to work around it we allow '\/'s in symbols.\n\t\tsymbol = alnum (alnum | [_+#=:\\-\/])*;\n\t\tstring = '\"' (('\\\\' print) | (print - '\\\\\"'))* '\"';\n\t\tnag = '$' digit+;\n\n\n\t\tmain := |*\n\t\t\tspace;\n\t\t\tsymbol => add_symbol;\n\t\t\tstring => add_string;\n\t\t\tnag => add_nag;\n\t\t\t'.' => { Token t = { DOT, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'*' => { Token t = { ASTERISK, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'[' => { Token t = { L_SQUARE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t']' => { Token t = { R_SQUARE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'(' => { Token t = { L_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t')' => { Token t = { R_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'<' => { Token t = { L_ANGLE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'>' => { Token t = { R_ANGLE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t*|;\n\n\n\t\twrite exec;\n\t}%%\n\n\t\/\/ Integers are a subset of symbols, and unfortunately Ragel scanners\n\t\/\/ attempt to match longer patterns before shorter ones.\n\t\/\/ So we do a second pass to look for symbols that are integers.\n\tfor (size_t i = 0; i < tokens->len; i++) {\n\t\tToken *t = &g_array_index(tokens, Token, i);\n\t\tif (t->type == SYMBOL && symbol_is_integer(t)) {\n\t\t\tint n;\n\t\t\tsscanf(t->value.string, \"%d\", &n);\n\n\t\t\tt->type = INTEGER;\n\t\t\tt->value.integer = n;\n\t\t}\n\t}\n\n\treturn tokens;\n}\n\n\/\/ It is impossible to parse a move without a reference to a particular board,\n\/\/ as something like Bd5 could start from any square on that diagonal.\nstatic Move parse_move(Board *board, char *notation)\n{\n\tif (strcmp(notation, \"O-O\") == 0) {\n\t\tuint rank = board->turn == WHITE ? 0 : 7;\n\t\treturn MOVE(SQUARE(4, rank), SQUARE(6, rank));\n\t}\n\tif (strcmp(notation, \"O-O-O\") == 0) {\n\t\tuint rank = board->turn == WHITE ? 0 : 7;\n\t\treturn MOVE(SQUARE(4, rank), SQUARE(2, rank));\n\t}\n\n\tchar stripped[5]; \/\/ max length without 'x#+'s, + 1 for null terminator\n\tsize_t j = 0;\n\tfor (size_t i = 0; notation[i] != '\\0'; i++)\n\t\tif (notation[i] != 'x' && notation[i] != '#' && notation[i] != '+')\n\t\t\tstripped[j++] = notation[i];\n\tstripped[j] = '\\0';\n\n\tsize_t i = 0;\n\tPiece_type type;\n\t\/\/ If it's a pawn move, the target square starts at the beginning of the\n\t\/\/ string\n\tif (islower(stripped[0])) {\n\t\ttype = PAWN;\n\n\t\t\/\/ An exception: if it's a move like exd5, the target square starts one \n\t\t\/\/ char further on\n\t\tif (islower(stripped[1]))\n\t\t\ti++;\n\t} else {\n\t\ttype = PIECE_TYPE(piece_from_char(stripped[0]));\n\t\ti++;\n\t}\n\t\n\tchar disambig = 0;\n\tif (j == 4)\n\t\t\/\/ If it's this long, there must be a disambiguation char in there\n\t\tdisambig = stripped[i++];\n\t\n\tuint target_file = CHAR_FILE(stripped[i++]);\n\tuint target_rank = CHAR_RANK(stripped[i++]);\n\n\tif (disambig != 0) {\n\t\tuint x = 0, y = 0, dx = 0, dy = 0;\n\t\tif (disambig >= 'a' && disambig <= 'g') {\n\t\t\tx = CHAR_FILE(disambig);\n\t\t\tdy = 1;\n\t\t} else if (disambig >= '1' && disambig <= '8') {\n\t\t\ty = CHAR_RANK(disambig);\n\t\t\tdx = 1;\n\t\t} else {\n\t\t\treturn NULL_MOVE;\n\t\t}\n\n\t\tfor (; x < BOARD_SIZE && y < BOARD_SIZE; x += dx, y += dy) {\n\t\t\tPiece p = PIECE_AT(board, x, y);\n\t\t\tif (PIECE_TYPE(p) != type || PLAYER(p) != board->turn)\n\t\t\t\tcontinue;\n\n\t\t\tMove m = MOVE(SQUARE(x, y), SQUARE(target_file, target_rank));\n\t\t\tif (legal_move(board, m, true))\n\t\t\t\treturn m;\n\t\t}\n\n\t\treturn NULL_MOVE;\n\t}\n\n\tfor (uint x = 0; x < BOARD_SIZE; x++) {\n\t\tfor (uint y = 0; y < BOARD_SIZE; y++) {\n\t\t\tPiece p = PIECE_AT(board, x, y);\n\t\t\tif (PIECE_TYPE(p) != type || PLAYER(p) != board->turn)\n\t\t\t\tcontinue;\n\n\t\t\tMove m = MOVE(SQUARE(x, y), SQUARE(target_file, target_rank));\n\t\t\tif (legal_move(board, m, true))\n\t\t\t\treturn m;\n\t\t}\n\t}\n\n\treturn NULL_MOVE;\n}\n\nstatic Result parse_game_termination_marker(char *symbol)\n{\n\tif (strcmp(symbol, \"1-0\") == 0)\n\t\treturn WHITE_WINS;\n\tif (strcmp(symbol, \"0-1\") == 0)\n\t\treturn BLACK_WINS;\n\tif (strcmp(symbol, \"1\/2-1\/2\") == 0)\n\t\treturn DRAW;\n\tif (strcmp(symbol, \"*\") == 0)\n\t\treturn OTHER;\n\t\n\treturn NULL_MOVE;\n}\n\nstatic char *game_termination_marker(Result r)\n{\n\tswitch (r) {\n\tcase WHITE_WINS: return \"1-0\";\n\tcase BLACK_WINS: return \"0-1\";\n\tcase DRAW: return \"1\/2-1\/2\";\n\tdefault: return \"*\";\n\t}\n}\n\nstatic bool parse_tokens(PGN *pgn, GArray *tokens, GError **err)\n{\n\t\/\/ Start with tags\n\tpgn->tags = g_hash_table_new(g_str_hash, g_str_equal);\n\n\tsize_t i = 0;\n\twhile ((&g_array_index(tokens, Token, i))->type == L_SQUARE_BRACKET) {\n\t\tToken *tag_name_token = &g_array_index(tokens, Token, ++i);\n\t\tif (tag_name_token->type != SYMBOL) {\n\t\t\tif (tag_name_token->type == INTEGER) {\n\t\t\t\tg_set_error(err, 0, 0,\n\t\t\t\t\t\t\"Unexpected token: %d\", tag_name_token->value.integer);\n\t\t\t} else {\n\t\t\t\tg_set_error(err, 0, 0,\n\t\t\t\t\t\t\"Unexpected token: %s\", tag_name_token->value.string);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tchar *tag_name = tag_name_token->value.string;\n\n\t\tif (g_hash_table_contains(pgn->tags, tag_name)) {\n\t\t\tg_set_error(err, 0, 0, \"Duplicate tag: %s\", tag_name);\n\t\t\treturn false;\n\t\t}\n\n\t\tToken *tag_value_token = &g_array_index(tokens, Token, ++i);\n\t\tif (tag_value_token->type != STRING) {\n\t\t\tif (tag_name_token->type == INTEGER) {\n\t\t\t\tg_set_error(err, 0, 0, \"Tag values must be strings, %d is not\",\n\t\t\t\t\t\ttag_value_token->value.integer);\n\t\t\t} else {\n\t\t\t\tg_set_error(err, 0, 0, \"Tag values must be strings, %s is not\",\n\t\t\t\t\t\ttag_value_token->value.string);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tchar *tag_value = tag_value_token->value.string;\n\n\t\tchar *tag_name_copy = malloc(strlen(tag_name) + 1);\n\t\tstrcpy(tag_name_copy, tag_name);\n\t\tchar *tag_value_copy = malloc(strlen(tag_value) + 1);\n\t\tstrcpy(tag_value_copy, tag_value);\n\n\t\tg_hash_table_insert(pgn->tags, tag_name_copy, tag_value_copy);\n\n\t\tToken *close_square_bracket_token = &g_array_index(tokens, Token, ++i);\n\t\tif (close_square_bracket_token->type != R_SQUARE_BRACKET) {\n\t\t\tg_set_error(err, 0, 0,\n\t\t\t\t\t\"Tag %s has no matching close bracket\", tag_name);\n\t\t\treturn false;\n\t\t}\n\n\t\ti++;\n\t}\n\n\t\/\/ Now the movetext section\n\tuint half_move_number = 2;\n\n\tGame *game = new_game();\n\tgame->board = malloc(sizeof(Board));\n\tpgn->game = game;\n\t\/\/ TODO: Use value in start board tag if present.\n\tfrom_fen(game->board, start_board_fen);\n\n\t\/\/ TODO: variations, NAG\n\twhile (i < tokens->len) {\n\t\tToken *t = &g_array_index(tokens, Token, i++);\n\t\tif (t->type == INTEGER) {\n\t\t\tif (t->value.integer != half_move_number \/ 2) {\n\t\t\t\tg_set_error(err, 0, 0,\n\t\t\t\t\t\t\"Incorrect move number %d (should be %d)\",\n\t\t\t\t\t\tt->value.integer, half_move_number \/ 2);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\twhile ((t = &g_array_index(tokens, Token, i++))->type == DOT)\n\t\t\t\t;\n\t\t}\n\n\t\tif (t->type != SYMBOL)\n\t\t\tif (t->type == INTEGER) {\n\t\t\t\tg_set_error(err, 0, 0, \"Expected a move, got %d\",\n\t\t\t\t\t\tt->value.integer);\n\t\t\t} else {\n\t\t\t\tg_set_error(err, 0, 0, \"Expected a move, got %s\",\n\t\t\t\t\t\tt->value.string);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tResult r;\n\t\tif ((r = parse_game_termination_marker(t->value.string)) != NULL_RESULT) {\n\t\t\tpgn->result = r;\n\n\t\t\t\/\/ If we didn't see a result tag, try to fill it in with the value\n\t\t\t\/\/ in the game termination marker\n\n\t\t\tif (!g_hash_table_contains(pgn->tags, \"Result\")) {\n\t\t\t\tchar *tmp = malloc(strlen(t->value.string));\n\t\t\t\tstrcpy(tmp, t->value.string);\n\t\t\t\tg_hash_table_insert(pgn->tags, \"Result\", tmp);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tMove m;\n\t\tif ((m = parse_move(game->board, t->value.string)) == NULL_MOVE) {\n\t\t\tg_set_error(err, 0, 0, \"Expected a move, got %s\", t->value.string);\n\t\t\t\n\t\t\treturn false;\n\t\t}\n\n\t\tBoard *new_board = malloc(sizeof *new_board);\n\t\tcopy_board(new_board, game->board);\n\t\tperform_move(new_board, m);\n\t\tadd_child(game, m, new_board);\n\t\tgame = first_child(game);\n\n\t\thalf_move_number++;\n\t}\n\n\treturn true;\n}\n\nvoid free_tokens(GArray *tokens)\n{\n\tfor (size_t i = 0; i < tokens->len; i++) {\n\t\tToken *t = &g_array_index(tokens, Token, i);\n\t\tif (t->type == SYMBOL || t->type == STRING || t->type == NAG)\n\t\t\tfree(t->value.string);\n\t}\n\n\tg_array_free(tokens, TRUE);\n}\n\n\nbool read_pgn(PGN *pgn, const char *input_filename, GError **error)\n{\n\tassert(*error == NULL);\n\n\tbool ret = true;\n\tchar *buf;\n\tgsize length;\n\n\tGFile *file = g_file_new_for_path(input_filename);\n\tif (!g_file_load_contents(file, NULL, &buf, &length, NULL, error)) {\n\t\tret = false;\n\t\tgoto cleanup;\n\t}\n\n\tGArray *tokens = tokenize_pgn(buf, length);\n\tret = parse_tokens(pgn, tokens, error);\n\tfree_tokens(tokens);\n\ncleanup:\n\tg_free(buf);\n\tg_object_unref(file);\n\n\treturn ret;\n}\n\nconst char *seven_tag_roster[] =\n{\n\t\"Event\", \"Site\", \"Date\", \"Round\", \"White\", \"Black\", \"Result\"\n};\n\nbool in_seven_tag_roster(char *tag_name)\n{\n\tsize_t size = sizeof(seven_tag_roster) \/ sizeof(seven_tag_roster[0]);\n\tfor (size_t i = 0; i < size; i++)\n\t\tif (strcmp(tag_name, seven_tag_roster[i]) == 0)\n\t\t\treturn true;\n\t\n\treturn false;\n}\n\nstatic void write_tag(FILE *file, const char *tag_name, const char *tag_value)\n{\n\t\/\/ TODO: handle IO errors\n\tfprintf(file, \"[%s \\\"\" , tag_name);\n\n\tfor (size_t i = 0; tag_value[i] != '\\0'; i++) {\n\t\tchar c = tag_value[i];\n\t\tif (c == '\\\\' || c == '\"')\n\t\t\tputc('\\\\', file);\n\n\t\tputc(c, file);\n\t}\n\n\tfputs(\"\\\"]\\n\", file);\n}\n\nstatic char *default_tag_value(const char *tag_name)\n{\n\tif (strcmp(tag_name, \"Date\") == 0)\n\t\treturn \"????.??.??\";\n\tif (strcmp(tag_name, \"Result\") == 0)\n\t\treturn \"*\";\n\telse\n\t\treturn \"?\";\n}\n\nstatic void process_tag(gpointer key, gpointer value, gpointer user_data)\n{\n\tFILE *file = (FILE *)user_data;\n\tchar *tag_name = (char *)key;\n\tchar *tag_value = (char *)value;\n\n\t\/\/ We print the standard seven tags first, in a specified order, so don't\n\t\/\/ print them again.\n\tif (in_seven_tag_roster(tag_name))\n\t\treturn;\n\n\twrite_tag(file, tag_name, tag_value);\n}\n\n\/\/ TODO: handle IO errors\nbool write_pgn(PGN *pgn, FILE *file)\n{\n\tsize_t size = sizeof(seven_tag_roster) \/ sizeof(seven_tag_roster[0]);\n\tfor (size_t i = 0; i < size; i++) {\n\t\tconst char *tag_name = seven_tag_roster[i];\n\t\tconst char *tag_value = g_hash_table_contains(pgn->tags, tag_name) ?\n\t\t\tg_hash_table_lookup(pgn->tags, tag_name) :\n\t\t\tdefault_tag_value(tag_name);\n\t\twrite_tag(file, tag_name, tag_value);\n\t}\n\tg_hash_table_foreach(pgn->tags, process_tag, (void *)file);\n\n\tputc('\\n', file);\n\t\n\tGame *game = pgn->game->children;\n\tdo {\n\t\t\/\/ A lot of the logic in here seems reversed\/offset by one. This is\n\t\t\/\/ because the board associated with a particular move actually lives\n\t\t\/\/ at the parent node for that board\n\t\tif (game->board->turn == BLACK)\n\t\t\tfprintf(file, game->board->move_number == 1 ?\n\t\t\t\t\"%d.\" :\n\t\t\t\t\" %d.\", game->board->move_number);\n\n\t\tchar move_str[MAX_NOTATION_LENGTH];\n\t\tmove_notation(game->parent->board, game->move, move_str);\n\t\tfprintf(file, \" %s\", move_str);\n\t\t\n\t\tgame = first_child(game);\n\t} while (game != NULL);\n\n\tfprintf(file, \" %s\\n\", game_termination_marker(pgn->result));\n\n\treturn true;\n}\n\nvoid free_pgn(PGN *pgn)\n{\n\tg_hash_table_destroy(pgn->tags);\n\tfree_game(pgn->game);\n}\n","old_contents":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"board.h\"\n#include \"moves.h\"\n#include \"pgn.h\"\n\n\/\/ TODO: error messages\n\n%%{\n\tmachine pgn_tokenizer;\n\twrite data;\n}%%\n\ntypedef enum Token_type\n{\n\t\/\/ Tokens with different values\n\tSTRING, INTEGER, NAG, SYMBOL,\n\t\/\/ Fixed tokens - always just a single character\n\tDOT, ASTERISK, L_SQUARE_BRACKET, R_SQUARE_BRACKET,\n\tL_BRACKET, R_BRACKET, L_ANGLE_BRACKET, R_ANGLE_BRACKET, \n} Token_type;\n\ntypedef union Token_value {\n\tchar *string;\n\tuint integer;\n} Token_value;\n\ntypedef struct Token\n{\n\tToken_type type;\n\tToken_value value;\n} Token;\n\nvoid print_token(Token *t)\n{\n\tswitch (t->type) {\n\tcase STRING: printf(\"STRING: %s\\n\", t->value.string); break;\n\tcase SYMBOL: printf(\"SYMBOL: %s\\n\", t->value.string); break;\n\tcase NAG: printf(\"NAG: %s\\n\", t->value.string); break;\n\tcase INTEGER: printf(\"INTEGER: %d\\n\", t->value.integer); break;\n\tcase DOT: puts(\"DOT\"); break;\n\tcase ASTERISK: puts(\"DOT\"); break;\n\tcase L_SQUARE_BRACKET: puts(\"L_SQUARE_BRACKET\"); break;\n\tcase R_SQUARE_BRACKET: puts(\"R_SQUARE_BRACKET\"); break;\n\tcase L_BRACKET: puts(\"L_BRACKET\"); break;\n\tcase R_BRACKET: puts(\"R_BRACKET\"); break;\n\tcase L_ANGLE_BRACKET: puts(\"L_ANGLE_BRACKET\"); break;\n\tcase R_ANGLE_BRACKET: puts(\"R_ANGLE_BRACKET\"); break;\n\t}\n}\n\nbool symbol_is_integer(Token *t)\n{\n\tchar *str = t->value.string;\n\tfor (size_t i = 0; str[i] != '\\0'; i++)\n\t\tif (!isdigit(str[i]))\n\t\t\treturn false;\n\n\treturn true;\n}\n\t\t\n\nchar *escape_string(char *str, size_t length)\n{\n\tchar *out = malloc(length + 1);\n\tsize_t j = 0;\n\tbool escaping = false;\n\n\tfor (size_t i = 0; i < length; i++) {\n\t\tchar c = str[i];\n\t\tswitch (c) {\n\t\tcase '\\\\':\n\t\t\tif (escaping) {\n\t\t\t\tout[j++] = '\\\\';\n\t\t\t\tescaping = false;\n\t\t\t} else {\n\t\t\t\tescaping = true;\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\t\/\/ We should never come across an unescaped quote in a string, as\n\t\t\t\/\/ the tokenizer should have terminated the string in this case.\n\t\t\tassert(escaping);\n\n\t\t\tout[j++] = '\"';\n\t\t\tescaping = false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tout[j++] = c;\n\t\t\tescaping = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tout[j] = '\\0';\n\n\treturn out;\n}\n\nstatic GArray *tokenize_pgn(char *buf, gsize length)\n{\n\t\/\/ The initial size (140) is just a rough estimate of the average number of\n\t\/\/ tokens, based on 4 tokens for each of the 7 required tags, and 4 tokens\n\t\/\/ for each of 30 moves.\n\tGArray *tokens = g_array_sized_new(FALSE, FALSE, sizeof(Token), 140);\n\n\t\/\/ Variables that Ragel needs\n\tchar *p = buf, *pe = buf + length;\n\tchar *eof = NULL;\n\tchar *ts, *te;\n\tint cs, act;\n\t\/\/ act is initialized for scanners, so it must be declared, but in this\n\t\/\/ scanner we don't actually use it. This silences the compiler warning.\n\tIGNORE(act);\n\n\t%%write init;\n\t%%{\n\t\taction add_string {\n\t\t\t\/\/ - 2 for quotes\n\t\t\tsize_t length = te - ts - 2;\n\t\t\tchar *token = escape_string(ts + 1, length);\n\n\t\t\tToken t = { STRING, { token } };\n\n\t\t\tg_array_append_val(tokens, t);\n\t\t}\n\n\t\taction add_symbol {\n\t\t\t\/\/ + 1 for null terminator\n\t\t\tsize_t length = te - ts + 1;\n\t\t\tchar *token = malloc(length); \n\t\t\tstrncpy(token, ts, length - 1);\n\t\t\ttoken[length - 1] = '\\0';\n\n\t\t\tToken t = { SYMBOL, { token } };\n\n\t\t\tg_array_append_val(tokens, t);\n\t\t}\n\n\t\taction add_nag {\n\t\t\t\/\/ + 1 for null terminator\n\t\t\tsize_t length = te - ts + 1;\n\t\t\tchar *token = malloc(length); \n\t\t\tstrncpy(token, ts, length - 1);\n\t\t\ttoken[length - 1] = '\\0';\n\n\t\t\tToken t = { NAG, { token } };\n\n\t\t\tg_array_append_val(tokens, t);\n\t\t}\n\n\t\t# Token types, as per PGN spec section 7\n\t\t# Integers are read as symbols, and we convert them in the second pass\n\n\t\t# We cheat a little bit here.\n\t\t# According to the PGN spec, game termination markers are simply symbols.\n\t\t# However, according to the definition of the symbol token, symbols\n\t\t# cannot contain the '\/' character. This seems like a contradiction, so\n\t\t# to work around it we allow '\/'s in symbols.\n\t\tsymbol = alnum (alnum | [_+#=:\\-\/])*;\n\t\tstring = '\"' (('\\\\' print) | (print - '\\\\\"'))* '\"';\n\t\tnag = '$' digit+;\n\n\n\t\tmain := |*\n\t\t\tspace;\n\t\t\tsymbol => add_symbol;\n\t\t\tstring => add_string;\n\t\t\tnag => add_nag;\n\t\t\t'.' => { Token t = { DOT, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'*' => { Token t = { ASTERISK, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'[' => { Token t = { L_SQUARE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t']' => { Token t = { R_SQUARE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'(' => { Token t = { L_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t')' => { Token t = { R_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'<' => { Token t = { L_ANGLE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t\t'>' => { Token t = { R_ANGLE_BRACKET, { 0 } }; g_array_append_val(tokens, t); };\n\t\t*|;\n\n\n\t\twrite exec;\n\t}%%\n\n\t\/\/ Integers are a subset of symbols, and unfortunately Ragel scanners\n\t\/\/ attempt to match longer patterns before shorter ones.\n\t\/\/ So we do a second pass to look for symbols that are integers.\n\tfor (size_t i = 0; i < tokens->len; i++) {\n\t\tToken *t = &g_array_index(tokens, Token, i);\n\t\tif (t->type == SYMBOL && symbol_is_integer(t)) {\n\t\t\tint n;\n\t\t\tsscanf(t->value.string, \"%d\", &n);\n\n\t\t\tt->type = INTEGER;\n\t\t\tt->value.integer = n;\n\t\t}\n\t}\n\n\treturn tokens;\n}\n\n\/\/ It is impossible to parse a move without a reference to a particular board,\n\/\/ as something like Bd5 could start from any square on that diagonal.\nstatic Move parse_move(Board *board, char *notation)\n{\n\tif (strcmp(notation, \"O-O\") == 0) {\n\t\tuint rank = board->turn == WHITE ? 0 : 7;\n\t\treturn MOVE(SQUARE(4, rank), SQUARE(6, rank));\n\t}\n\tif (strcmp(notation, \"O-O-O\") == 0) {\n\t\tuint rank = board->turn == WHITE ? 0 : 7;\n\t\treturn MOVE(SQUARE(4, rank), SQUARE(2, rank));\n\t}\n\n\tchar stripped[5]; \/\/ max length without 'x#+'s, + 1 for null terminator\n\tsize_t j = 0;\n\tfor (size_t i = 0; notation[i] != '\\0'; i++)\n\t\tif (notation[i] != 'x' && notation[i] != '#' && notation[i] != '+')\n\t\t\tstripped[j++] = notation[i];\n\tstripped[j] = '\\0';\n\n\tsize_t i = 0;\n\tPiece_type type;\n\t\/\/ If it's a pawn move, the target square starts at the beginning of the\n\t\/\/ string\n\tif (islower(stripped[0])) {\n\t\ttype = PAWN;\n\n\t\t\/\/ An exception: if it's a move like exd5, the target square starts one \n\t\t\/\/ char further on\n\t\tif (islower(stripped[1]))\n\t\t\ti++;\n\t} else {\n\t\ttype = PIECE_TYPE(piece_from_char(stripped[0]));\n\t\ti++;\n\t}\n\t\n\tchar disambig = 0;\n\tif (j == 4)\n\t\t\/\/ If it's this long, there must be a disambiguation char in there\n\t\tdisambig = stripped[i++];\n\t\n\tuint target_file = CHAR_FILE(stripped[i++]);\n\tuint target_rank = CHAR_RANK(stripped[i++]);\n\n\tif (disambig != 0) {\n\t\tuint x = 0, y = 0, dx = 0, dy = 0;\n\t\tif (disambig >= 'a' && disambig <= 'g') {\n\t\t\tx = CHAR_FILE(disambig);\n\t\t\tdy = 1;\n\t\t} else if (disambig >= '1' && disambig <= '8') {\n\t\t\ty = CHAR_RANK(disambig);\n\t\t\tdx = 1;\n\t\t} else {\n\t\t\treturn NULL_MOVE;\n\t\t}\n\n\t\tfor (; x < BOARD_SIZE && y < BOARD_SIZE; x += dx, y += dy) {\n\t\t\tPiece p = PIECE_AT(board, x, y);\n\t\t\tif (PIECE_TYPE(p) != type || PLAYER(p) != board->turn)\n\t\t\t\tcontinue;\n\n\t\t\tMove m = MOVE(SQUARE(x, y), SQUARE(target_file, target_rank));\n\t\t\tif (legal_move(board, m, true))\n\t\t\t\treturn m;\n\t\t}\n\n\t\treturn NULL_MOVE;\n\t}\n\n\tfor (uint x = 0; x < BOARD_SIZE; x++) {\n\t\tfor (uint y = 0; y < BOARD_SIZE; y++) {\n\t\t\tPiece p = PIECE_AT(board, x, y);\n\t\t\tif (PIECE_TYPE(p) != type || PLAYER(p) != board->turn)\n\t\t\t\tcontinue;\n\n\t\t\tMove m = MOVE(SQUARE(x, y), SQUARE(target_file, target_rank));\n\t\t\tif (legal_move(board, m, true))\n\t\t\t\treturn m;\n\t\t}\n\t}\n\n\treturn NULL_MOVE;\n}\n\nstatic Result parse_game_termination_marker(char *symbol)\n{\n\tif (strcmp(symbol, \"1-0\") == 0)\n\t\treturn WHITE_WINS;\n\tif (strcmp(symbol, \"0-1\") == 0)\n\t\treturn BLACK_WINS;\n\tif (strcmp(symbol, \"1\/2-1\/2\") == 0)\n\t\treturn DRAW;\n\tif (strcmp(symbol, \"*\") == 0)\n\t\treturn OTHER;\n\t\n\treturn NULL_MOVE;\n}\n\nstatic char *game_termination_marker(Result r)\n{\n\tswitch (r) {\n\tcase WHITE_WINS: return \"1-0\";\n\tcase BLACK_WINS: return \"0-1\";\n\tcase DRAW: return \"1\/2-1\/2\";\n\tdefault: return \"*\";\n\t}\n}\n\nstatic bool parse_tokens(PGN *pgn, GArray *tokens)\n{\n\t\/\/ Start with tags\n\tpgn->tags = g_hash_table_new(g_str_hash, g_str_equal);\n\n\tsize_t i = 0;\n\twhile ((&g_array_index(tokens, Token, i))->type == L_SQUARE_BRACKET) {\n\t\tToken *tag_name_token = &g_array_index(tokens, Token, ++i);\n\t\tif (tag_name_token->type != SYMBOL)\n\t\t\treturn false;\n\n\t\tchar *tag_name = tag_name_token->value.string;\n\n\t\tif (g_hash_table_contains(pgn->tags, tag_name))\n\t\t\treturn false;\n\n\t\tToken *tag_value_token = &g_array_index(tokens, Token, ++i);\n\t\tif (tag_value_token->type != STRING)\n\t\t\treturn false;\n\n\t\tchar *tag_value = tag_value_token->value.string;\n\n\t\tchar *tag_name_copy = malloc(strlen(tag_name) + 1);\n\t\tstrcpy(tag_name_copy, tag_name);\n\t\tchar *tag_value_copy = malloc(strlen(tag_value) + 1);\n\t\tstrcpy(tag_value_copy, tag_value);\n\n\t\tg_hash_table_insert(pgn->tags, tag_name_copy, tag_value_copy);\n\n\t\tToken *close_square_bracket_token = &g_array_index(tokens, Token, ++i);\n\t\tif (close_square_bracket_token->type != R_SQUARE_BRACKET)\n\t\t\treturn false;\n\n\t\ti++;\n\t}\n\n\t\/\/ Now the movetext section\n\tuint half_move_number = 2;\n\n\tGame *game = new_game();\n\tgame->board = malloc(sizeof(Board));\n\tpgn->game = game;\n\t\/\/ TODO: Use value in start board tag if present.\n\tfrom_fen(game->board, start_board_fen);\n\n\t\/\/ TODO: variations, NAG\n\twhile (i < tokens->len) {\n\t\tToken *t = &g_array_index(tokens, Token, i++);\n\t\tif (t->type == INTEGER) {\n\t\t\tif (t->value.integer != half_move_number \/ 2)\n\t\t\t\treturn false;\n\n\t\t\twhile ((t = &g_array_index(tokens, Token, i++))->type == DOT)\n\t\t\t\t;\n\t\t}\n\n\t\tif (t->type != SYMBOL)\n\t\t\treturn false;\n\n\t\tResult r;\n\t\tif ((r = parse_game_termination_marker(t->value.string)) != NULL_RESULT) {\n\t\t\tpgn->result = r;\n\n\t\t\t\/\/ If we didn't see a result tag, try to fill it in with the value\n\t\t\t\/\/ in the game termination marker\n\n\t\t\tif (!g_hash_table_contains(pgn->tags, \"Result\")) {\n\t\t\t\tchar *tmp = malloc(strlen(t->value.string));\n\t\t\t\tstrcpy(tmp, t->value.string);\n\t\t\t\tg_hash_table_insert(pgn->tags, \"Result\", tmp);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tMove m;\n\t\tif ((m = parse_move(game->board, t->value.string)) == NULL_MOVE)\n\t\t\treturn false;\n\n\t\tBoard *new_board = malloc(sizeof *new_board);\n\t\tcopy_board(new_board, game->board);\n\t\tperform_move(new_board, m);\n\t\tadd_child(game, m, new_board);\n\t\tgame = first_child(game);\n\n\t\thalf_move_number++;\n\t}\n\n\treturn true;\n}\n\nvoid free_tokens(GArray *tokens)\n{\n\tfor (size_t i = 0; i < tokens->len; i++) {\n\t\tToken *t = &g_array_index(tokens, Token, i);\n\t\tif (t->type == SYMBOL || t->type == STRING || t->type == NAG)\n\t\t\tfree(t->value.string);\n\t}\n\n\tg_array_free(tokens, TRUE);\n}\n\n\nbool read_pgn(PGN *pgn, const char *input_filename, GError **error)\n{\n\tassert(*error == NULL);\n\n\tbool ret = true;\n\tchar *buf;\n\tgsize length;\n\n\tGFile *file = g_file_new_for_path(input_filename);\n\tif (!g_file_load_contents(file, NULL, &buf, &length, NULL, error)) {\n\t\tret = false;\n\t\tgoto cleanup;\n\t}\n\n\tGArray *tokens = tokenize_pgn(buf, length);\n\tret = parse_tokens(pgn, tokens);\n\tfree_tokens(tokens);\n\ncleanup:\n\tg_free(buf);\n\tg_object_unref(file);\n\n\treturn ret;\n}\n\nconst char *seven_tag_roster[] =\n{\n\t\"Event\", \"Site\", \"Date\", \"Round\", \"White\", \"Black\", \"Result\"\n};\n\nbool in_seven_tag_roster(char *tag_name)\n{\n\tsize_t size = sizeof(seven_tag_roster) \/ sizeof(seven_tag_roster[0]);\n\tfor (size_t i = 0; i < size; i++)\n\t\tif (strcmp(tag_name, seven_tag_roster[i]) == 0)\n\t\t\treturn true;\n\t\n\treturn false;\n}\n\nstatic void write_tag(FILE *file, const char *tag_name, const char *tag_value)\n{\n\t\/\/ TODO: handle IO errors\n\tfprintf(file, \"[%s \\\"\" , tag_name);\n\n\tfor (size_t i = 0; tag_value[i] != '\\0'; i++) {\n\t\tchar c = tag_value[i];\n\t\tif (c == '\\\\' || c == '\"')\n\t\t\tputc('\\\\', file);\n\n\t\tputc(c, file);\n\t}\n\n\tfputs(\"\\\"]\\n\", file);\n}\n\nstatic char *default_tag_value(const char *tag_name)\n{\n\tif (strcmp(tag_name, \"Date\") == 0)\n\t\treturn \"????.??.??\";\n\tif (strcmp(tag_name, \"Result\") == 0)\n\t\treturn \"*\";\n\telse\n\t\treturn \"?\";\n}\n\nstatic void process_tag(gpointer key, gpointer value, gpointer user_data)\n{\n\tFILE *file = (FILE *)user_data;\n\tchar *tag_name = (char *)key;\n\tchar *tag_value = (char *)value;\n\n\t\/\/ We print the standard seven tags first, in a specified order, so don't\n\t\/\/ print them again.\n\tif (in_seven_tag_roster(tag_name))\n\t\treturn;\n\n\twrite_tag(file, tag_name, tag_value);\n}\n\n\/\/ TODO: handle IO errors\nbool write_pgn(PGN *pgn, FILE *file)\n{\n\tsize_t size = sizeof(seven_tag_roster) \/ sizeof(seven_tag_roster[0]);\n\tfor (size_t i = 0; i < size; i++) {\n\t\tconst char *tag_name = seven_tag_roster[i];\n\t\tconst char *tag_value = g_hash_table_contains(pgn->tags, tag_name) ?\n\t\t\tg_hash_table_lookup(pgn->tags, tag_name) :\n\t\t\tdefault_tag_value(tag_name);\n\t\twrite_tag(file, tag_name, tag_value);\n\t}\n\tg_hash_table_foreach(pgn->tags, process_tag, (void *)file);\n\n\tputc('\\n', file);\n\t\n\tGame *game = pgn->game->children;\n\tdo {\n\t\t\/\/ A lot of the logic in here seems reversed\/offset by one. This is\n\t\t\/\/ because the board associated with a particular move actually lives\n\t\t\/\/ at the parent node for that board\n\t\tif (game->board->turn == BLACK)\n\t\t\tfprintf(file, game->board->move_number == 1 ?\n\t\t\t\t\"%d.\" :\n\t\t\t\t\" %d.\", game->board->move_number);\n\n\t\tchar move_str[MAX_NOTATION_LENGTH];\n\t\tmove_notation(game->parent->board, game->move, move_str);\n\t\tfprintf(file, \" %s\", move_str);\n\t\t\n\t\tgame = first_child(game);\n\t} while (game != NULL);\n\n\tfprintf(file, \" %s\\n\", game_termination_marker(pgn->result));\n\n\treturn true;\n}\n\nvoid free_pgn(PGN *pgn)\n{\n\tg_hash_table_destroy(pgn->tags);\n\tfree_game(pgn->game);\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"03b235a57808aadd6239a3209c0855b3815dc6ac","subject":"SSA: More parser resilience for files with weird handwritten headers","message":"SSA: More parser resilience for files with weird handwritten headers\n\n- Allow spaces at the end of section header lines\n- Be completely case-insensitive when reading section header lines\n- Skip reading comments into the dictionary (no behavior change, only micro optimization)\n\nFixes [CrunchySubs] Otome Yokai Zakuro - 02 [720p].mkv\n\ngit-svn-id: d8f21eb7283bfb39ebab2f8f9b4a259b233f9348@1365 621663c8-3916-0410-8f58-edc14a8543d5\n","repos":"mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian","old_file":"Subtitles\/SubParsing.m.rl","new_file":"Subtitles\/SubParsing.m.rl","new_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\/*\n * Parsing of SSA\/ASS subtitle files using Ragel.\n * At the moment, all subtitle formats supported by Perian\n * are converted to SSA before reaching here.\n * Feel free to implement new file formats as Ragel parsers here\n * if it ends up cleaner than doing it by hand.\n *\n * SSA specification (as it exists):\n * http:\/\/google.com\/codesearch\/p?hl=en#_g4u1OIsR_M\/trunk\/src\/subtitles\/STS.cpp&q=package:vsfilter%20%22v4%22&sa=N&cd=7&ct=rc&l=1395\n * http:\/\/moodub.free.fr\/video\/ass-specs.doc \n *\n * FIXME:\n * - Files which can't be parsed have no clear error messages.\n * - Line and section names are case-insensitive in VSFilter, but we\n * assume they are capitalized as in Aegisub.\n * - SSA v4.00++ is not supported.\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\nSubRGBAColor SubParseSSAColor(unsigned rgb)\n{\n\tunsigned char r, g, b, a;\n\t\n\ta = (rgb >> 24) & 0xff;\n\tb = (rgb >> 16) & 0xff;\n\tg = (rgb >> 8) & 0xff;\n\tr = rgb & 0xff;\n\t\n\ta = 255-a;\n\t\n\treturn (SubRGBAColor){r\/255.,g\/255.,b\/255.,a\/255.};\n}\n\nSubRGBAColor SubParseSSAColorString(NSString *c)\n{\n\tconst char *c_ = [c UTF8String];\n\tunsigned int rgb;\n\t\n\tif (c_[0] == '&') {\n\t\trgb = strtoul(&c_[2],NULL,16);\n\t} else {\n\t\trgb = strtol(c_,NULL,0);\n\t}\n\t\n\treturn SubParseSSAColor(rgb);\n}\n\nUInt8 SubASSFromSSAAlignment(UInt8 a)\n{\n int h = 1, v = 0;\n\tif (a >= 9 && a <= 11) {v = kSubAlignmentMiddle; h = a-8;}\n\tif (a >= 5 && a <= 7) {v = kSubAlignmentTop; h = a-4;}\n\tif (a >= 1 && a <= 3) {v = kSubAlignmentBottom; h = a;}\n\treturn v * 3 + h;\n}\n\nvoid SubParseASSAlignment(UInt8 a, UInt8 *alignH, UInt8 *alignV)\n{\n\tswitch (a) {\n\t\tdefault: case 1 ... 3: *alignV = kSubAlignmentBottom; break;\n\t\tcase 4 ... 6: *alignV = kSubAlignmentMiddle; break;\n\t\tcase 7 ... 9: *alignV = kSubAlignmentTop; break;\n\t}\n\t\n\tswitch (a) {\n\t\tcase 1: case 4: case 7: *alignH = kSubAlignmentLeft; break;\n\t\tdefault: case 2: case 5: case 8: *alignH = kSubAlignmentCenter; break;\n\t\tcase 3: case 6: case 9: *alignH = kSubAlignmentRight; break;\n\t}\n}\n\nBOOL SubParseFontVerticality(NSString **fontname)\n{\n\tif ([*fontname length] && [*fontname characterAtIndex:0] == '@') {\n\t\t*fontname = [*fontname substringFromIndex:1];\n\t\treturn YES;\n\t}\n\treturn NO;\n}\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = SubSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = SubSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = SubUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *headerdict = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\tBOOL is_ass = NO;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[headerdict setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupstyles {\n\t\t\tcur_array=stylearr;\n\t\t\tis_ass = IsScriptASS(headerdict);\n\t\t\tstyleformat = is_ass ?\n\t\t\t\t@\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\"\n\t\t\t :@\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";\n\t\t}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = is_ass ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\"\n\t\t\t :@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tcomment = \";\" :> str;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\tkeyvalueline = str >sstart %savestr :> (\":\" ws* %sstart str %setheaderval);\n\t\theaderline = (keyvalueline | comment | str) :> nl;\n\t\theader = \"[\" [Ss] \"cript \" [Ii] \"nfo]\" ws* nl headerline*;\n\t\t\n\t\tstyleline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\tstyles = (\"[\" [Vv] \"4\" \"+\"? \" \" [Ss] \"tyles]\") %setupstyles ws* nl styleline*;\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[\" [Ee] \"vents]\" %setupevents ws* nl event*;\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = headerdict;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = SubStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = SubSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = SubUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tSubParseASSAlignment(SubASSFromSSAAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tSubParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|\"fr\" \"z\"? floatnum %frz\n\t\t\t\t\t\t\t|\"frx\" floatnum\n\t\t\t\t\t\t\t|\"fry\" floatnum\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|\"1\"? \"c\" color %primaryc\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|[kK] [fo]? intnum\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|\"fad\" \"e\"? parens\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSubSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","old_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\/*\n * Parsing of SSA\/ASS subtitle files using Ragel.\n * At the moment, all subtitle formats supported by Perian\n * are converted to SSA before reaching here.\n * Feel free to implement new file formats as Ragel parsers here\n * if it ends up cleaner than doing it by hand.\n *\n * SSA specification (as it exists):\n * http:\/\/google.com\/codesearch\/p?hl=en#_g4u1OIsR_M\/trunk\/src\/subtitles\/STS.cpp&q=package:vsfilter%20%22v4%22&sa=N&cd=7&ct=rc&l=1395\n * http:\/\/moodub.free.fr\/video\/ass-specs.doc \n *\n * FIXME:\n * - Files which can't be parsed have no clear error messages.\n * - Line and section names are case-insensitive in VSFilter, but we\n * assume they are capitalized as in Aegisub.\n * - SSA v4.00++ is not supported.\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\nSubRGBAColor SubParseSSAColor(unsigned rgb)\n{\n\tunsigned char r, g, b, a;\n\t\n\ta = (rgb >> 24) & 0xff;\n\tb = (rgb >> 16) & 0xff;\n\tg = (rgb >> 8) & 0xff;\n\tr = rgb & 0xff;\n\t\n\ta = 255-a;\n\t\n\treturn (SubRGBAColor){r\/255.,g\/255.,b\/255.,a\/255.};\n}\n\nSubRGBAColor SubParseSSAColorString(NSString *c)\n{\n\tconst char *c_ = [c UTF8String];\n\tunsigned int rgb;\n\t\n\tif (c_[0] == '&') {\n\t\trgb = strtoul(&c_[2],NULL,16);\n\t} else {\n\t\trgb = strtol(c_,NULL,0);\n\t}\n\t\n\treturn SubParseSSAColor(rgb);\n}\n\nUInt8 SubASSFromSSAAlignment(UInt8 a)\n{\n int h = 1, v = 0;\n\tif (a >= 9 && a <= 11) {v = kSubAlignmentMiddle; h = a-8;}\n\tif (a >= 5 && a <= 7) {v = kSubAlignmentTop; h = a-4;}\n\tif (a >= 1 && a <= 3) {v = kSubAlignmentBottom; h = a;}\n\treturn v * 3 + h;\n}\n\nvoid SubParseASSAlignment(UInt8 a, UInt8 *alignH, UInt8 *alignV)\n{\n\tswitch (a) {\n\t\tdefault: case 1 ... 3: *alignV = kSubAlignmentBottom; break;\n\t\tcase 4 ... 6: *alignV = kSubAlignmentMiddle; break;\n\t\tcase 7 ... 9: *alignV = kSubAlignmentTop; break;\n\t}\n\t\n\tswitch (a) {\n\t\tcase 1: case 4: case 7: *alignH = kSubAlignmentLeft; break;\n\t\tdefault: case 2: case 5: case 8: *alignH = kSubAlignmentCenter; break;\n\t\tcase 3: case 6: case 9: *alignH = kSubAlignmentRight; break;\n\t}\n}\n\nBOOL SubParseFontVerticality(NSString **fontname)\n{\n\tif ([*fontname length] && [*fontname characterAtIndex:0] == '@') {\n\t\t*fontname = [*fontname substringFromIndex:1];\n\t\treturn YES;\n\t}\n\treturn NO;\n}\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = SubSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = SubSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = SubUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *headerdict = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\tBOOL is_ass = NO;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[headerdict setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupstyles {\n\t\t\tcur_array=stylearr;\n\t\t\tis_ass = IsScriptASS(headerdict);\n\t\t\tstyleformat = is_ass ?\n\t\t\t\t@\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\"\n\t\t\t :@\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";\n\t\t}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = is_ass ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\"\n\t\t\t :@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\tkeyvalueline = str >sstart %savestr :> (\":\" ws* %sstart str %setheaderval);\n\t\theaderline = (keyvalueline | str) :> nl;\n\t\theader = \"[Script Info]\" nl headerline*;\n\t\t\n\t\tstyleline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\tstyles = (\"[\" [Vv] \"4\" \"+\"? \" Styles]\") %setupstyles nl styleline*;\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl event*;\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = headerdict;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = SubStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = SubSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = SubUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tSubParseASSAlignment(SubASSFromSSAAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tSubParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|\"fr\" \"z\"? floatnum %frz\n\t\t\t\t\t\t\t|\"frx\" floatnum\n\t\t\t\t\t\t\t|\"fry\" floatnum\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|\"1\"? \"c\" color %primaryc\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|[kK] [fo]? intnum\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|\"fad\" \"e\"? parens\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSubSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"407d236e86339f8d870a65fb286ccd6abb7c9241","subject":"CR characters need to be treated as whitespace.","message":"CR characters need to be treated as whitespace.\n","repos":"timoc\/ragel,timoc\/ragel,timoc\/ragel,timoc\/ragel","old_file":"ragel\/rlscan.rl","new_file":"ragel\/rlscan.rl","new_contents":"\/*\n * Copyright 2006-2007 Adrian Thurston \n *\/\n\n\/* This file is part of Ragel.\n *\n * Ragel is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Ragel is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Ragel; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"ragel.h\"\n#include \"rlparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nextern char *Parser_lelNames[];\n\n\/* This is used for tracking the current stack of include file\/machine pairs. It is\n * is used to detect and recursive include structure. *\/\nstruct IncludeStackItem\n{\n\tIncludeStackItem( char *fileName, char *sectionName )\n\t\t: fileName(fileName), sectionName(sectionName) {}\n\n\tchar *fileName;\n\tchar *sectionName;\n};\n\ntypedef Vector IncludeStack;\n\nenum InlineBlockType\n{\n\tCurlyDelimited,\n\tSemiTerminated\n};\n\nstruct Scanner\n{\n\tScanner( char *fileName, istream &input, ostream &output,\n\t\t\tParser *inclToParser, char *inclSectionTarg,\n\t\t\tint includeDepth )\n\t: \n\t\tfileName(fileName), input(input), output(output),\n\t\tinclToParser(inclToParser),\n\t\tinclSectionTarg(inclSectionTarg),\n\t\tincludeDepth(includeDepth),\n\t\tline(1), column(1), lastnl(0), \n\t\tparser(0), active(false), \n\t\tparserExistsError(false),\n\t\twhitespaceOn(true)\n\t\t{}\n\n\tbool recursiveInclude( char *inclFileName, char *inclSectionName );\n\n\tchar *prepareFileName( char *fileName, int len )\n\t{\n\t\tbool caseInsensitive;\n\t\tToken tokenFnStr, tokenRes;\n\t\ttokenFnStr.data = fileName;\n\t\ttokenFnStr.length = len;\n\t\ttokenFnStr.prepareLitString( tokenRes, caseInsensitive );\n\t\treturn tokenRes.data;\n\t}\n\n\tvoid init();\n\tvoid token( int type, char *start, char *end );\n\tvoid token( int type, char c );\n\tvoid token( int type );\n\tvoid updateCol();\n\tvoid startSection();\n\tvoid endSection();\n\tvoid do_scan();\n\tbool parserExists();\n\tostream &scan_error();\n\n\tchar *fileName;\n\tistream &input;\n\tostream &output;\n\tParser *inclToParser;\n\tchar *inclSectionTarg;\n\tint includeDepth;\n\n\tint cs;\n\tint line;\n\tchar *word, *lit;\n\tint word_len, lit_len;\n\tInputLoc sectionLoc;\n\tchar *tokstart, *tokend;\n\tint column;\n\tchar *lastnl;\n\n\t\/* Set by machine statements, these persist from section to section\n\t * allowing for unnamed sections. *\/\n\tParser *parser;\n\tbool active;\n\tIncludeStack includeStack;\n\n\t\/* This is set if ragel has already emitted an error stating that\n\t * no section name has been seen and thus no parser exists. *\/\n\tbool parserExistsError;\n\n\t\/* This is for inline code. By default it is on. It goes off for\n\t * statements and values in inline blocks which are parsed. *\/\n\tbool whitespaceOn;\n};\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid Scanner::init( )\n{\n\t%% write init;\n}\n\nbool Scanner::parserExists()\n{\n\tif ( parser != 0 )\n\t\treturn true;\n\n\tif ( ! parserExistsError ) {\n\t\tscan_error() << \"include: there is no previous specification name\" << endl;\n\t\tparserExistsError = true;\n\t}\n\treturn false;\n}\n\nostream &Scanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 &&\n\t\t\t\tstrcmp( si->sectionName, inclSectionName ) == 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\t\n}\n\nvoid Scanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = tokstart;\n\t\/\/cerr << \"adding \" << tokend - from << \" to column\" << endl;\n\tcolumn += tokend - from;\n\tlastnl = 0;\n}\n\nvoid Scanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid Scanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\n%%{\n\tmachine section_parse;\n\n\t# This relies on the the kelbt implementation and the order\n\t# that tokens are declared.\n\tKW_Machine = 128;\n\tKW_Include = 129;\n\tKW_Write = 130;\n\tTK_Word = 131;\n\tTK_Literal = 132;\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_word { word = tokdata; word_len = toklen; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_machine\n\t{\n\t\t\/* Assign a name to the machine. *\/\n\t\tchar *machine = word;\n\n\t\tif ( inclSectionTarg == 0 ) {\n\t\t\tactive = true;\n\n\t\t\tParserDictEl *pdEl = parserDict.find( machine );\n\t\t\tif ( pdEl == 0 ) {\n\t\t\t\tpdEl = new ParserDictEl( machine );\n\t\t\t\tpdEl->value = new Parser( fileName, machine, sectionLoc );\n\t\t\t\tpdEl->value->init();\n\t\t\t\tparserDict.insert( pdEl );\n\t\t\t}\n\n\t\t\tparser = pdEl->value;\n\t\t}\n\t\telse if ( strcmp( inclSectionTarg, machine ) == 0 ) {\n\t\t\t\/* found include target *\/\n\t\t\tactive = true;\n\t\t\tparser = inclToParser;\n\t\t}\n\t\telse {\n\t\t\t\/* ignoring section *\/\n\t\t\tactive = false;\n\t\t\tparser = 0;\n\t\t}\n\t}\n\n\tmachine_stmt =\n\t\t( KW_Machine TK_Word @store_word ';' ) @handle_machine\n\t\t<>err mach_err <>eof mach_err;\n\n\taction handle_include\n\t{\n\t\tif ( active && parserExists() ) {\n\t\t\tchar *inclSectionName = word;\n\t\t\tchar *inclFileName = 0;\n\n\t\t\t\/* Implement defaults for the input file and section name. *\/\n\t\t\tif ( inclSectionName == 0 )\n\t\t\t\tinclSectionName = parser->sectionName;\n\n\t\t\tif ( lit != 0 ) \n\t\t\t\tinclFileName = prepareFileName( lit, lit_len );\n\t\t\telse\n\t\t\t\tinclFileName = fileName;\n\n\t\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t\t * name then check if what we are including is already in the stack. *\/\n\t\t\tincludeStack.append( IncludeStackItem( fileName, parser->sectionName ) );\n\n\t\t\tif ( recursiveInclude( inclFileName, inclSectionName ) )\n\t\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\t\t\telse {\n\t\t\t\t\/* Open the input file for reading. *\/\n\t\t\t\tifstream *inFile = new ifstream( inclFileName );\n\t\t\t\tif ( ! inFile->is_open() ) {\n\t\t\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\t\t\tinclFileName << \" for reading\" << endl;\n\t\t\t\t}\n\n\t\t\t\tScanner scanner( inclFileName, *inFile, output, parser,\n\t\t\t\t\t\tinclSectionName, includeDepth+1 );\n\t\t\t\tscanner.init();\n\t\t\t\tscanner.do_scan( );\n\t\t\t\tdelete inFile;\n\t\t\t}\n\n\t\t\t\/* Remove the last element (len-1) *\/\n\t\t\tincludeStack.remove( -1 );\n\t\t}\n\t}\n\n\tinclude_names = (\n\t\tTK_Word @store_word ( TK_Literal @store_lit )? |\n\t\tTK_Literal @store_lit\n\t) >clear_words;\n\n\tinclude_stmt =\n\t\t( KW_Include include_names ';' ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction write_command\n\t{\n\t\tif ( active && machineSpec == 0 && machineName == 0 ) {\n\t\t\toutput << \"sectionName << \"\\\"\"\n\t\t\t\t\t\" line=\\\"\" << line << \"\\\"\"\n\t\t\t\t\t\" col=\\\"\" << column << \"\\\"\"\n\t\t\t\t\t\">\";\n\t\t}\n\t}\n\n\taction write_arg\n\t{\n\t\tif ( active && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"\" << tokdata << \"<\/arg>\";\n\t}\n\n\taction write_close\n\t{\n\t\tif ( active && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/write>\\n\";\n\t}\n\n\twrite_stmt =\n\t\t( KW_Write @write_command \n\t\t( TK_Word @write_arg )+ ';' @write_close )\n\t\t<>err write_err <>eof write_err;\n\n\taction handle_token\n\t{\n\t\t\/* Send the token off to the parser. *\/\n\t\tif ( active && parserExists() ) {\n\t\t\tInputLoc loc;\n\n\t\t\t#if 0\n\t\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\t\tcerr << \" \" << toklen;\n\t\t\tif ( tokdata != 0 )\n\t\t\t\tcerr << \" \" << tokdata;\n\t\t\tcerr << endl;\n\t\t\t#endif\n\n\t\t\tloc.fileName = fileName;\n\t\t\tloc.line = line;\n\t\t\tloc.col = column;\n\n\t\t\tparser->token( loc, type, tokdata, toklen );\n\t\t}\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;\n\n\tmain := ( \n\t\tmachine_stmt |\n\t\tinclude_stmt |\n\t\twrite_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid Scanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n}\n\nvoid Scanner::startSection( )\n{\n\tparserExistsError = false;\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/host>\\n\";\n\t}\n\n\tsectionLoc.fileName = fileName;\n\tsectionLoc.line = line;\n\tsectionLoc.col = 0;\n}\n\nvoid Scanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t%%{\n\t\tmachine section_parse;\n\t\twrite eof;\n\t}%%\n\n\t\/* Close off the section with the parser. *\/\n\tif ( active && parserExists() ) {\n\t\tInputLoc loc;\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = 0;\n\n\t\tparser->token( loc, TK_EndSection, 0, 0 );\n\t}\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 ) {\n\t\t\t\/* The end section may include a newline on the end, so\n\t\t\t * we use the last line, which will count the newline. *\/\n\t\t\toutput << \"\";\n\t\t}\n\t}\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\tc_comment = \n\t\t'\/*' ( any | NL )* :>> '*\/';\n\n\tcpp_comment =\n\t\t'\/\/' [^\\n]* NL;\n\n\tc_cpp_comment = c_comment | cpp_comment;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\t# An inline block of code. This is specified as a scanned, but is sent to\n\t# the parser as one long block. The inline_block pointer is used to handle\n\t# the preservation of the data.\n\tinline_code := |*\n\t\t# Inline expression keywords.\n\t\t\"fpc\" => { token( KW_PChar ); };\n\t\t\"fc\" => { token( KW_Char ); };\n\t\t\"fcurs\" => { token( KW_CurState ); };\n\t\t\"ftargs\" => { token( KW_TargState ); };\n\t\t\"fentry\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Entry );\n\t\t};\n\n\t\t# Inline statement keywords.\n\t\t\"fhold\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Hold );\n\t\t};\n\t\t\"fexec\" => { token( KW_Exec, 0, 0 ); };\n\t\t\"fgoto\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Goto );\n\t\t};\n\t\t\"fnext\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Next );\n\t\t};\n\t\t\"fcall\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Call );\n\t\t};\n\t\t\"fret\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Ret );\n\t\t};\n\t\t\"fbreak\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Break );\n\t\t};\n\n\t\tident => { token( TK_Word, tokstart, tokend ); };\n\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t( s_literal | d_literal ) \n\t\t\t=> { token( IL_Literal, tokstart, tokend ); };\n\n\t\twhitespace+ => { \n\t\t\tif ( whitespaceOn ) \n\t\t\t\ttoken( IL_WhiteSpace, tokstart, tokend );\n\t\t};\n\t\tc_cpp_comment => { token( IL_Comment, tokstart, tokend ); };\n\n\t\t\"::\" => { token( TK_NameSep, tokstart, tokend ); };\n\n\t\t# Some symbols need to go to the parser as with their cardinal value as\n\t\t# the token type (as opposed to being sent as anonymous symbols)\n\t\t# because they are part of the sequences which we interpret. The * ) ;\n\t\t# symbols cause whitespace parsing to come back on. This gets turned\n\t\t# off by some keywords.\n\n\t\t\";\" => {\n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t\tif ( inlineBlockType == SemiTerminated )\n\t\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t[*)] => { \n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t};\n\n\t\t[,(] => { token( *tokstart, tokstart, tokend ); };\n\n\t\t'{' => { \n\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\tcurly_count += 1; \n\t\t};\n\n\t\t'}' => { \n\t\t\tif ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {\n\t\t\t\t\/* Inline code block ends. *\/\n\t\t\t\ttoken( '}' );\n\t\t\t\tfgoto parser_def;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/* Either a semi terminated inline block or only the closing\n\t\t\t\t * brace of some inner scope, not the block's closing brace. *\/\n\t\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\t}\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated code block\" << endl;\n\t\t};\n\n\t\t# Send every other character as a symbol.\n\t\tany => { token( IL_Symbol, tokstart, tokend ); };\n\t*|;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( RE_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( RE_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( RE_Char, tokstart, tokend ); };\n\n\t*|;\n\n\tre_literal := |*\n\t\t# Escape sequences in regular expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Terminate an OR expression.\n\t\t'\/' [i]? => { \n\t\t\ttoken( RE_Slash, tokstart, tokend ); \n\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t# Special characters.\n\t\t'.' => { token( RE_Dot ); };\n\t\t'*' => { token( RE_Star ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated regular expression\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\\/] => { token( RE_Char, tokstart, tokend ); };\n\t*|;\n\n\t# We need a separate token space here to avoid the ragel keywords.\n\twrite_statement := |*\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\t\t[ \\t\\n]+ => { updateCol(); };\n\t\t';' => { token( ';' ); fgoto parser_def; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated write statement\" << endl;\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tparser_def := |*\n\t\t'machine' => { token( KW_Machine ); };\n\t\t'include' => { token( KW_Include ); };\n\t\t'write' => { \n\t\t\ttoken( KW_Write );\n\t\t\tfgoto write_statement;\n\t\t};\n\t\t'action' => { token( KW_Action ); };\n\t\t'alphtype' => { token( KW_AlphType ); };\n\n\t\t# FIXME: Enable this post 5.17.\n\t\t# 'range' => { token( KW_Range ); };\n\n\t\t'getkey' => { \n\t\t\ttoken( KW_GetKey );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'access' => { \n\t\t\ttoken( KW_Access );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'variable' => { \n\t\t\ttoken( KW_Variable );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'when' => { token( KW_When ); };\n\t\t'eof' => { token( KW_Eof ); };\n\t\t'err' => { token( KW_Err ); };\n\t\t'lerr' => { token( KW_Lerr ); };\n\t\t'to' => { token( KW_To ); };\n\t\t'from' => { token( KW_From ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, tokstart, tokend ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( RE_Slash ); fgoto re_literal; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t':=' => { token( TK_ColonEquals ); };\n\n\t\t# To State Actions.\n\t\t\">~\" => { token( TK_StartToState ); };\n\t\t\"$~\" => { token( TK_AllToState ); };\n\t\t\"%~\" => { token( TK_FinalToState ); };\n\t\t\"<~\" => { token( TK_NotStartToState ); };\n\t\t\"@~\" => { token( TK_NotFinalToState ); };\n\t\t\"<>~\" => { token( TK_MiddleToState ); };\n\n\t\t# From State actions\n\t\t\">*\" => { token( TK_StartFromState ); };\n\t\t\"$*\" => { token( TK_AllFromState ); };\n\t\t\"%*\" => { token( TK_FinalFromState ); };\n\t\t\"<*\" => { token( TK_NotStartFromState ); };\n\t\t\"@*\" => { token( TK_NotFinalFromState ); };\n\t\t\"<>*\" => { token( TK_MiddleFromState ); };\n\n\t\t# EOF Actions.\n\t\t\">\/\" => { token( TK_StartEOF ); };\n\t\t\"$\/\" => { token( TK_AllEOF ); };\n\t\t\"%\/\" => { token( TK_FinalEOF ); };\n\t\t\"<\/\" => { token( TK_NotStartEOF ); };\n\t\t\"@\/\" => { token( TK_NotFinalEOF ); };\n\t\t\"<>\/\" => { token( TK_MiddleEOF ); };\n\n\t\t# Global Error actions.\n\t\t\">!\" => { token( TK_StartGblError ); };\n\t\t\"$!\" => { token( TK_AllGblError ); };\n\t\t\"%!\" => { token( TK_FinalGblError ); };\n\t\t\" { token( TK_NotStartGblError ); };\n\t\t\"@!\" => { token( TK_NotFinalGblError ); };\n\t\t\"<>!\" => { token( TK_MiddleGblError ); };\n\n\t\t# Local error actions.\n\t\t\">^\" => { token( TK_StartLocalError ); };\n\t\t\"$^\" => { token( TK_AllLocalError ); };\n\t\t\"%^\" => { token( TK_FinalLocalError ); };\n\t\t\"<^\" => { token( TK_NotStartLocalError ); };\n\t\t\"@^\" => { token( TK_NotFinalLocalError ); };\n\t\t\"<>^\" => { token( TK_MiddleLocalError ); };\n\n\t\t# Middle.\n\t\t\"<>\" => { token( TK_Middle ); };\n\n\t\t# Conditions. \n\t\t'>?' => { token( TK_StartCond ); };\n\t\t'$?' => { token( TK_AllCond ); };\n\t\t'%?' => { token( TK_LeavingCond ); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\t\t'->' => { token( TK_Arrow ); };\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\n\t\t\":>\" => { token( TK_ColonGt ); };\n\t\t\":>>\" => { token( TK_ColonGtGt ); };\n\t\t\"<:\" => { token( TK_LtColon ); };\n\n\t\t# Opening of longest match.\n\t\t\"|*\" => { token( TK_BarStar ); };\n\n\t\t'}%%' => { \n\t\t\tupdateCol();\n\t\t\tendSection();\n\t\t\tfgoto main;\n\t\t};\n\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => {\n\t\t\tupdateCol();\n\t\t\tif ( singleLineSpec ) {\n\t\t\t\tendSection();\n\t\t\t\tfgoto main;\n\t\t\t}\n\t\t};\n\n\t\t'{' => { \n\t\t\ttoken( '{' );\n\t\t\tcurly_count = 1; \n\t\t\tinlineBlockType = CurlyDelimited;\n\t\t\tfgoto inline_code;\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated ragel section\" << endl;\n\t\t};\n\n\t\tany => { token( *tokstart ); } ;\n\t*|;\n\n\taction pass {\n\t\tupdateCol();\n\n\t\t\/* If no errors and we are at the bottom of the include stack (the\n\t\t * source file listed on the command line) then write out the data. *\/\n\t\tif ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )\n\t\t\txmlEscapeHost( output, tokstart, tokend-tokstart );\n\t}\n\n\t# Outside code scanner. These tokens get passed through.\n\tmain := |*\n\t\tident => pass;\n\t\tnumber => pass;\n\t\tc_cpp_comment => pass;\n\t\ts_literal | d_literal => pass;\n\t\t'%%{' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = false;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\t'%%' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = true;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\twhitespace+ => pass;\n\t\tEOF;\n\t\tany => pass;\n\t*|;\n\n}%%\n\n%% write data;\n\nvoid Scanner::do_scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[1];\n\tint curly_count = 0;\n\tbool execute = true;\n\tbool singleLineSpec = false;\n\tInlineBlockType inlineBlockType;\n\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart = newbuf + ( tokstart - buf );\n\t\t\ttokend = newbuf + ( tokend - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"scanner error\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = tokstart;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart -= shiftback;\n\t\t\ttokend -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\n\tdelete[] buf;\n}\n\nvoid scan( char *fileName, istream &input, ostream &output )\n{\n\tScanner scanner( fileName, input, output, 0, 0, 0 );\n\tscanner.init();\n\tscanner.do_scan();\n\n\tInputLoc eofLoc;\n\teofLoc.fileName = fileName;\n\teofLoc.col = 1;\n\teofLoc.line = scanner.line;\n}\n","old_contents":"\/*\n * Copyright 2006-2007 Adrian Thurston \n *\/\n\n\/* This file is part of Ragel.\n *\n * Ragel is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Ragel is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Ragel; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"ragel.h\"\n#include \"rlparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n\/* This is used for tracking the current stack of include file\/machine pairs. It is\n * is used to detect and recursive include structure. *\/\nstruct IncludeStackItem\n{\n\tIncludeStackItem( char *fileName, char *sectionName )\n\t\t: fileName(fileName), sectionName(sectionName) {}\n\n\tchar *fileName;\n\tchar *sectionName;\n};\n\ntypedef Vector IncludeStack;\n\nenum InlineBlockType\n{\n\tCurlyDelimited,\n\tSemiTerminated\n};\n\nstruct Scanner\n{\n\tScanner( char *fileName, istream &input, ostream &output,\n\t\t\tParser *inclToParser, char *inclSectionTarg,\n\t\t\tint includeDepth )\n\t: \n\t\tfileName(fileName), input(input), output(output),\n\t\tinclToParser(inclToParser),\n\t\tinclSectionTarg(inclSectionTarg),\n\t\tincludeDepth(includeDepth),\n\t\tline(1), column(1), lastnl(0), \n\t\tparser(0), active(false), \n\t\tparserExistsError(false),\n\t\twhitespaceOn(true)\n\t\t{}\n\n\tbool recursiveInclude( char *inclFileName, char *inclSectionName );\n\n\tchar *prepareFileName( char *fileName, int len )\n\t{\n\t\tbool caseInsensitive;\n\t\tToken tokenFnStr, tokenRes;\n\t\ttokenFnStr.data = fileName;\n\t\ttokenFnStr.length = len;\n\t\ttokenFnStr.prepareLitString( tokenRes, caseInsensitive );\n\t\treturn tokenRes.data;\n\t}\n\n\tvoid init();\n\tvoid token( int type, char *start, char *end );\n\tvoid token( int type, char c );\n\tvoid token( int type );\n\tvoid updateCol();\n\tvoid startSection();\n\tvoid endSection();\n\tvoid do_scan();\n\tbool parserExists();\n\tostream &scan_error();\n\n\tchar *fileName;\n\tistream &input;\n\tostream &output;\n\tParser *inclToParser;\n\tchar *inclSectionTarg;\n\tint includeDepth;\n\n\tint cs;\n\tint line;\n\tchar *word, *lit;\n\tint word_len, lit_len;\n\tInputLoc sectionLoc;\n\tchar *tokstart, *tokend;\n\tint column;\n\tchar *lastnl;\n\n\t\/* Set by machine statements, these persist from section to section\n\t * allowing for unnamed sections. *\/\n\tParser *parser;\n\tbool active;\n\tIncludeStack includeStack;\n\n\t\/* This is set if ragel has already emitted an error stating that\n\t * no section name has been seen and thus no parser exists. *\/\n\tbool parserExistsError;\n\n\t\/* This is for inline code. By default it is on. It goes off for\n\t * statements and values in inline blocks which are parsed. *\/\n\tbool whitespaceOn;\n};\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid Scanner::init( )\n{\n\t%% write init;\n}\n\nbool Scanner::parserExists()\n{\n\tif ( parser != 0 )\n\t\treturn true;\n\n\tif ( ! parserExistsError ) {\n\t\tscan_error() << \"include: there is no previous specification name\" << endl;\n\t\tparserExistsError = true;\n\t}\n\treturn false;\n}\n\nostream &Scanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 &&\n\t\t\t\tstrcmp( si->sectionName, inclSectionName ) == 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\t\n}\n\nvoid Scanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = tokstart;\n\t\/\/cerr << \"adding \" << tokend - from << \" to column\" << endl;\n\tcolumn += tokend - from;\n\tlastnl = 0;\n}\n\nvoid Scanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid Scanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\n%%{\n\tmachine section_parse;\n\n\t# This relies on the the kelbt implementation and the order\n\t# that tokens are declared.\n\tKW_Machine = 128;\n\tKW_Include = 129;\n\tKW_Write = 130;\n\tTK_Word = 131;\n\tTK_Literal = 132;\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_word { word = tokdata; word_len = toklen; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_machine\n\t{\n\t\t\/* Assign a name to the machine. *\/\n\t\tchar *machine = word;\n\n\t\tif ( inclSectionTarg == 0 ) {\n\t\t\tactive = true;\n\n\t\t\tParserDictEl *pdEl = parserDict.find( machine );\n\t\t\tif ( pdEl == 0 ) {\n\t\t\t\tpdEl = new ParserDictEl( machine );\n\t\t\t\tpdEl->value = new Parser( fileName, machine, sectionLoc );\n\t\t\t\tpdEl->value->init();\n\t\t\t\tparserDict.insert( pdEl );\n\t\t\t}\n\n\t\t\tparser = pdEl->value;\n\t\t}\n\t\telse if ( strcmp( inclSectionTarg, machine ) == 0 ) {\n\t\t\t\/* found include target *\/\n\t\t\tactive = true;\n\t\t\tparser = inclToParser;\n\t\t}\n\t\telse {\n\t\t\t\/* ignoring section *\/\n\t\t\tactive = false;\n\t\t\tparser = 0;\n\t\t}\n\t}\n\n\tmachine_stmt =\n\t\t( KW_Machine TK_Word @store_word ';' ) @handle_machine\n\t\t<>err mach_err <>eof mach_err;\n\n\taction handle_include\n\t{\n\t\tif ( active && parserExists() ) {\n\t\t\tchar *inclSectionName = word;\n\t\t\tchar *inclFileName = 0;\n\n\t\t\t\/* Implement defaults for the input file and section name. *\/\n\t\t\tif ( inclSectionName == 0 )\n\t\t\t\tinclSectionName = parser->sectionName;\n\n\t\t\tif ( lit != 0 ) \n\t\t\t\tinclFileName = prepareFileName( lit, lit_len );\n\t\t\telse\n\t\t\t\tinclFileName = fileName;\n\n\t\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t\t * name then check if what we are including is already in the stack. *\/\n\t\t\tincludeStack.append( IncludeStackItem( fileName, parser->sectionName ) );\n\n\t\t\tif ( recursiveInclude( inclFileName, inclSectionName ) )\n\t\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\t\t\telse {\n\t\t\t\t\/* Open the input file for reading. *\/\n\t\t\t\tifstream *inFile = new ifstream( inclFileName );\n\t\t\t\tif ( ! inFile->is_open() ) {\n\t\t\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\t\t\tinclFileName << \" for reading\" << endl;\n\t\t\t\t}\n\n\t\t\t\tScanner scanner( inclFileName, *inFile, output, parser,\n\t\t\t\t\t\tinclSectionName, includeDepth+1 );\n\t\t\t\tscanner.init();\n\t\t\t\tscanner.do_scan( );\n\t\t\t\tdelete inFile;\n\t\t\t}\n\n\t\t\t\/* Remove the last element (len-1) *\/\n\t\t\tincludeStack.remove( -1 );\n\t\t}\n\t}\n\n\tinclude_names = (\n\t\tTK_Word @store_word ( TK_Literal @store_lit )? |\n\t\tTK_Literal @store_lit\n\t) >clear_words;\n\n\tinclude_stmt =\n\t\t( KW_Include include_names ';' ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction write_command\n\t{\n\t\tif ( active && machineSpec == 0 && machineName == 0 ) {\n\t\t\toutput << \"sectionName << \"\\\"\"\n\t\t\t\t\t\" line=\\\"\" << line << \"\\\"\"\n\t\t\t\t\t\" col=\\\"\" << column << \"\\\"\"\n\t\t\t\t\t\">\";\n\t\t}\n\t}\n\n\taction write_arg\n\t{\n\t\tif ( active && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"\" << tokdata << \"<\/arg>\";\n\t}\n\n\taction write_close\n\t{\n\t\tif ( active && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/write>\\n\";\n\t}\n\n\twrite_stmt =\n\t\t( KW_Write @write_command \n\t\t( TK_Word @write_arg )+ ';' @write_close )\n\t\t<>err write_err <>eof write_err;\n\n\taction handle_token\n\t{\n\t\t\/* Send the token off to the parser. *\/\n\t\tif ( active && parserExists() ) {\n\t\t\tInputLoc loc;\n\n\t\t\t#if 0\n\t\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\t\": sending token to the parser \" << lelNames[*p];\n\t\t\tcerr << \" \" << toklen;\n\t\t\tif ( tokdata != 0 )\n\t\t\t\tcerr << \" \" << tokdata;\n\t\t\tcerr << endl;\n\t\t\t#endif\n\n\t\t\tloc.fileName = fileName;\n\t\t\tloc.line = line;\n\t\t\tloc.col = column;\n\n\t\t\tparser->token( loc, type, tokdata, toklen );\n\t\t}\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;\n\n\tmain := ( \n\t\tmachine_stmt |\n\t\tinclude_stmt |\n\t\twrite_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid Scanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n}\n\nvoid Scanner::startSection( )\n{\n\tparserExistsError = false;\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/host>\\n\";\n\t}\n\n\tsectionLoc.fileName = fileName;\n\tsectionLoc.line = line;\n\tsectionLoc.col = 0;\n}\n\nvoid Scanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t%%{\n\t\tmachine section_parse;\n\t\twrite eof;\n\t}%%\n\n\t\/* Close off the section with the parser. *\/\n\tif ( active && parserExists() ) {\n\t\tInputLoc loc;\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = 0;\n\n\t\tparser->token( loc, TK_EndSection, 0, 0 );\n\t}\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 ) {\n\t\t\t\/* The end section may include a newline on the end, so\n\t\t\t * we use the last line, which will count the newline. *\/\n\t\t\toutput << \"\";\n\t\t}\n\t}\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\tc_comment = \n\t\t'\/*' ( any | NL )* :>> '*\/';\n\n\tcpp_comment =\n\t\t'\/\/' [^\\n]* NL;\n\n\tc_cpp_comment = c_comment | cpp_comment;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\t# An inline block of code. This is specified as a scanned, but is sent to\n\t# the parser as one long block. The inline_block pointer is used to handle\n\t# the preservation of the data.\n\tinline_code := |*\n\t\t# Inline expression keywords.\n\t\t\"fpc\" => { token( KW_PChar ); };\n\t\t\"fc\" => { token( KW_Char ); };\n\t\t\"fcurs\" => { token( KW_CurState ); };\n\t\t\"ftargs\" => { token( KW_TargState ); };\n\t\t\"fentry\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Entry );\n\t\t};\n\n\t\t# Inline statement keywords.\n\t\t\"fhold\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Hold );\n\t\t};\n\t\t\"fexec\" => { token( KW_Exec, 0, 0 ); };\n\t\t\"fgoto\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Goto );\n\t\t};\n\t\t\"fnext\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Next );\n\t\t};\n\t\t\"fcall\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Call );\n\t\t};\n\t\t\"fret\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Ret );\n\t\t};\n\t\t\"fbreak\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Break );\n\t\t};\n\n\t\tident => { token( TK_Word, tokstart, tokend ); };\n\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t( s_literal | d_literal ) \n\t\t\t=> { token( IL_Literal, tokstart, tokend ); };\n\n\t\twhitespace+ => { \n\t\t\tif ( whitespaceOn ) \n\t\t\t\ttoken( IL_WhiteSpace, tokstart, tokend );\n\t\t};\n\t\tc_cpp_comment => { token( IL_Comment, tokstart, tokend ); };\n\n\t\t\"::\" => { token( TK_NameSep, tokstart, tokend ); };\n\n\t\t# Some symbols need to go to the parser as with their cardinal value as\n\t\t# the token type (as opposed to being sent as anonymous symbols)\n\t\t# because they are part of the sequences which we interpret. The * ) ;\n\t\t# symbols cause whitespace parsing to come back on. This gets turned\n\t\t# off by some keywords.\n\n\t\t\";\" => {\n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t\tif ( inlineBlockType == SemiTerminated )\n\t\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t[*)] => { \n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t};\n\n\t\t[,(] => { token( *tokstart, tokstart, tokend ); };\n\n\t\t'{' => { \n\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\tcurly_count += 1; \n\t\t};\n\n\t\t'}' => { \n\t\t\tif ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {\n\t\t\t\t\/* Inline code block ends. *\/\n\t\t\t\ttoken( '}' );\n\t\t\t\tfgoto parser_def;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/* Either a semi terminated inline block or only the closing\n\t\t\t\t * brace of some inner scope, not the block's closing brace. *\/\n\t\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\t}\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated code block\" << endl;\n\t\t};\n\n\t\t# Send every other character as a symbol.\n\t\tany => { token( IL_Symbol, tokstart, tokend ); };\n\t*|;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( RE_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( RE_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( RE_Char, tokstart, tokend ); };\n\n\t*|;\n\n\tre_literal := |*\n\t\t# Escape sequences in regular expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Terminate an OR expression.\n\t\t'\/' [i]? => { \n\t\t\ttoken( RE_Slash, tokstart, tokend ); \n\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t# Special characters.\n\t\t'.' => { token( RE_Dot ); };\n\t\t'*' => { token( RE_Star ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated regular expression\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\\/] => { token( RE_Char, tokstart, tokend ); };\n\t*|;\n\n\t# We need a separate token space here to avoid the ragel keywords.\n\twrite_statement := |*\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\t\t[ \\t\\n]+ => { updateCol(); };\n\t\t';' => { token( ';' ); fgoto parser_def; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated write statement\" << endl;\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tparser_def := |*\n\t\t'machine' => { token( KW_Machine ); };\n\t\t'include' => { token( KW_Include ); };\n\t\t'write' => { \n\t\t\ttoken( KW_Write );\n\t\t\tfgoto write_statement;\n\t\t};\n\t\t'action' => { token( KW_Action ); };\n\t\t'alphtype' => { token( KW_AlphType ); };\n\n\t\t# FIXME: Enable this post 5.17.\n\t\t# 'range' => { token( KW_Range ); };\n\n\t\t'getkey' => { \n\t\t\ttoken( KW_GetKey );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'access' => { \n\t\t\ttoken( KW_Access );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'variable' => { \n\t\t\ttoken( KW_Variable );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'when' => { token( KW_When ); };\n\t\t'eof' => { token( KW_Eof ); };\n\t\t'err' => { token( KW_Err ); };\n\t\t'lerr' => { token( KW_Lerr ); };\n\t\t'to' => { token( KW_To ); };\n\t\t'from' => { token( KW_From ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, tokstart, tokend ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( RE_Slash ); fgoto re_literal; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t':=' => { token( TK_ColonEquals ); };\n\n\t\t# To State Actions.\n\t\t\">~\" => { token( TK_StartToState ); };\n\t\t\"$~\" => { token( TK_AllToState ); };\n\t\t\"%~\" => { token( TK_FinalToState ); };\n\t\t\"<~\" => { token( TK_NotStartToState ); };\n\t\t\"@~\" => { token( TK_NotFinalToState ); };\n\t\t\"<>~\" => { token( TK_MiddleToState ); };\n\n\t\t# From State actions\n\t\t\">*\" => { token( TK_StartFromState ); };\n\t\t\"$*\" => { token( TK_AllFromState ); };\n\t\t\"%*\" => { token( TK_FinalFromState ); };\n\t\t\"<*\" => { token( TK_NotStartFromState ); };\n\t\t\"@*\" => { token( TK_NotFinalFromState ); };\n\t\t\"<>*\" => { token( TK_MiddleFromState ); };\n\n\t\t# EOF Actions.\n\t\t\">\/\" => { token( TK_StartEOF ); };\n\t\t\"$\/\" => { token( TK_AllEOF ); };\n\t\t\"%\/\" => { token( TK_FinalEOF ); };\n\t\t\"<\/\" => { token( TK_NotStartEOF ); };\n\t\t\"@\/\" => { token( TK_NotFinalEOF ); };\n\t\t\"<>\/\" => { token( TK_MiddleEOF ); };\n\n\t\t# Global Error actions.\n\t\t\">!\" => { token( TK_StartGblError ); };\n\t\t\"$!\" => { token( TK_AllGblError ); };\n\t\t\"%!\" => { token( TK_FinalGblError ); };\n\t\t\" { token( TK_NotStartGblError ); };\n\t\t\"@!\" => { token( TK_NotFinalGblError ); };\n\t\t\"<>!\" => { token( TK_MiddleGblError ); };\n\n\t\t# Local error actions.\n\t\t\">^\" => { token( TK_StartLocalError ); };\n\t\t\"$^\" => { token( TK_AllLocalError ); };\n\t\t\"%^\" => { token( TK_FinalLocalError ); };\n\t\t\"<^\" => { token( TK_NotStartLocalError ); };\n\t\t\"@^\" => { token( TK_NotFinalLocalError ); };\n\t\t\"<>^\" => { token( TK_MiddleLocalError ); };\n\n\t\t# Middle.\n\t\t\"<>\" => { token( TK_Middle ); };\n\n\t\t# Conditions. \n\t\t'>?' => { token( TK_StartCond ); };\n\t\t'$?' => { token( TK_AllCond ); };\n\t\t'%?' => { token( TK_LeavingCond ); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\t\t'->' => { token( TK_Arrow ); };\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\n\t\t\":>\" => { token( TK_ColonGt ); };\n\t\t\":>>\" => { token( TK_ColonGtGt ); };\n\t\t\"<:\" => { token( TK_LtColon ); };\n\n\t\t# Opening of longest match.\n\t\t\"|*\" => { token( TK_BarStar ); };\n\n\t\t'}%%' => { \n\t\t\tupdateCol();\n\t\t\tendSection();\n\t\t\tfgoto main;\n\t\t};\n\n\t\t[ \\t]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => {\n\t\t\tupdateCol();\n\t\t\tif ( singleLineSpec ) {\n\t\t\t\tendSection();\n\t\t\t\tfgoto main;\n\t\t\t}\n\t\t};\n\n\t\t'{' => { \n\t\t\ttoken( '{' );\n\t\t\tcurly_count = 1; \n\t\t\tinlineBlockType = CurlyDelimited;\n\t\t\tfgoto inline_code;\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated ragel section\" << endl;\n\t\t};\n\n\t\tany => { token( *tokstart ); } ;\n\t*|;\n\n\taction pass {\n\t\tupdateCol();\n\n\t\t\/* If no errors and we are at the bottom of the include stack (the\n\t\t * source file listed on the command line) then write out the data. *\/\n\t\tif ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )\n\t\t\txmlEscapeHost( output, tokstart, tokend-tokstart );\n\t}\n\n\t# Outside code scanner. These tokens get passed through.\n\tmain := |*\n\t\tident => pass;\n\t\tnumber => pass;\n\t\tc_cpp_comment => pass;\n\t\ts_literal | d_literal => pass;\n\t\t'%%{' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = false;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\t'%%' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = true;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\twhitespace+ => pass;\n\t\tEOF;\n\t\tany => pass;\n\t*|;\n\n}%%\n\n%% write data;\n\nvoid Scanner::do_scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[1];\n\tint curly_count = 0;\n\tbool execute = true;\n\tbool singleLineSpec = false;\n\tInlineBlockType inlineBlockType;\n\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart = newbuf + ( tokstart - buf );\n\t\t\ttokend = newbuf + ( tokend - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"scanner error\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = tokstart;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart -= shiftback;\n\t\t\ttokend -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\n\tdelete[] buf;\n}\n\nvoid scan( char *fileName, istream &input, ostream &output )\n{\n\tScanner scanner( fileName, input, output, 0, 0, 0 );\n\tscanner.init();\n\tscanner.do_scan();\n\n\tInputLoc eofLoc;\n\teofLoc.fileName = fileName;\n\teofLoc.col = 1;\n\teofLoc.line = scanner.line;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f33ff596a04bf6113a1668fd04eabb2b889b904a","subject":"refactor","message":"refactor\n","repos":"razum2um\/params_tree","old_file":"hello_world.rl","new_file":"hello_world.rl","new_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { inject_key }\n action push { push }\n action pop { pop }\n\n DELIMITER = ',' >H@T @{ log(:delimiter) };\n LEVEL = '('+ >H@T @{ log(:level) };\n END_LEVEL = ')'+ >H@T @{ log(:end_level); };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER? @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n puts key\n puts @hash.inspect\n puts @hash_stack.inspect\n\n @hash_stack.first\n end\n\n def chars\n @data[@head..@tail]\n end\n\n def strokes\n chars.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = chars\n end\n\n def key\n @key.pack('c*')\n end\n\n def inject_key\n @hash[key] = {}\n end\n\n def push\n @hash_stack.push @hash; @hash = @hash[key]\n end\n\n def pop\n @hash = @hash_stack.pop\n end\n end\nend\n\n#s = \"default(all,usadasdid(zczxc(pio(xqwe)),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\ns = \"default,all\"\nputs s\nputs ParamsTree::Parser.new.process s\n","old_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ',' >H@T @{ log(:delimiter) };\n LEVEL = '('+ >H@T @{ log(:level) };\n END_LEVEL = ')'+ >H@T @{ log(:end_level); };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER? @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n #@hash.inspect\n #@hash_stack.inspect\n @hash_stack.first\n end\n\n def chars\n @data[@head..@tail]\n end\n\n def strokes\n chars.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = chars\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\ns = \"default(all,usadasdid(zczxc(pio(xqwe)),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\nputs s\nputs ParamsTree::Parser.new.process s\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"13b2a64c89b20d3a53c5ff34ef9a87f04a91c652","subject":"There's an accepted definition for \"XML character data\" out there. This commit uses it.","message":"There's an accepted definition for \"XML character data\" out there. This commit uses it.\n\nThe XML CharData definition makes provisions for XML CDATA, which these\nparsers technically don't interpret. I've yet to see CDATA used by any\nCAS server, so I'm not going to worry about it too much, but Castanet\nought to be able to handle CDATA since there's nothing stopping a CAS\nserver from using it in its responses.\n","repos":"NUBIC\/castanet","old_file":"lib\/castanet\/responses\/common.rl","new_file":"lib\/castanet\/responses\/common.rl","new_contents":"%%{\n machine common;\n\n # Needed to support XML's character set, i.e. Unicode minus surrogate blocks.\n # See http:\/\/www.w3.org\/TR\/REC-xml\/#charsets.\n alphtype int;\n\n # XML definitions\n # ---------------\n\n quote = '\"' | \"'\";\n\n # See http:\/\/www.w3.org\/TR\/REC-xml\/#syntax.\n char_data = [^<&]* - ([^<&]* \"]]>\" [^<&]*);\n\n # CAS definitions\n # ---------------\n \n # Section 3.7\n ticket_character = 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '-';\n}%%\n","old_contents":"%%{\n machine common;\n\n # Needed to support XML's character set, i.e. Unicode minus surrogate blocks.\n # See http:\/\/www.w3.org\/TR\/REC-xml\/#charsets.\n alphtype int;\n\n # XML definitions\n # ---------------\n quote = '\"' | \"'\";\n xml_content = any -- [<&];\n\n # CAS definitions\n # ---------------\n \n # Section 3.7\n ticket_character = 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '-';\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"0f226cd405ce5c8c8fd2d8e3715967355eed9304","subject":"* working snapshot","message":"* working snapshot\n","repos":"nineties\/amber","old_file":"rlc1\/typing.rl","new_file":"rlc1\/typing.rl","new_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: typing.rl 2010-04-29 22:46:33 nineties $\n %);\n\ninclude(stddef, code);\n\nexport(init_typing, typing, unit_type, char_type, int_type, float_type, double_type, void_type);\nexport(get_variable);\n\nscopeid: 0;\nscopeid_stack: NULL; \n\nvarmap: NULL; (% variable table. name -> (tyscheme, id, is_global) %);\n\n(% p0: (scopeid-id, name) %);\nident_hash: (p0) {\n return strhash(p0[1]) * 3+ p0[0];\n};\n\nident_equal: (p0, p1) {\n if (p0[0] != p1[0]) { return FALSE; };\n return streq(p0[1], p1[1]);\n};\n\nscope_push: () {\n scopeid = scopeid + 1;\n vec_pushback(scopeid_stack, scopeid);\n};\n\nscope_pop: () {\n vec_popback(scopeid_stack);\n};\n\n(% p0: name, p1: value %);\nvarmap_add: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(varmap, mktup2(x0, p0), p1);\n};\n\n(% p0: name %);\nvarmap_find: (p0) {\n allocate(3);\n x0 = vec_size(scopeid_stack)-1;\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(varmap, mktup2(x1, p0));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return NULL;\n};\n\nfuntable: NULL; (% function table. name -> list of tyscheme %);\n\n(% p0: name, p1: value %);\nfunction_add: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(funtable, mktup2(x0, p0), p1);\n};\n\n(% p0: name %);\nfunction_find: (p0) {\n allocate(3);\n x0 = vec_size(scopeid_stack)-1;\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(funtable, mktup2(x1, p0));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return NULL;\n};\n\n(% p0: name %);\nget_variable: (p0) {\n allocate(1);\n x0 = varmap_find(p0); (% tyscheme, id, is_global %);\n if (x0 == NULL) {\n fputs(stderr, \"ERROR: variable '\");\n fputs(stderr, p0);\n fputs(stderr, \"' is not declared\\n\");\n exit(1);\n };\n return mktup6(NODE_IDENTIFIER, x0[0][1], p0, x0[1], x0[0], x0[2]);\n};\n\n\nin_global_namespace: () {\n return vec_size(scopeid_stack) == 1;\n};\n\ntyvarmap: NULL;\n\ntyvarid_hash: (p0) {\n return p0;\n};\n\ntyvarid_equal: (p0, p1) {\n return p0 == p1;\n};\n\ninit_tyvarmap: () {\n tyvarmap = mkmap(&tyvarid_hash, &tyvarid_equal, 10);\n};\n\n(% constructor name -> (variant type, corresponding row) %);\nvariant_map: NULL;\n\nnot_reachable: (p0) {\n fputs(stderr, \"ERROR: not reachable here\\n\");\n exit(1);\n};\n\nnot_implemented: (p0) {\n fputs(stderr, \"ERROR: not implemented\\n\");\n exit(1);\n};\n\ninfer_funcs: [not_reachable, infer_integer, infer_string, not_implemented,\n infer_identifier, infer_array, infer_tuple, infer_block, infer_decl,\n infer_call, infer_subscript, infer_lambda, infer_unexpr, infer_binexpr,\n infer_assign, infer_export, infer_import, infer_external, infer_ret, infer_retval,\n infer_syscall, infer_field, infer_fieldref, infer_typedecl, infer_variant, infer_unit,\n infer_typedexpr, infer_if, infer_ifelse, infer_static_array, infer_cast, infer_new,\n infer_while, infer_for, infer_newarray, infer_rewrite\n];\n\nunit_type : NULL;\nchar_type : NULL;\nint_type : NULL;\nfloat_type : NULL;\ndouble_type : NULL;\nvoid_type : NULL;\n\ninit_typing: () {\n unit_type = mktup1(NODE_UNIT_T);\n char_type = mktup1(NODE_CHAR_T);\n int_type = mktup1(NODE_INT_T);\n float_type = mktup1(NODE_FLOAT_T);\n double_type = mktup1(NODE_DOUBLE_T);\n void_type = mktup1(NODE_VOID_T);\n};\n\ninfer_integer: (p0) {\n if (p0[2] == 8) { p0[1] = char_type; return char_type; };\n if (p0[2] == 32) { p0[1] = int_type; return int_type; };\n not_reachable();\n};\n\ninfer_string: (p0) {\n p0[1] = mktup3(NODE_NAMED_T, \"string\", NULL);\n return p0[1];\n};\n\ninfer_identifier: (p0) {\n allocate(3);\n x0 = varmap_find(p0[2]); (% (tyscheme, id, is_global) %);\n if (x0 == NULL) {\n fputs(stderr, \"ERROR: undefined symbol '\");\n fputs(stderr, p0[2]);\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n\n x1 = rename_tyscheme(x0[0]);\n p0[1] = x1[1];\n p0[3] = x0[1];\n p0[4] = x1;\n p0[5] = x0[2];\n\n deref(p0);\n\n return p0[1];\n};\n\ninfer_array: (p0) {\n allocate(5);\n x0 = mktyvar();\n x1 = p0[2]; (% length %);\n x2 = 0;\n x3 = p0[3]; (% pointer to the array %);\n while (x2 < x1) {\n x4 = x3[x2];\n x4[1] = infer_item(x3[x2]);\n unify(x0, x4[1], TRUE);\n x2 = x2 + 1;\n };\n not_implemented();\n p0[1] = mktup4(NODE_ARRAY_T, x0, x1, FALSE);\n deref(p0);\n return p0[1];\n};\n\ninfer_tuple: (p0) {\n allocate(5);\n x1 = p0[2]; (% length %);\n x2 = p0[3];\n x3 = memalloc(4*x1);\n x0 = 0;\n while (x0 < x1) {\n x4 = x2[x0];\n x4[1] = infer_item((p0[3])[x0]);\n x3[x0] = x4[1];\n x0 = x0 + 1;\n };\n p0[1] = mktup3(NODE_TUPLE_T, x1, x3);\n deref(p0);\n return p0[1];\n};\n\ndo_exit: (p0) {\n if (p0[0] == NODE_RETVAL) { return TRUE; };\n if (p0[0] == NODE_RET) { return TRUE; };\n if (p0[1][0] == NODE_VOID_T) { return TRUE; };\n return FALSE;\n};\n\n(% p0: instruction %);\nblock_type: (p0) {\n if (p0[0] == NODE_RET) { return void_type; };\n if (p0[0] == NODE_RETVAL) { return void_type; };\n if (p0[1][0] == NODE_VOID_T) {\n return void_type;\n };\n return unit_type;\n};\n\nreturn_stack: NULL;\n\ninfer_block: (p0) {\n allocate(3);\n x0 = p0[BLOCK_STATEMENTS];\n\n if (x0 != NULL) {\n while (x0 != NULL) {\n x1 = ls_value(x0);\n x2 = infer_item(x1);\n if (ls_next(x0) != NULL) {\n if (do_exit(ls_value(x0))) {\n fputs(stderr, \"ERROR: unreachable code '\");\n put_item(stderr, ls_value(ls_next(x0)));\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n } else {\n p0[1] = block_type(x1);\n };\n x0 = ls_next(x0);\n };\n } else {\n (% empty function body %);\n p0[1] = unit_type;\n };\n\n deref(p0);\n return p0[1];\n};\n\n(% p0: dontcare pattern, p1: expr %);\ninfer_decl_dontcare: (p0, p1) {\n p0[1] = infer_item(p1);\n return p0[1];\n};\n\n(% p0: var, p1: expr %);\ninfer_decl_var: (p0, p1) {\n allocate(5);\n x0 = mktyvar();\n x1 = set_varid(p0);\n x2 = in_global_namespace();\n varmap_add(p0[2], mktup3(mktyscheme(x0), x1, x2));\n x3 = infer_item(p1);\n unify(x0, x3, TRUE);\n x4 = closure(x3);\n varmap_add(p0[2], mktup3(x4, x1, x2));\n p0[1] = x3; (% type %);\n p0[3] = x1; (% variable id %);\n p0[4] = x4; (% type scheme %);\n p0[5] = x2;\n deref_pattern(p0);\n deref(p1);\n return p0[1];\n};\n\n(% p0: tuple pattern, p1: expr %);\ninfer_decl_tuple: (p0, p1) {\n allocate(1);\n x0 = infer_pattern(p0);\n unify(x0, infer_item(p1), TRUE);\n deref_pattern(p0);\n deref(p1);\n return p0[1];\n};\n\ninfer_pattern: (p0) {\n allocate(5);\n if (p0[0] == NODE_UNIT) {\n p0[1] = unit_type;\n return unit_type;\n };\n if (p0[0] == NODE_DONTCARE) {\n x0 = mktyvar();\n p0[1] = x0;\n return x0;\n };\n if (p0[0] == NODE_IDENTIFIER) {\n (% variable pattern %);\n x0 = mktyvar(); (% type of variable %);\n x1 = set_varid(p0);\n x2 = mktup3(mktyscheme(x0), x1, in_global_namespace());\n varmap_add(p0[2], x2);\n p0[1] = x0;\n p0[3] = x1;\n p0[4] = x2;\n deref(p0);\n return p0[1];\n };\n if (p0[0] == NODE_TUPLE) {\n (% tuple pattern %);\n x0 = p0[TUPLE_LENGTH];\n x1 = p0[TUPLE_ELEMENTS];\n x2 = memalloc(4*x0); (% element types %);\n x3 = 0;\n while (x3 < x0) {\n x4 = infer_pattern(x1[x3]);\n x2[x3] = x4;\n x3 = x3 + 1;\n };\n p0[1] = mktup3(NODE_TUPLE_T, x0, x2);\n return p0[1];\n };\n if (p0[0] == NODE_TYPEDEXPR) {\n (% typed pattern %);\n x0 = infer_pattern(p0[2]);\n unify(x0, p0[1], TRUE);\n deref(p0);\n return p0[1];\n };\n fputs(stderr, \"ERROR: invalid pattern expression\\n\");\n exit(1);\n};\n\n(% p0: lhs, p1: rhs %);\ninfer_decl_impl: (p0, p1) {\n if (p0[0] == NODE_DONTCARE) {\n return infer_decl_dontcare(p0, p1);\n };\n if (p0[0] == NODE_IDENTIFIER) {\n return infer_decl_var(p0, p1);\n };\n if (p0[0] == NODE_TUPLE) {\n return infer_decl_tuple(p0, p1);\n };\n not_implemented();\n};\n\ninfer_decl: (p0) {\n allocate(1);\n x0 = infer_decl_impl(p0[2], p0[3]);\n p0[1] = x0;\n deref(p0);\n return p0[1];\n};\n\n\n(% p0: expr %);\ninfer_call: (p0) {\n allocate(3);\n x0 = infer_item(p0[2]); (% function type %);\n x1 = infer_item(p0[3]); (% argument type %);\n x2 = mktyvar(); (% return type %);\n unify(x0, mktup3(NODE_LAMBDA_T, x1, x2), TRUE);\n\n p0[1] = x2;\n deref(p0);\n return p0[1];\n};\n\ninfer_subscript: (p0) {\n allocate(2);\n x0 = infer_item(p0[2]);\n x1 = infer_item(p0[3]);\n unify(int_type, x1, TRUE);\n if (x0[0] == NODE_SARRAY_T) {\n\tp0[1] = x0[1];\n\tderef(p0);\n\treturn p0[1];\n };\n if (x0[0] == NODE_ARRAY_T) {\n p0[1] = x0[1];\n deref(p0);\n return p0[1];\n };\n not_implemented();\n};\n\ninsert_missing_ret: (p0) {\n allocate(1);\n if (p0 == NULL) {\n return ls_singleton(mktup2(NODE_RET, unit_type));\n };\n x0 = ls_value(p0);\n if (x0[0] == NODE_RET) { return p0; };\n if (x0[0] == NODE_RETVAL) { return p0; };\n if (x0[1] == void_type) { return p0; };\n return ls_cons(x0, insert_missing_ret(ls_next(p0)));\n};\n\ninfer_lambda: (p0) {\n allocate(3);\n\n (% lambda opens new namespace %);\n scope_push();\n x0 = infer_pattern(p0[LAMBDA_ARG]);\n\n vec_pushback(return_stack, NULL);\n x1 = infer_item(p0[LAMBDA_BODY]);\n x2 = vec_at(return_stack, vec_size(return_stack)-1);\n if (x2 != NULL) {\n x1 = x2;\n };\n vec_popback(return_stack);\n scope_pop();\n\n p0[1] = mktup3(NODE_LAMBDA_T, x0, x1);\n\n if (p0[1] != void_type) {\n x2 = p0[LAMBDA_BODY];\n x2[2] = insert_missing_ret(x2[2]);\n };\n\n deref(p0);\n return p0[1];\n};\n\nunexpr_funcs: [\n infer_unarith, infer_unarith, infer_unarith, infer_unarith, not_implemented,\n infer_indirect, infer_unarith, infer_unarith, infer_unarith, infer_unarith\n];\n\ninfer_unarith: (p0) {\n allocate(1);\n x0 = infer_item(p0[3]);\n unify(int_type, x0, TRUE);\n p0[1] = int_type;\n return int_type;\n};\n\ninfer_indirect: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]);\n x1 = mktyvar();\n unify(mktup2(NODE_POINTER_T, x1), x0, TRUE);\n p0[1] = x1;\n deref(p0);\n return p0[1];\n};\n\ninfer_unexpr: (p0) {\n allocate(1);\n x0 = unexpr_funcs[p0[2]];\n return x0(p0);\n};\n\nbinexpr_funcs: [\n not_reachable, infer_binarith, infer_binarith, infer_binarith, infer_binarith,\n infer_binarith, infer_binarith, infer_binarith, infer_binarith, infer_binarith,\n infer_binarith, infer_equality, infer_equality, infer_binarith, infer_binarith,\n infer_binarith, infer_binarith, not_implemented, not_implemented\n];\n\ninfer_binarith: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]);\n x1 = infer_item(p0[4]);\n unify(int_type, x0, TRUE);\n unify(int_type, x1, TRUE);\n p0[1] = int_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_equality: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]);\n x1 = infer_item(p0[4]);\n unify(x0, x1, TRUE);\n p0[1] = int_type;\n deref(p0);\n return int_type;\n};\n\ninfer_binexpr: (p0) {\n allocate(1);\n x0 = binexpr_funcs[p0[2]];\n return x0(p0);\n};\n\ninfer_assign: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]); (% lhs type %);\n x1 = infer_item(p0[4]); (% rhs type %);\n unify(x0, x1, TRUE);\n p0[1] = x0;\n return x0;\n};\n\ninfer_export: (p0) {\n infer_item(p0[1]);\n deref(p0);\n return unit_type;\n};\n\ninfer_import: (p0) {\n (% do nothing %);\n};\n\ninfer_external: (p0) {\n allocate(5);\n x0 = p0[1]; (% ident %);\n x1 = p0[2]; (% type %);\n x2 = closure(x1);\n x3 = set_varid(x0);\n varmap_add(get_ident_name(x0), mktup3(x2, x3, TRUE));\n x0[1] = x1;\n x0[3] = x3;\n x0[4] = x2;\n x0[5] = TRUE;\n return unit_type;\n};\n\ninfer_ret: (p0) {\n allocate(1);\n x0 = vec_back(return_stack);\n if (x0 != NULL) {\n unify(x0, unit_type, TRUE);\n };\n vec_put(return_stack, vec_size(return_stack)-1, unit_type);\n p0[1] = unit_type;\n deref(p0);\n return unit_type;\n};\n\n(% return e; is treated as .pseudo_retvar = e; %);\ninfer_retval: (p0) {\n allocate(1);\n p0[1] = infer_item(p0[RETVAL_VALUE]);\n x0 = vec_back(return_stack);\n if (x0 != NULL) {\n unify(p0[1], x0, TRUE);\n };\n deref(p0);\n vec_put(return_stack, vec_size(return_stack)-1, p0[1]);\n return p0[1];\n};\n\ninfer_syscall: (p0) {\n infer_item(p0[2]);\n p0[1] = mktyvar();\n deref(p0);\n return p0[1];\n};\n\n(% fieldname : expression %);\ninfer_field: (p0) {\n allocate(3);\n x0 = p0[2]; (% lhs %);\n if (x0[0] != NODE_IDENTIFIER) {\n fputs(stderr, \"ERROR: invalid field name\\n\");\n exit(1);\n };\n x1 = infer_item(p0[3]);\n x2 = mktup3(NODE_FIELD_T, get_ident_name(x0), x1);\n p0[1] = x2;\n deref(p0);\n return p0[1];\n};\n\n(% p0: type, p1: field name %);\nget_fieldtype: (p0, p1) {\n allocate(4);\n if (p0[0] == NODE_TUPLE_T) {\n x0 = p0[TUPLE_T_LENGTH];\n x1 = p0[TUPLE_T_ELEMENTS];\n x2 = 0;\n while (x2 < x0) {\n x3 = x1[x2];\n if (has_name(x3, p1)) {\n return x3[2];\n };\n x2 = x2 + 1;\n };\n return NULL;\n };\n if (p0[0] == NODE_VARIANT_T) {\n x0 = p0[2]; (% rows %);\n if (ls_length(x0) != 1) {\n return NULL;\n };\n x1 = (ls_value(x0))[2]; (% argument type %);\n return get_fieldtype(x1, p1);\n };\n if (p0[0] == NODE_NAMED_T) {\n if (p0[2] != NULL) {\n return get_fieldtype(p0[2], p1);\n };\n return NULL;\n };\n return NULL;\n};\n\ninfer_fieldref: (p0) {\n allocate(3);\n x0 = infer_item(p0[2]); (% lhs %);\n x1 = p0[3]; (% field name %);\n x2 = get_fieldtype(x0, x1);\n if (x2 == NULL) {\n fputs(stderr, \"ERROR: field '\");\n fputs(stderr, x1);\n fputs(stderr, \"' not found\\n\");\n exit(1);\n };\n p0[1] = x2;\n deref(p0);\n return p0[1];\n};\n\ninfer_typedecl: (p0) {\n allocate(5);\n x0 = p0[1]; (% identifier %);\n x1 = p0[2][2]; (% type %);\n if (x1 == NULL) {\n\treturn unit_type;\n };\n if (x1[0] == NODE_VARIANT_T) {\n x1[1] = x0;\n x2 = x1[2]; (% rows %);\n x3 = 0; (% constructor id %);\n\n (% set constructor-id and register to variant_map %);\n while (x2 != NULL) {\n x4 = ls_value(x2); (% constructor name, id, arg %);\n x4[1] = x3;\n map_add(variant_map, x4[0], mktup2(x1, x4));\n x2 = ls_next(x2);\n x3 = x3 + 1;\n };\n return unit_type;\n };\n return unit_type;\n};\n\ninfer_variant: (p0) {\n allocate(3);\n x0 = p0[2]; (% constructor name %);\n x1 = map_find(variant_map, x0); (% (type, (constructor name, id, arg type)) %);\n assert(x1 != NULL);\n p0[1] = x1[0];\n p0[3] = x1[1][1]; (% id %);\n if (p0[4] != NULL) {\n x2 = infer_item(p0[4]); (% infer argument %);\n unify(x2, x1[1][2], TRUE);\n };\n deref(p0);\n return p0[1];\n};\n\ninfer_unit: (p0) {\n p0[1] = unit_type;\n return unit_type;\n};\n\ninfer_typedexpr: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]); (% expression %);\n unify(x0, p0[1], TRUE);\n deref(p0);\n return p0[1];\n};\n\ninfer_if: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]); (% condition %);\n unify(x0, int_type, TRUE);\n infer_item(p0[3]);\n p0[1] = unit_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_ifelse: (p0) {\n allocate(3);\n x0 = infer_item(p0[2]); (% condition %);\n unify(int_type, x0, TRUE);\n x1 = infer_item(p0[3]); (% ifthen block %);\n x2 = infer_item(p0[4]); (% ifelse block %);\n p0[1] = unify_join(x1, x2, TRUE);\n deref(p0);\n return p0[1];\n};\n\ninfer_static_array: (p0) {\n allocate(4);\n x0 = infer_item(p0[2]); (% initializer %);\n x1 = infer_item(p0[3]); (% length %);\n unify(x1, int_type, TRUE);\n p0[1] = mktup2(NODE_SARRAY_T, x0);\n deref(p0);\n return p0[1];\n};\n\ninfer_cast: (p0) {\n infer_item(p0[2]);\n deref(p0);\n return p0[1];\n};\n\ninfer_new: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]);\n p0[1] = mktup2(NODE_POINTER_T, x0);\n deref(p0);\n return p0[1];\n};\n\ninfer_while: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]); (% condition %);\n unify(int_type, x0, TRUE);\n infer_item(p0[3]);\n p0[1] = unit_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_for: (p0) {\n allocate(1);\n infer_item(p0[2]);\n x0 = infer_item(p0[3]); (% condition %);\n unify(int_type, x0, TRUE);\n infer_item(p0[4]);\n infer_item(p0[5]);\n p0[1] = unit_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_newarray: (p0) {\n allocate(2);\n x0 = infer_item(p0[2]); (% length %);\n unify(int_type, x0, TRUE);\n x1 = infer_item(p0[3]);\n p0[1] = mktup2(NODE_ARRAY_T, x1);\n deref(p0);\n return p0[1];\n};\n\ninfer_rewrite: (p0) {\n return unit_type;\n};\n\n(% p0: item %);\ninfer_item: (p0) {\n allocate(1);\n x0 = infer_funcs[p0[0]];\n return x0(p0);\n};\n\nremove_freevar: (p0) {\n allocate(1);\n if (p0 == NULL) { return NULL; };\n x0 = map_find(tyvarmap, ls_value(p0));\n if (x0 != NULL) {\n p0[1] = remove_freevar(ls_next(p0));\n return p0;\n };\n return remove_freevar(ls_next(p0));\n};\n\n(% p0: type %);\nclosure: (p0) {\n allocate(1);\n x0 = freevar(p0);\n x0 = remove_freevar(x0);\n return mktup2(x0, p0);\n};\n\n\n(% p0, p1: type, p2: do update tyvarmap %);\nunify: (p0, p1, p2) {\n if (p0[0] == NODE_TYVAR) { return unify_tyvar(p0, p1, p2); };\n if (p1[0] == NODE_TYVAR) { return unify_tyvar(p1, p0, p2); };\n if (p0[0] == p1[0]) {\n if (p0[0] == NODE_UNIT_T) { return TRUE; };\n if (p0[0] == NODE_CHAR_T) { return TRUE; };\n if (p0[0] == NODE_INT_T) { return TRUE; };\n if (p0[0] == NODE_FLOAT_T) { return TRUE; };\n if (p0[0] == NODE_DOUBLE_T) { return TRUE; };\n if (p0[0] == NODE_POINTER_T) { return unify(p0[POINTER_T_BASE], p1[POINTER_T_BASE], p2); };\n if (p0[0] == NODE_TUPLE_T) { return unify_tuple_t(p0, p1, p2); };\n if (p0[0] == NODE_ARRAY_T) {\n unify(p0[ARRAY_T_ELEMENT], p1[ARRAY_T_ELEMENT], p2);\n return TRUE;\n };\n if (p0[0] == NODE_LAMBDA_T) { return unify_lambda_t(p0, p1, p2); };\n if (p0[0] == NODE_VARIANT_T) {\n if (streq(p0[1], p1[1])) { return TRUE; };\n };\n\tif (p0[0] == NODE_NAMED_T) {\n\t if (streq(p0[1], p1[1])) { return TRUE; };\n\t};\n };\n if (p0[0] == NODE_NAMED_T) {\n\tif (p0[2] != NULL) {\n\t return unify(p0[2], p1, p2);\n\t};\n };\n if (p1[0] == NODE_NAMED_T) {\n\tif (p1[2] != NULL) {\n\t return unify(p0, p1[2], p2);\n\t};\n };\n if (p0[0] == NODE_FIELD_T) {\n return unify(p0[2], p1, p2);\n };\n if (p1[0] == NODE_FIELD_T) {\n return unify(p0, p1[2], p2);\n };\n if (p2) {\n type_mismatch(p0, p1);\n };\n return FALSE;\n};\n\nunify_tuple_t: (p0, p1, p2) {\n allocate(2);\n if (p0[1] != p1[1]) {\n if (p2) {\n type_mismatch(p0, p1);\n };\n return FALSE;\n };\n x1 = p0[1]; (% length %);\n x0 = 0;\n while (x0 < x1) {\n if (unify((p0[2])[x0], (p1[2])[x0], p2) == FALSE) {\n return FALSE;\n };\n x0 = x0 + 1;\n };\n return TRUE;\n};\n\nunify_lambda_t: (p0, p1, p2) {\n if(unify(p0[1], p1[1], p2) == FALSE) {\n return FALSE;\n };\n return unify(p0[2], p1[2], p2);\n};\n\n(% p0: tyvar, p1, type %);\nunify_tyvar: (p0, p1, p2) {\n allocate(1);\n if (p1[0] == NODE_TYVAR) {\n if (p0[1] == p1[1]) { return TRUE; };\n };\n x0 = map_find(tyvarmap, p0[1]);\n if (x0 != NULL) {\n return unify(x0[1], p1, p2);\n };\n if (p1[0] == NODE_TYVAR) {\n x0 = map_find(tyvarmap, p1[1]);\n if (x0 != NULL) {\n return unify(p0, x0[1], p2);\n };\n };\n occur_check(p0[1], p1);\n if (p2) {\n x0 = closure(p1);\n map_add(tyvarmap, p0[1], x0);\n };\n};\n\n(% p0: type of ifthen block, p1: type of ifelse block %);\nunify_join: (p0, p1) {\n if (p0 == void_type) { return p1; };\n if (p1 == void_type) { return p0; };\n return unit_type;\n};\n\n(% p0: id, p1, type %);\noccur_check: (p0, p1) {\n allocate(1);\n if (p1[0] == NODE_TUPLE_T) { return occur_check_tuple_t(p0, p1); };\n if (p1[0] == NODE_ARRAY_T) { return occur_check(p0, p1[1]); };\n if (p1[0] == NODE_LAMBDA_T) { return occur_check_lambda_t(p0, p1); };\n if (p1[0] == NODE_TYVAR) {\n if (p0 == p1[1]) {\n fputs(stderr, \"ERROR: infinite type\\n\");\n exit(1);\n };\n x0 = map_find(tyvarmap, p1[1]);\n if (x0 == NULL) { return; };\n x0 = rename_tyscheme(x0);\n occur_check(p0, x0[1]);\n return;\n };\n};\n\noccur_check_tuple_t: (p0, p1) {\n allocate(2);\n x1 = p1[1]; (% length %);\n x0 = 0;\n while (x0 < x1) {\n occur_check(p0, (p1[2])[x0]);\n x0 = x0 + 1;\n };\n};\n\noccur_check_lambda_t: (p0, p1) {\n occur_check(p0, p1[1]);\n occur_check(p0, p1[2]);\n};\n\n(% p0, p1: type %);\ntype_mismatch: (p0, p1) {\n fputs(stderr, \"ERROR: type mismatch \");\n put_type(stderr, p0);\n fputs(stderr, \" <-> \");\n put_type(stderr, p1);\n fputc(stderr, '\\n');\n exit(1);\n};\n\nderef_funcs: [not_reachable, deref_integer, deref_string, deref_dontcare,\n deref_identifier, deref_array, deref_tuple, deref_block, deref_decl,\n deref_call, deref_subscript, deref_lambda, deref_unexpr, deref_binexpr,\n deref_assign, deref_export, deref_import, deref_external, deref_ret, deref_retval,\n deref_syscall, deref_field, deref_fieldref, deref_typedecl, deref_variant, deref_unit,\n deref_typedexpr, deref_if, deref_ifelse, deref_static_array, deref_cast, deref_new,\n deref_while, deref_for, deref_newarray, deref_rewrite\n];\n\n(% p0: item %);\nderef: (p0) {\n allocate(1);\n x0 = deref_funcs[p0[0]];\n x0(p0);\n};\n\nderef_identifier: (p0) {\n p0[1] = deref_type(p0[1]);\n p0[4] = closure(p0[1]);\n};\n\nderef_dontcare: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_integer: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_string: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_array: (p0) {\n allocate(3);\n x0 = p0[2]; (% length %);\n x1 = 0;\n while (x1 < x0) {\n x2 = p0[3];\n deref(x2[x1]);\n x1 = x1 + 1;\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_tuple: (p0) {\n allocate(3);\n x0 = p0[2]; (% length %);\n x1 = 0;\n while (x1 < x0) {\n x2 = p0[3];\n deref(x2[x1]);\n x1 = x1 + 1;\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_block: (p0) {\n allocate(1);\n x0 = p0[BLOCK_STATEMENTS];\n while (x0 != NULL) {\n deref(ls_value(x0));\n x0 = ls_next(x0);\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_decl: (p0) {\n deref(p0[2]); (% lhs %);\n deref(p0[3]); (% rhs %);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_call: (p0) {\n deref(p0[2]); (% function %);\n deref(p0[3]); (% argument %);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_subscript: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_lambda: (p0) {\n deref(p0[LAMBDA_ARG]);\n deref(p0[LAMBDA_BODY]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_unexpr: (p0) {\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_binexpr: (p0) {\n deref(p0[3]);\n deref(p0[4]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_assign: (p0) {\n deref(p0[3]);\n deref(p0[4]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_export: (p0) {\n deref(p0[1]);\n};\n\nderef_import: (p0) {\n (% do nothing %);\n};\n\nderef_external: (p0) {\n (% do nothing %);\n};\n\nderef_ret: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_retval: (p0) {\n deref(p0[RETVAL_VALUE]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_syscall: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_field: (p0) {\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_fieldref: (p0) {\n deref(p0[2]); (% lhs %);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_typedecl: (p0) {\n (% do nothing %);\n};\n\nderef_variant: (p0) {\n if (p0[4] != NULL) {\n deref(p0[4]);\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_unit: (p0) {\n (% do nothing %);\n};\n\nderef_typedexpr: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_if: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_ifelse: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n deref(p0[4]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_static_array: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_cast: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_new: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_while: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n};\n\nderef_for: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n deref(p0[4]);\n deref(p0[5]);\n};\n\nderef_newarray: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_rewrite: (p0) {\n (% do nothing %);\n return;\n};\n\n(% p0: type %);\nderef_type: (p0) {\n allocate(3);\n if (p0[0] == NODE_TUPLE_T) {\n x0 = p0[1]; (% length %);\n x1 = 0;\n while (x1 < x0) {\n x2 = p0[2];\n x2[x1] = deref_type(x2[x1]);\n x1 = x1 + 1;\n };\n return p0;\n };\n if (p0[0] == NODE_ARRAY_T) { p0[1] = deref_type(p0[1]); return p0; };\n if (p0[0] == NODE_LAMBDA_T) {\n p0[1] = deref_type(p0[1]);\n p0[2] = deref_type(p0[2]);\n return p0;\n };\n if (p0[0] == NODE_TYVAR) {\n x0 = map_find(tyvarmap, p0[1]); (% x0: type scheme %);\n if (x0 == NULL) { return p0; };\n x1 = x0[1];\n x1 = deref_type(x1);\n x2 = closure(x1);\n map_add(tyvarmap, p0[1], x2);\n return x1\n };\n if (p0[0] == NODE_FIELD_T) {\n p0[2] = deref_type(p0[2]);\n return p0;\n };\n if (p0[0] == NODE_NAMED_T) {\n\tif (p0[2] != NULL) {\n\t p0[2] = deref_type(p0[2]);\n\t};\n\treturn p0;\n };\n return p0;\n};\n\n(% p0: pattern %);\nderef_pattern: (p0) {\n allocate(3);\n if (p0[0] == NODE_DONTCARE) {\n p0[1] = deref_type(p0[1]);\n return;\n };\n if (p0[0] == NODE_IDENTIFIER) {\n p0[1] = deref_type(p0[1]);\n p0[4] = closure(p0[1]);\n return;\n };\n if (p0[0] == NODE_TUPLE) {\n x0 = p0[TUPLE_LENGTH];\n x1 = p0[TUPLE_ELEMENTS];\n x2 = 0;\n while (x2 < x0) {\n deref_pattern(x1[x2]);\n x2 = x2 + 1;\n };\n p0[1] = deref_type(p0[1]);\n return;\n };\n not_reachable();\n};\n\n(% p0: program (item list) %);\ntyping: (p0) {\n allocate(1);\n\n varmap = mkmap(&ident_hash, &ident_equal, 10);\n funtable = mkmap(&ident_hash, &ident_equal, 10);\n scopeid_stack = mkvec(0);\n scope_push(); (% global scopeid %);\n init_tyvarmap();\n\n variant_map = mkmap(&strhash, &streq, 10);\n return_stack = mkvec(0);\n\n x0 = p0[1];\n while (x0 != NULL) {\n infer_item(ls_value(x0));\n x0 = ls_next(x0);\n };\n return p0;\n};\n","old_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: typing.rl 2010-04-23 16:56:50 nineties $\n %);\n\ninclude(stddef, code);\n\nexport(init_typing, typing, unit_type, char_type, int_type, float_type, double_type, void_type);\nexport(get_variable);\n\nscopeid: 0;\nscopeid_stack: NULL; \n\nvarmap: NULL; (% variable table. name -> list of (tyscheme, id) %);\n\n(% p0: (scopeid-id, name) %);\nvarmap_hash: (p0) {\n return strhash(p0[1]) * 3+ p0[0];\n};\n\nvarmap_keyequal: (p0, p1) {\n if (p0[0] != p1[0]) { return FALSE; };\n return streq(p0[1], p1[1]);\n};\n\nvarmap_push: () {\n scopeid = scopeid + 1;\n vec_pushback(scopeid_stack, scopeid);\n};\n\nvarmap_pop: () {\n vec_popback(scopeid_stack);\n};\n\n(% p0: name, p1: value %);\nvarmap_add: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(varmap, mktup2(x0, p0), p1);\n};\n\n(% p0: name %);\nvarmap_find: (p0) {\n allocate(3);\n x0 = vec_size(scopeid_stack)-1;\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(varmap, mktup2(x1, p0));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return NULL;\n};\n\ninit_varmap: () {\n varmap = mkmap(&varmap_hash, &varmap_keyequal, 10);\n scopeid_stack = mkvec(0);\n varmap_push(); (% global scopeid %);\n};\n\n(% p0: name %);\nget_variable: (p0) {\n allocate(1);\n x0 = varmap_find(p0); (% tyscheme, id, is_global %);\n if (x0 == NULL) {\n fputs(stderr, \"ERROR: variable '\");\n fputs(stderr, p0);\n fputs(stderr, \"' is not declared\\n\");\n exit(1);\n };\n return mktup6(NODE_IDENTIFIER, x0[0][1], p0, x0[1], x0[0], x0[2]);\n};\n\n\nin_global_namespace: () {\n return vec_size(scopeid_stack) == 1;\n};\n\ntyvarmap: NULL;\n\ntyvarid_hash: (p0) {\n return p0;\n};\n\ntyvarid_equal: (p0, p1) {\n return p0 == p1;\n};\n\ninit_tyvarmap: () {\n tyvarmap = mkmap(&tyvarid_hash, &tyvarid_equal, 10);\n};\n\n(% constructor name -> (variant type, corresponding row) %);\nvariant_map: NULL;\n\nnot_reachable: (p0) {\n fputs(stderr, \"ERROR: not reachable here\\n\");\n exit(1);\n};\n\nnot_implemented: (p0) {\n fputs(stderr, \"ERROR: not implemented\\n\");\n exit(1);\n};\n\ninfer_funcs: [not_reachable, infer_integer, infer_string, not_implemented,\n infer_identifier, infer_array, infer_tuple, infer_block, infer_decl,\n infer_call, infer_subscript, infer_lambda, infer_unexpr, infer_binexpr,\n infer_assign, infer_export, infer_import, infer_external, infer_ret, infer_retval,\n infer_syscall, infer_field, infer_fieldref, infer_typedecl, infer_variant, infer_unit,\n infer_typedexpr, infer_if, infer_ifelse, infer_static_array, infer_cast, infer_new,\n infer_while, infer_for, infer_newarray, infer_rewrite\n];\n\nunit_type : NULL;\nchar_type : NULL;\nint_type : NULL;\nfloat_type : NULL;\ndouble_type : NULL;\nvoid_type : NULL;\n\ninit_typing: () {\n unit_type = mktup1(NODE_UNIT_T);\n char_type = mktup1(NODE_CHAR_T);\n int_type = mktup1(NODE_INT_T);\n float_type = mktup1(NODE_FLOAT_T);\n double_type = mktup1(NODE_DOUBLE_T);\n void_type = mktup1(NODE_VOID_T);\n};\n\ninfer_integer: (p0) {\n if (p0[2] == 8) { p0[1] = char_type; return char_type; };\n if (p0[2] == 32) { p0[1] = int_type; return int_type; };\n not_reachable();\n};\n\ninfer_string: (p0) {\n p0[1] = mktup3(NODE_NAMED_T, \"string\", NULL);\n return p0[1];\n};\n\ninfer_identifier: (p0) {\n allocate(3);\n x0 = varmap_find(p0[2]); (% (tyscheme, id, is_global) %);\n if (x0 == NULL) {\n fputs(stderr, \"ERROR: undefined symbol '\");\n fputs(stderr, p0[2]);\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n\n x1 = rename_tyscheme(x0[0]);\n p0[1] = x1[1];\n p0[3] = x0[1];\n p0[4] = x1;\n p0[5] = x0[2];\n\n deref(p0);\n\n return p0[1];\n};\n\ninfer_array: (p0) {\n allocate(5);\n x0 = mktyvar();\n x1 = p0[2]; (% length %);\n x2 = 0;\n x3 = p0[3]; (% pointer to the array %);\n while (x2 < x1) {\n x4 = x3[x2];\n x4[1] = infer_item(x3[x2]);\n unify(x0, x4[1], TRUE);\n x2 = x2 + 1;\n };\n not_implemented();\n p0[1] = mktup4(NODE_ARRAY_T, x0, x1, FALSE);\n deref(p0);\n return p0[1];\n};\n\ninfer_tuple: (p0) {\n allocate(5);\n x1 = p0[2]; (% length %);\n x2 = p0[3];\n x3 = memalloc(4*x1);\n x0 = 0;\n while (x0 < x1) {\n x4 = x2[x0];\n x4[1] = infer_item((p0[3])[x0]);\n x3[x0] = x4[1];\n x0 = x0 + 1;\n };\n p0[1] = mktup3(NODE_TUPLE_T, x1, x3);\n deref(p0);\n return p0[1];\n};\n\ndo_exit: (p0) {\n if (p0[0] == NODE_RETVAL) { return TRUE; };\n if (p0[0] == NODE_RET) { return TRUE; };\n if (p0[1][0] == NODE_VOID_T) { return TRUE; };\n return FALSE;\n};\n\n(% p0: instruction %);\nblock_type: (p0) {\n if (p0[0] == NODE_RET) { return void_type; };\n if (p0[0] == NODE_RETVAL) { return void_type; };\n if (p0[1][0] == NODE_VOID_T) {\n return void_type;\n };\n return unit_type;\n};\n\nreturn_stack: NULL;\n\ninfer_block: (p0) {\n allocate(3);\n x0 = p0[BLOCK_STATEMENTS];\n\n if (x0 != NULL) {\n while (x0 != NULL) {\n x1 = ls_value(x0);\n x2 = infer_item(x1);\n if (ls_next(x0) != NULL) {\n if (do_exit(ls_value(x0))) {\n fputs(stderr, \"ERROR: unreachable code '\");\n put_item(stderr, ls_value(ls_next(x0)));\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n } else {\n p0[1] = block_type(x1);\n };\n x0 = ls_next(x0);\n };\n } else {\n (% empty function body %);\n p0[1] = unit_type;\n };\n\n deref(p0);\n return p0[1];\n};\n\n(% p0: dontcare pattern, p1: expr %);\ninfer_decl_dontcare: (p0, p1) {\n p0[1] = infer_item(p1);\n return p0[1];\n};\n\n(% p0: var, p1: expr %);\ninfer_decl_var: (p0, p1) {\n allocate(5);\n x0 = mktyvar();\n x1 = set_varid(p0);\n x2 = in_global_namespace();\n varmap_add(p0[2], mktup3(mktyscheme(x0), x1, x2));\n x3 = infer_item(p1);\n unify(x0, x3, TRUE);\n x4 = closure(x3);\n varmap_add(p0[2], mktup3(x4, x1, x2));\n p0[1] = x3; (% type %);\n p0[3] = x1; (% variable id %);\n p0[4] = x4; (% type scheme %);\n p0[5] = x2;\n deref_pattern(p0);\n deref(p1);\n return p0[1];\n};\n\n(% p0: tuple pattern, p1: expr %);\ninfer_decl_tuple: (p0, p1) {\n allocate(1);\n x0 = infer_pattern(p0);\n unify(x0, infer_item(p1), TRUE);\n deref_pattern(p0);\n deref(p1);\n return p0[1];\n};\n\ninfer_pattern: (p0) {\n allocate(5);\n if (p0[0] == NODE_UNIT) {\n p0[1] = unit_type;\n return unit_type;\n };\n if (p0[0] == NODE_DONTCARE) {\n x0 = mktyvar();\n p0[1] = x0;\n return x0;\n };\n if (p0[0] == NODE_IDENTIFIER) {\n (% variable pattern %);\n x0 = mktyvar(); (% type of variable %);\n x1 = set_varid(p0);\n x2 = mktup3(mktyscheme(x0), x1, in_global_namespace());\n varmap_add(p0[2], x2);\n p0[1] = x0;\n p0[3] = x1;\n p0[4] = x2;\n deref(p0);\n return p0[1];\n };\n if (p0[0] == NODE_TUPLE) {\n (% tuple pattern %);\n x0 = p0[TUPLE_LENGTH];\n x1 = p0[TUPLE_ELEMENTS];\n x2 = memalloc(4*x0); (% element types %);\n x3 = 0;\n while (x3 < x0) {\n x4 = infer_pattern(x1[x3]);\n x2[x3] = x4;\n x3 = x3 + 1;\n };\n p0[1] = mktup3(NODE_TUPLE_T, x0, x2);\n return p0[1];\n };\n if (p0[0] == NODE_TYPEDEXPR) {\n (% typed pattern %);\n x0 = infer_pattern(p0[2]);\n unify(x0, p0[1], TRUE);\n deref(p0);\n return p0[1];\n };\n fputs(stderr, \"ERROR: invalid pattern expression\\n\");\n exit(1);\n};\n\n(% p0: lhs, p1: rhs %);\ninfer_decl_impl: (p0, p1) {\n if (p0[0] == NODE_DONTCARE) {\n return infer_decl_dontcare(p0, p1);\n };\n if (p0[0] == NODE_IDENTIFIER) {\n return infer_decl_var(p0, p1);\n };\n if (p0[0] == NODE_TUPLE) {\n return infer_decl_tuple(p0, p1);\n };\n not_implemented();\n};\n\ninfer_decl: (p0) {\n allocate(1);\n x0 = infer_decl_impl(p0[2], p0[3]);\n p0[1] = x0;\n deref(p0);\n return p0[1];\n};\n\n\n(% p0: expr %);\ninfer_call: (p0) {\n allocate(3);\n x0 = infer_item(p0[2]); (% function type %);\n x1 = infer_item(p0[3]); (% argument type %);\n x2 = mktyvar(); (% return type %);\n unify(x0, mktup3(NODE_LAMBDA_T, x1, x2), TRUE);\n\n p0[1] = x2;\n deref(p0);\n return p0[1];\n};\n\ninfer_subscript: (p0) {\n allocate(2);\n x0 = infer_item(p0[2]);\n x1 = infer_item(p0[3]);\n unify(int_type, x1, TRUE);\n if (x0[0] == NODE_SARRAY_T) {\n\tp0[1] = x0[1];\n\tderef(p0);\n\treturn p0[1];\n };\n if (x0[0] == NODE_ARRAY_T) {\n p0[1] = x0[1];\n deref(p0);\n return p0[1];\n };\n not_implemented();\n};\n\ninsert_missing_ret: (p0) {\n allocate(1);\n if (p0 == NULL) {\n return ls_singleton(mktup2(NODE_RET, unit_type));\n };\n x0 = ls_value(p0);\n if (x0[0] == NODE_RET) { return p0; };\n if (x0[0] == NODE_RETVAL) { return p0; };\n if (x0[1] == void_type) { return p0; };\n return ls_cons(x0, insert_missing_ret(ls_next(p0)));\n};\n\ninfer_lambda: (p0) {\n allocate(3);\n\n (% lambda opens new namespace %);\n varmap_push();\n x0 = infer_pattern(p0[LAMBDA_ARG]);\n\n vec_pushback(return_stack, NULL);\n x1 = infer_item(p0[LAMBDA_BODY]);\n x2 = vec_at(return_stack, vec_size(return_stack)-1);\n if (x2 != NULL) {\n x1 = x2;\n };\n vec_popback(return_stack);\n varmap_pop();\n\n p0[1] = mktup3(NODE_LAMBDA_T, x0, x1);\n\n if (p0[1] != void_type) {\n x2 = p0[LAMBDA_BODY];\n x2[2] = insert_missing_ret(x2[2]);\n };\n\n deref(p0);\n return p0[1];\n};\n\nunexpr_funcs: [\n infer_unarith, infer_unarith, infer_unarith, infer_unarith, not_implemented,\n infer_indirect, infer_unarith, infer_unarith, infer_unarith, infer_unarith\n];\n\ninfer_unarith: (p0) {\n allocate(1);\n x0 = infer_item(p0[3]);\n unify(int_type, x0, TRUE);\n p0[1] = int_type;\n return int_type;\n};\n\ninfer_indirect: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]);\n x1 = mktyvar();\n unify(mktup2(NODE_POINTER_T, x1), x0, TRUE);\n p0[1] = x1;\n deref(p0);\n return p0[1];\n};\n\ninfer_unexpr: (p0) {\n allocate(1);\n x0 = unexpr_funcs[p0[2]];\n return x0(p0);\n};\n\nbinexpr_funcs: [\n not_reachable, infer_binarith, infer_binarith, infer_binarith, infer_binarith,\n infer_binarith, infer_binarith, infer_binarith, infer_binarith, infer_binarith,\n infer_binarith, infer_equality, infer_equality, infer_binarith, infer_binarith,\n infer_binarith, infer_binarith, not_implemented, not_implemented\n];\n\ninfer_binarith: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]);\n x1 = infer_item(p0[4]);\n unify(int_type, x0, TRUE);\n unify(int_type, x1, TRUE);\n p0[1] = int_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_equality: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]);\n x1 = infer_item(p0[4]);\n unify(x0, x1, TRUE);\n p0[1] = int_type;\n deref(p0);\n return int_type;\n};\n\ninfer_binexpr: (p0) {\n allocate(1);\n x0 = binexpr_funcs[p0[2]];\n return x0(p0);\n};\n\ninfer_assign: (p0) {\n allocate(2);\n x0 = infer_item(p0[3]); (% lhs type %);\n x1 = infer_item(p0[4]); (% rhs type %);\n unify(x0, x1, TRUE);\n p0[1] = x0;\n return x0;\n};\n\ninfer_export: (p0) {\n infer_item(p0[1]);\n deref(p0);\n return unit_type;\n};\n\ninfer_import: (p0) {\n (% do nothing %);\n};\n\ninfer_external: (p0) {\n allocate(5);\n x0 = p0[1]; (% ident %);\n x1 = p0[2]; (% type %);\n x2 = closure(x1);\n x3 = set_varid(x0);\n varmap_add(get_ident_name(x0), mktup3(x2, x3, TRUE));\n x0[1] = x1;\n x0[3] = x3;\n x0[4] = x2;\n x0[5] = TRUE;\n return unit_type;\n};\n\ninfer_ret: (p0) {\n allocate(1);\n x0 = vec_back(return_stack);\n if (x0 != NULL) {\n unify(x0, unit_type, TRUE);\n };\n vec_put(return_stack, vec_size(return_stack)-1, unit_type);\n p0[1] = unit_type;\n deref(p0);\n return unit_type;\n};\n\n(% return e; is treated as .pseudo_retvar = e; %);\ninfer_retval: (p0) {\n allocate(1);\n p0[1] = infer_item(p0[RETVAL_VALUE]);\n x0 = vec_back(return_stack);\n if (x0 != NULL) {\n unify(p0[1], x0, TRUE);\n };\n deref(p0);\n vec_put(return_stack, vec_size(return_stack)-1, p0[1]);\n return p0[1];\n};\n\ninfer_syscall: (p0) {\n infer_item(p0[2]);\n p0[1] = mktyvar();\n deref(p0);\n return p0[1];\n};\n\n(% fieldname : expression %);\ninfer_field: (p0) {\n allocate(3);\n x0 = p0[2]; (% lhs %);\n if (x0[0] != NODE_IDENTIFIER) {\n fputs(stderr, \"ERROR: invalid field name\\n\");\n exit(1);\n };\n x1 = infer_item(p0[3]);\n x2 = mktup3(NODE_FIELD_T, get_ident_name(x0), x1);\n p0[1] = x2;\n deref(p0);\n return p0[1];\n};\n\n(% p0: type, p1: field name %);\nget_fieldtype: (p0, p1) {\n allocate(4);\n if (p0[0] == NODE_TUPLE_T) {\n x0 = p0[TUPLE_T_LENGTH];\n x1 = p0[TUPLE_T_ELEMENTS];\n x2 = 0;\n while (x2 < x0) {\n x3 = x1[x2];\n if (has_name(x3, p1)) {\n return x3[2];\n };\n x2 = x2 + 1;\n };\n return NULL;\n };\n if (p0[0] == NODE_VARIANT_T) {\n x0 = p0[2]; (% rows %);\n if (ls_length(x0) != 1) {\n return NULL;\n };\n x1 = (ls_value(x0))[2]; (% argument type %);\n return get_fieldtype(x1, p1);\n };\n if (p0[0] == NODE_NAMED_T) {\n if (p0[2] != NULL) {\n return get_fieldtype(p0[2], p1);\n };\n return NULL;\n };\n return NULL;\n};\n\ninfer_fieldref: (p0) {\n allocate(3);\n x0 = infer_item(p0[2]); (% lhs %);\n x1 = p0[3]; (% field name %);\n x2 = get_fieldtype(x0, x1);\n if (x2 == NULL) {\n fputs(stderr, \"ERROR: field '\");\n fputs(stderr, x1);\n fputs(stderr, \"' not found\\n\");\n exit(1);\n };\n p0[1] = x2;\n deref(p0);\n return p0[1];\n};\n\ninfer_typedecl: (p0) {\n allocate(5);\n x0 = p0[1]; (% identifier %);\n x1 = p0[2][2]; (% type %);\n if (x1 == NULL) {\n\treturn unit_type;\n };\n if (x1[0] == NODE_VARIANT_T) {\n x1[1] = x0;\n x2 = x1[2]; (% rows %);\n x3 = 0; (% constructor id %);\n\n (% set constructor-id and register to variant_map %);\n while (x2 != NULL) {\n x4 = ls_value(x2); (% constructor name, id, arg %);\n x4[1] = x3;\n map_add(variant_map, x4[0], mktup2(x1, x4));\n x2 = ls_next(x2);\n x3 = x3 + 1;\n };\n return unit_type;\n };\n return unit_type;\n};\n\ninfer_variant: (p0) {\n allocate(3);\n x0 = p0[2]; (% constructor name %);\n x1 = map_find(variant_map, x0); (% (type, (constructor name, id, arg type)) %);\n assert(x1 != NULL);\n p0[1] = x1[0];\n p0[3] = x1[1][1]; (% id %);\n if (p0[4] != NULL) {\n x2 = infer_item(p0[4]); (% infer argument %);\n unify(x2, x1[1][2], TRUE);\n };\n deref(p0);\n return p0[1];\n};\n\ninfer_unit: (p0) {\n p0[1] = unit_type;\n return unit_type;\n};\n\ninfer_typedexpr: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]); (% expression %);\n unify(x0, p0[1], TRUE);\n deref(p0);\n return p0[1];\n};\n\ninfer_if: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]); (% condition %);\n unify(x0, int_type, TRUE);\n infer_item(p0[3]);\n p0[1] = unit_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_ifelse: (p0) {\n allocate(3);\n x0 = infer_item(p0[2]); (% condition %);\n unify(int_type, x0, TRUE);\n x1 = infer_item(p0[3]); (% ifthen block %);\n x2 = infer_item(p0[4]); (% ifelse block %);\n p0[1] = unify_join(x1, x2, TRUE);\n deref(p0);\n return p0[1];\n};\n\ninfer_static_array: (p0) {\n allocate(4);\n x0 = infer_item(p0[2]); (% initializer %);\n x1 = infer_item(p0[3]); (% length %);\n unify(x1, int_type, TRUE);\n p0[1] = mktup2(NODE_SARRAY_T, x0);\n deref(p0);\n return p0[1];\n};\n\ninfer_cast: (p0) {\n infer_item(p0[2]);\n deref(p0);\n return p0[1];\n};\n\ninfer_new: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]);\n p0[1] = mktup2(NODE_POINTER_T, x0);\n deref(p0);\n return p0[1];\n};\n\ninfer_while: (p0) {\n allocate(1);\n x0 = infer_item(p0[2]); (% condition %);\n unify(int_type, x0, TRUE);\n infer_item(p0[3]);\n p0[1] = unit_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_for: (p0) {\n allocate(1);\n infer_item(p0[2]);\n x0 = infer_item(p0[3]); (% condition %);\n unify(int_type, x0, TRUE);\n infer_item(p0[4]);\n infer_item(p0[5]);\n p0[1] = unit_type;\n deref(p0);\n return p0[1];\n};\n\ninfer_newarray: (p0) {\n allocate(2);\n x0 = infer_item(p0[2]); (% length %);\n unify(int_type, x0, TRUE);\n x1 = infer_item(p0[3]);\n p0[1] = mktup2(NODE_ARRAY_T, x1);\n deref(p0);\n return p0[1];\n};\n\ninfer_rewrite: (p0) {\n return unit_type;\n};\n\n(% p0: item %);\ninfer_item: (p0) {\n allocate(1);\n x0 = infer_funcs[p0[0]];\n return x0(p0);\n};\n\nremove_freevar: (p0) {\n allocate(1);\n if (p0 == NULL) { return NULL; };\n x0 = map_find(tyvarmap, ls_value(p0));\n if (x0 != NULL) {\n p0[1] = remove_freevar(ls_next(p0));\n return p0;\n };\n return remove_freevar(ls_next(p0));\n};\n\n(% p0: type %);\nclosure: (p0) {\n allocate(1);\n x0 = freevar(p0);\n x0 = remove_freevar(x0);\n return mktup2(x0, p0);\n};\n\n\n(% p0, p1: type, p2: do update tyvarmap %);\nunify: (p0, p1, p2) {\n if (p0[0] == NODE_TYVAR) { return unify_tyvar(p0, p1, p2); };\n if (p1[0] == NODE_TYVAR) { return unify_tyvar(p1, p0, p2); };\n if (p0[0] == p1[0]) {\n if (p0[0] == NODE_UNIT_T) { return TRUE; };\n if (p0[0] == NODE_CHAR_T) { return TRUE; };\n if (p0[0] == NODE_INT_T) { return TRUE; };\n if (p0[0] == NODE_FLOAT_T) { return TRUE; };\n if (p0[0] == NODE_DOUBLE_T) { return TRUE; };\n if (p0[0] == NODE_POINTER_T) { return unify(p0[POINTER_T_BASE], p1[POINTER_T_BASE], p2); };\n if (p0[0] == NODE_TUPLE_T) { return unify_tuple_t(p0, p1, p2); };\n if (p0[0] == NODE_ARRAY_T) {\n unify(p0[ARRAY_T_ELEMENT], p1[ARRAY_T_ELEMENT], p2);\n return TRUE;\n };\n if (p0[0] == NODE_LAMBDA_T) { return unify_lambda_t(p0, p1, p2); };\n if (p0[0] == NODE_VARIANT_T) {\n if (streq(p0[1], p1[1])) { return TRUE; };\n };\n\tif (p0[0] == NODE_NAMED_T) {\n\t if (streq(p0[1], p1[1])) { return TRUE; };\n\t};\n };\n if (p0[0] == NODE_NAMED_T) {\n\tif (p0[2] != NULL) {\n\t return unify(p0[2], p1, p2);\n\t};\n };\n if (p1[0] == NODE_NAMED_T) {\n\tif (p1[2] != NULL) {\n\t return unify(p0, p1[2], p2);\n\t};\n };\n if (p0[0] == NODE_FIELD_T) {\n return unify(p0[2], p1, p2);\n };\n if (p1[0] == NODE_FIELD_T) {\n return unify(p0, p1[2], p2);\n };\n if (p2) {\n type_mismatch(p0, p1);\n };\n return FALSE;\n};\n\nunify_tuple_t: (p0, p1, p2) {\n allocate(2);\n if (p0[1] != p1[1]) {\n if (p2) {\n type_mismatch(p0, p1);\n };\n return FALSE;\n };\n x1 = p0[1]; (% length %);\n x0 = 0;\n while (x0 < x1) {\n if (unify((p0[2])[x0], (p1[2])[x0], p2) == FALSE) {\n return FALSE;\n };\n x0 = x0 + 1;\n };\n return TRUE;\n};\n\nunify_lambda_t: (p0, p1, p2) {\n if(unify(p0[1], p1[1], p2) == FALSE) {\n return FALSE;\n };\n return unify(p0[2], p1[2], p2);\n};\n\n(% p0: tyvar, p1, type %);\nunify_tyvar: (p0, p1, p2) {\n allocate(1);\n if (p1[0] == NODE_TYVAR) {\n if (p0[1] == p1[1]) { return TRUE; };\n };\n x0 = map_find(tyvarmap, p0[1]);\n if (x0 != NULL) {\n return unify(x0[1], p1, p2);\n };\n if (p1[0] == NODE_TYVAR) {\n x0 = map_find(tyvarmap, p1[1]);\n if (x0 != NULL) {\n return unify(p0, x0[1], p2);\n };\n };\n occur_check(p0[1], p1);\n if (p2) {\n x0 = closure(p1);\n map_add(tyvarmap, p0[1], x0);\n };\n};\n\n(% p0: type of ifthen block, p1: type of ifelse block %);\nunify_join: (p0, p1) {\n if (p0 == void_type) { return p1; };\n if (p1 == void_type) { return p0; };\n return unit_type;\n};\n\n(% p0: id, p1, type %);\noccur_check: (p0, p1) {\n allocate(1);\n if (p1[0] == NODE_TUPLE_T) { return occur_check_tuple_t(p0, p1); };\n if (p1[0] == NODE_ARRAY_T) { return occur_check(p0, p1[1]); };\n if (p1[0] == NODE_LAMBDA_T) { return occur_check_lambda_t(p0, p1); };\n if (p1[0] == NODE_TYVAR) {\n if (p0 == p1[1]) {\n fputs(stderr, \"ERROR: infinite type\\n\");\n exit(1);\n };\n x0 = map_find(tyvarmap, p1[1]);\n if (x0 == NULL) { return; };\n x0 = rename_tyscheme(x0);\n occur_check(p0, x0[1]);\n return;\n };\n};\n\noccur_check_tuple_t: (p0, p1) {\n allocate(2);\n x1 = p1[1]; (% length %);\n x0 = 0;\n while (x0 < x1) {\n occur_check(p0, (p1[2])[x0]);\n x0 = x0 + 1;\n };\n};\n\noccur_check_lambda_t: (p0, p1) {\n occur_check(p0, p1[1]);\n occur_check(p0, p1[2]);\n};\n\n(% p0, p1: type %);\ntype_mismatch: (p0, p1) {\n fputs(stderr, \"ERROR: type mismatch \");\n put_type(stderr, p0);\n fputs(stderr, \" <-> \");\n put_type(stderr, p1);\n fputc(stderr, '\\n');\n exit(1);\n};\n\nderef_funcs: [not_reachable, deref_integer, deref_string, deref_dontcare,\n deref_identifier, deref_array, deref_tuple, deref_block, deref_decl,\n deref_call, deref_subscript, deref_lambda, deref_unexpr, deref_binexpr,\n deref_assign, deref_export, deref_import, deref_external, deref_ret, deref_retval,\n deref_syscall, deref_field, deref_fieldref, deref_typedecl, deref_variant, deref_unit,\n deref_typedexpr, deref_if, deref_ifelse, deref_static_array, deref_cast, deref_new,\n deref_while, deref_for, deref_newarray, deref_rewrite\n];\n\n(% p0: item %);\nderef: (p0) {\n allocate(1);\n x0 = deref_funcs[p0[0]];\n x0(p0);\n};\n\nderef_identifier: (p0) {\n p0[1] = deref_type(p0[1]);\n p0[4] = closure(p0[1]);\n};\n\nderef_dontcare: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_integer: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_string: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_array: (p0) {\n allocate(3);\n x0 = p0[2]; (% length %);\n x1 = 0;\n while (x1 < x0) {\n x2 = p0[3];\n deref(x2[x1]);\n x1 = x1 + 1;\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_tuple: (p0) {\n allocate(3);\n x0 = p0[2]; (% length %);\n x1 = 0;\n while (x1 < x0) {\n x2 = p0[3];\n deref(x2[x1]);\n x1 = x1 + 1;\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_block: (p0) {\n allocate(1);\n x0 = p0[BLOCK_STATEMENTS];\n while (x0 != NULL) {\n deref(ls_value(x0));\n x0 = ls_next(x0);\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_decl: (p0) {\n deref(p0[2]); (% lhs %);\n deref(p0[3]); (% rhs %);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_call: (p0) {\n deref(p0[2]); (% function %);\n deref(p0[3]); (% argument %);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_subscript: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_lambda: (p0) {\n deref(p0[LAMBDA_ARG]);\n deref(p0[LAMBDA_BODY]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_unexpr: (p0) {\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_binexpr: (p0) {\n deref(p0[3]);\n deref(p0[4]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_assign: (p0) {\n deref(p0[3]);\n deref(p0[4]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_export: (p0) {\n deref(p0[1]);\n};\n\nderef_import: (p0) {\n (% do nothing %);\n};\n\nderef_external: (p0) {\n (% do nothing %);\n};\n\nderef_ret: (p0) {\n p0[1] = deref_type(p0[1]);\n};\n\nderef_retval: (p0) {\n deref(p0[RETVAL_VALUE]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_syscall: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_field: (p0) {\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_fieldref: (p0) {\n deref(p0[2]); (% lhs %);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_typedecl: (p0) {\n (% do nothing %);\n};\n\nderef_variant: (p0) {\n if (p0[4] != NULL) {\n deref(p0[4]);\n };\n p0[1] = deref_type(p0[1]);\n};\n\nderef_unit: (p0) {\n (% do nothing %);\n};\n\nderef_typedexpr: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_if: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_ifelse: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n deref(p0[4]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_static_array: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_cast: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_new: (p0) {\n deref(p0[2]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_while: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n};\n\nderef_for: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n deref(p0[4]);\n deref(p0[5]);\n};\n\nderef_newarray: (p0) {\n deref(p0[2]);\n deref(p0[3]);\n p0[1] = deref_type(p0[1]);\n};\n\nderef_rewrite: (p0) {\n (% do nothing %);\n return;\n};\n\n(% p0: type %);\nderef_type: (p0) {\n allocate(3);\n if (p0[0] == NODE_TUPLE_T) {\n x0 = p0[1]; (% length %);\n x1 = 0;\n while (x1 < x0) {\n x2 = p0[2];\n x2[x1] = deref_type(x2[x1]);\n x1 = x1 + 1;\n };\n return p0;\n };\n if (p0[0] == NODE_ARRAY_T) { p0[1] = deref_type(p0[1]); return p0; };\n if (p0[0] == NODE_LAMBDA_T) {\n p0[1] = deref_type(p0[1]);\n p0[2] = deref_type(p0[2]);\n return p0;\n };\n if (p0[0] == NODE_TYVAR) {\n x0 = map_find(tyvarmap, p0[1]); (% x0: type scheme %);\n if (x0 == NULL) { return p0; };\n x1 = x0[1];\n x1 = deref_type(x1);\n x2 = closure(x1);\n map_add(tyvarmap, p0[1], x2);\n return x1\n };\n if (p0[0] == NODE_FIELD_T) {\n p0[2] = deref_type(p0[2]);\n return p0;\n };\n if (p0[0] == NODE_NAMED_T) {\n\tif (p0[2] != NULL) {\n\t p0[2] = deref_type(p0[2]);\n\t};\n\treturn p0;\n };\n return p0;\n};\n\n(% p0: pattern %);\nderef_pattern: (p0) {\n allocate(3);\n if (p0[0] == NODE_DONTCARE) {\n p0[1] = deref_type(p0[1]);\n return;\n };\n if (p0[0] == NODE_IDENTIFIER) {\n p0[1] = deref_type(p0[1]);\n p0[4] = closure(p0[1]);\n return;\n };\n if (p0[0] == NODE_TUPLE) {\n x0 = p0[TUPLE_LENGTH];\n x1 = p0[TUPLE_ELEMENTS];\n x2 = 0;\n while (x2 < x0) {\n deref_pattern(x1[x2]);\n x2 = x2 + 1;\n };\n p0[1] = deref_type(p0[1]);\n return;\n };\n not_reachable();\n};\n\n(% p0: program (item list) %);\ntyping: (p0) {\n allocate(1);\n\n init_varmap();\n init_tyvarmap();\n variant_map = mkmap(&strhash, &streq, 10);\n return_stack = mkvec(0);\n\n x0 = p0[1];\n while (x0 != NULL) {\n infer_item(ls_value(x0));\n x0 = ls_next(x0);\n };\n return p0;\n};\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f43b7ead2c27bf6fe43c381ea5078bb14dfbdf29","subject":"http: capture request content for POST requests","message":"http: capture request content for POST requests\n\nHTTP parser code used to capture HTTP headers only, ignoring\nthe content altogether, while it's allowed for POST requests\nto have contents. This commit adds parsing the content and makes\nit available through req->content string.\n\nMessage-Id: <5fd68ef57425289d55d49bc09f4d33fecd7c6509@scylladb.com>\n","repos":"dreamsxin\/seastar,cloudius-systems\/seastar,avikivity\/seastar,scylladb\/seastar,scylladb\/seastar,dreamsxin\/seastar,syuu1228\/seastar,avikivity\/seastar,syuu1228\/seastar,scylladb\/seastar,cloudius-systems\/seastar,dreamsxin\/seastar,cloudius-systems\/seastar,avikivity\/seastar,syuu1228\/seastar","old_file":"src\/http\/request_parser.rl","new_file":"src\/http\/request_parser.rl","new_contents":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace seastar {\n\nusing namespace httpd;\n\n%% machine request;\n\n%%{\n\naccess _fsm_;\n\naction mark {\n g.mark_start(p);\n}\n\naction store_method {\n _req->_method = str();\n}\n\naction store_uri {\n _req->_url = str();\n}\n\naction store_version {\n _req->_version = str();\n}\n\naction store_field_name {\n _field_name = str();\n}\n\naction store_value {\n _value = str();\n}\n\naction assign_field {\n _req->_headers[_field_name] = std::move(_value);\n}\n\naction extend_field {\n _req->_headers[_field_name] += sstring(\" \") + std::move(_value);\n}\n\naction done {\n g.mark_start(p);\n g.mark_end(pe);\n _req->content = get_str();\n _req->content_length = _req->content.size();\n done = true;\n fbreak;\n}\n\ncrlf = '\\r\\n';\ntchar = alpha | digit | '-' | '!' | '#' | '$' | '%' | '&' | '\\'' | '*'\n | '+' | '.' | '^' | '_' | '`' | '|' | '~';\n\nsp = ' ';\nht = '\\t';\n\nsp_ht = sp | ht;\n\nop_char = upper;\n\noperation = op_char+ >mark %store_method;\nuri = (any - sp)+ >mark %store_uri;\nhttp_version = 'HTTP\/' (digit '.' digit) >mark %store_version;\n\nfield = tchar+ >mark %store_field_name;\nvalue = any* >mark %store_value;\nstart_line = ((operation sp uri sp http_version) -- crlf) crlf;\nheader_1st = (field sp_ht* ':' sp_ht* value :> crlf) %assign_field;\nheader_cont = (sp_ht+ value sp_ht* crlf) %extend_field;\nheader = header_1st header_cont*;\nmain := start_line header* :> (crlf @done);\n\n}%%\n\nclass http_request_parser : public ragel_parser_base {\n %% write data nofinal noprefix;\npublic:\n enum class state {\n error,\n eof,\n done,\n };\n std::unique_ptr _req;\n sstring _field_name;\n sstring _value;\n state _state;\npublic:\n void init() {\n init_base();\n _req.reset(new httpd::request());\n _state = state::eof;\n %% write init;\n }\n char* parse(char* p, char* pe, char* eof) {\n sstring_builder::guard g(_builder, p, pe);\n auto str = [this, &g, &p] { g.mark_end(p); return get_str(); };\n bool done = false;\n if (p != pe) {\n _state = state::error;\n }\n %% write exec;\n if (!done) {\n p = nullptr;\n } else {\n _state = state::done;\n }\n return p;\n }\n auto get_parsed_request() {\n return std::move(_req);\n }\n bool eof() const {\n return _state == state::eof;\n }\n};\n\n}\n","old_contents":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace seastar {\n\nusing namespace httpd;\n\n%% machine request;\n\n%%{\n\naccess _fsm_;\n\naction mark {\n g.mark_start(p);\n}\n\naction store_method {\n _req->_method = str();\n}\n\naction store_uri {\n _req->_url = str();\n}\n\naction store_version {\n _req->_version = str();\n}\n\naction store_field_name {\n _field_name = str();\n}\n\naction store_value {\n _value = str();\n}\n\naction assign_field {\n _req->_headers[_field_name] = std::move(_value);\n}\n\naction extend_field {\n _req->_headers[_field_name] += sstring(\" \") + std::move(_value);\n}\n\naction done {\n done = true;\n fbreak;\n}\n\ncrlf = '\\r\\n';\ntchar = alpha | digit | '-' | '!' | '#' | '$' | '%' | '&' | '\\'' | '*'\n | '+' | '.' | '^' | '_' | '`' | '|' | '~';\n\nsp = ' ';\nht = '\\t';\n\nsp_ht = sp | ht;\n\nop_char = upper;\n\noperation = op_char+ >mark %store_method;\nuri = (any - sp)+ >mark %store_uri;\nhttp_version = 'HTTP\/' (digit '.' digit) >mark %store_version;\n\nfield = tchar+ >mark %store_field_name;\nvalue = any* >mark %store_value;\nstart_line = ((operation sp uri sp http_version) -- crlf) crlf;\nheader_1st = (field sp_ht* ':' sp_ht* value :> crlf) %assign_field;\nheader_cont = (sp_ht+ value sp_ht* crlf) %extend_field;\nheader = header_1st header_cont*;\nmain := start_line header* :> (crlf @done);\n\n}%%\n\nclass http_request_parser : public ragel_parser_base {\n %% write data nofinal noprefix;\npublic:\n enum class state {\n error,\n eof,\n done,\n };\n std::unique_ptr _req;\n sstring _field_name;\n sstring _value;\n state _state;\npublic:\n void init() {\n init_base();\n _req.reset(new httpd::request());\n _state = state::eof;\n %% write init;\n }\n char* parse(char* p, char* pe, char* eof) {\n sstring_builder::guard g(_builder, p, pe);\n auto str = [this, &g, &p] { g.mark_end(p); return get_str(); };\n bool done = false;\n if (p != pe) {\n _state = state::error;\n }\n %% write exec;\n if (!done) {\n p = nullptr;\n } else {\n _state = state::done;\n }\n return p;\n }\n auto get_parsed_request() {\n return std::move(_req);\n }\n bool eof() const {\n return _state == state::eof;\n }\n};\n\n}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"1e8ad386d547354d9fd2ce6d34a9b31728956953","subject":"Don't consume the last carriage return in the single line mutli-consume","message":"Don't consume the last carriage return in the single line mutli-consume\n\nThis is probably the least efficient way to do this, because I must be reparsing\nthe line 5 times. At some future point I have to come up with a single pass.\n","repos":"yanfali\/gomkv","old_file":"src\/handbrake\/handbrake.rl","new_file":"src\/handbrake\/handbrake.rl","new_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\nfunc parseOutput(data string) (HandBrakeMeta) {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\t_,_,_,_ = top, ts, te, act\n\tstack := []int{0}\n\t_ = eof\n\tline := 1\n\tcapture := false\n\tcsp := 0\n\tmeta := HandBrakeMeta{}\n\tfmt.Printf(\"%02d: \", line)\n\t_ = capture\n\t_ = csp\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\ttitle := |*\n\t\t\t(alnum|space)+[.]*alnum* => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tduration := |*\n\t\t\tspace*;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t*|;\n\t\tpaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1,4} \"\/\" digit{1,4} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tdaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1} . \".\" . digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tfps := |*\n\t\t\t\"\\n\" => { ts -= 10; fmt.Printf(\"%s\", data[ts:te-5]); p -= 1; fret; };\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tspace+ \"+\" space+ \"stream:\" space* @{ fcall title; } |\n\t\t\tspace+ \"+\" space+ \"duration:\" @{ fcall duration; } |\n\t\t\tspace+ \"+\" space+ \"size:\" @{ fcall picture; } |\n\t\t\tspace+ \"+\" any+ \"pixel\" space+ \"aspect:\" @{ fcall paspect; } |\n\t\t\tspace+ \"+\" any+ \"display\" space+ \"aspect:\" @{ fcall daspect; } |\n\t\t\tspace+ \"+\" any+ \"fps\" @{ fcall fps; } |\n\t\t\tspace+ \"+\" space+ \"autocrop:\" @{ fcall crop; }\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","old_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\nfunc parseOutput(data string) (HandBrakeMeta) {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\t_,_,_,_ = top, ts, te, act\n\tstack := []int{0}\n\t_ = eof\n\tline := 1\n\tcapture := false\n\tcsp := 0\n\tmeta := HandBrakeMeta{}\n\tfmt.Printf(\"%02d: \", line)\n\t_ = capture\n\t_ = csp\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\ttitle := |*\n\t\t\t(alnum|space)+[.]*alnum* => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tduration := |*\n\t\t\tspace*;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t*|;\n\t\tpaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1,4} \"\/\" digit{1,4} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tdaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1} . \".\" . digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tfps := |*\n\t\t\t\"\\n\" => { ts=ts-12; fmt.Printf(\"%s\\n\", data[ts:te-4]); fret; };\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tspace+ \"+\" space+ \"stream:\" space* @{ fcall title; } |\n\t\t\tspace+ \"+\" space+ \"duration:\" @{ fcall duration; } |\n\t\t\tspace+ \"+\" space+ \"size:\" @{ fcall picture; } |\n\t\t\tspace+ \"+\" any+ \"pixel\" space+ \"aspect:\" @{ fcall paspect; } |\n\t\t\tspace+ \"+\" any+ \"display\" space+ \"aspect:\" @{ fcall daspect; } |\n\t\t\tspace+ \"+\" any+ \"fps\" @{ fcall fps; } |\n\t\t\tspace+ \"+\" space+ \"autocrop:\" @{ fcall crop; }\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"039f6fa417ac2deef7a0ba4787f9d738dfdc6549","subject":"Fix CParser for Rubinius and Ruby 2.0.0 (and slightly speed it up!)","message":"Fix CParser for Rubinius and Ruby 2.0.0 (and slightly speed it up!)","repos":"elabs\/stomp_parser,elabs\/stomp_parser","old_file":"ext\/stomp_parser\/c_parser.c.rl","new_file":"ext\/stomp_parser\/c_parser.c.rl","new_contents":"#include \n\n#if DEBUG_H\n# define DEBUG(fmt, ...) do { fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__); } while(0)\n#else\n# define DEBUG(...)\n#endif\n\n#define UNUSED(x) (void)(x)\n#define MARK_LEN (p - mark)\n#define MARK_STR_NEW() rb_str_new(mark, MARK_LEN)\n\n#define true 1\n#define false 0\n\ntypedef struct {\n VALUE error;\n long max_frame_size;\n\n VALUE chunk;\n const char *p;\n int cs;\n const char *mark;\n VALUE mark_key;\n VALUE mark_frame;\n long mark_frame_size;\n long mark_content_length;\n} parser_state_t;\n\nVALUE mStompParser = Qnil;\nVALUE cFrame = Qnil;\nVALUE eFrameSizeExceeded = Qnil;\nID g_write_command;\nID g_write_header;\nID g_write_body;\nID g_content_length;\nID g_build_parse_error;\nID g_max_frame_size;\n\n%%{\n machine frame;\n\n action mark {\n mark = p;\n }\n\n action mark_frame {\n mark_frame = rb_class_new_instance(0, NULL, cFrame);\n mark_frame_size = 0;\n }\n\n action write_command {\n VALUE command = MARK_STR_NEW();\n rb_funcall2(mark_frame, g_write_command, 1, &command);\n mark = NULL;\n }\n\n action mark_key {\n mark_key = MARK_STR_NEW();\n mark = NULL;\n }\n\n action write_header {\n VALUE args[2] = { mark_key, MARK_STR_NEW() };\n rb_funcall2(mark_frame, g_write_header, 2, args);\n mark_key = Qnil;\n mark = NULL;\n }\n\n action finish_headers {\n VALUE length = rb_funcall2(mark_frame, g_content_length, 0, NULL);\n if ( ! NIL_P(length)) {\n mark_content_length = NUM2LONG(length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n VALUE body = MARK_STR_NEW();\n rb_funcall2(mark_frame, g_write_body, 1, &body);\n mark = NULL;\n }\n\n action consume_null {\n ((mark_content_length != -1) && (MARK_LEN < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || (MARK_LEN < mark_content_length))\n }\n\n action check_frame_size {\n mark_frame_size += 1;\n if (mark_frame_size > max_frame_size) {\n rb_raise(eFrameSizeExceeded, \"\");\n }\n }\n\n action finish_frame {\n rb_yield(mark_frame);\n mark_frame = Qnil;\n }\n\n include frame_common \"parser_common.rl\";\n\n write data noprefix;\n}%%\n\nstatic void parser_free(parser_state_t *state) {\n xfree(state);\n}\n\nstatic void parser_mark(parser_state_t *state) {\n rb_gc_mark(state->error);\n rb_gc_mark(state->mark_key);\n rb_gc_mark(state->mark_frame);\n rb_gc_mark(state->chunk);\n}\n\nstatic VALUE parser_alloc(VALUE klass) {\n parser_state_t *state = ALLOC(parser_state_t);\n return Data_Wrap_Struct(klass, parser_mark, parser_free, state);\n}\n\nstatic VALUE parser_initialize(int argc, VALUE *argv, VALUE self) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n VALUE max_frame_size;\n rb_scan_args(argc, argv, \"01\", &max_frame_size);\n\n if (max_frame_size == Qnil) {\n max_frame_size = rb_funcall(mStompParser, g_max_frame_size, 0);\n }\n\n state->error = Qnil;\n state->max_frame_size = FIX2LONG(max_frame_size);\n state->chunk = Qnil;\n state->cs = start;\n state->mark = NULL;\n state->mark_key = Qnil;\n state->mark_frame = Qnil;\n state->mark_frame_size = 0;\n state->mark_content_length = 0;\n\n return self;\n}\n\nstatic VALUE parser_parse(VALUE self, VALUE new_chunk) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n if (NIL_P(state->error)) {\n VALUE chunk = Qnil;\n const char *p = NULL;\n const char *mark = NULL;\n\n if ( ! NIL_P(state->chunk)) {\n long offset = RSTRING_LEN(state->chunk);\n long mark_offset = state->mark - RSTRING_PTR(state->chunk);\n\n chunk = rb_str_append(state->chunk, new_chunk);\n p = RSTRING_PTR(chunk) + offset;\n mark = RSTRING_PTR(chunk) + mark_offset;\n } else {\n chunk = new_chunk;\n p = RSTRING_PTR(chunk);\n }\n\n const char *pe = RSTRING_END(chunk);\n long max_frame_size = state->max_frame_size;\n\n int cs = state->cs;\n VALUE mark_key = state->mark_key;\n VALUE mark_frame = state->mark_frame;\n long mark_frame_size = state->mark_frame_size;\n long mark_content_length = state->mark_content_length;\n\n %% write exec;\n\n if (mark != NULL) {\n state->chunk = chunk;\n } else {\n state->chunk = Qnil;\n }\n\n state->cs = cs;\n state->mark = mark;\n state->mark_key = mark_key;\n state->mark_frame = mark_frame;\n state->mark_frame_size = mark_frame_size;\n state->mark_content_length = mark_content_length;\n\n if (cs == error) {\n long index = p - RSTRING_PTR(chunk);\n state->error = rb_funcall(mStompParser, g_build_parse_error, 2, chunk, LONG2NUM(index));\n }\n }\n\n if ( ! NIL_P(state->error)) {\n rb_exc_raise(state->error);\n }\n\n return Qnil;\n}\n\nvoid Init_c_parser(void) {\n mStompParser = rb_const_get(rb_cObject, rb_intern(\"StompParser\"));\n cFrame = rb_const_get(mStompParser, rb_intern(\"Frame\"));\n eFrameSizeExceeded = rb_const_get(mStompParser, rb_intern(\"FrameSizeExceeded\"));\n\n g_write_command = rb_intern(\"write_command\");\n g_write_header = rb_intern(\"write_header\");\n g_write_body = rb_intern(\"write_body\");\n g_content_length = rb_intern(\"content_length\");\n g_build_parse_error = rb_intern(\"build_parse_error\");\n g_max_frame_size = rb_intern(\"max_frame_size\");\n\n VALUE cParser = rb_define_class_under(mStompParser, \"CParser\", rb_cObject);\n rb_define_alloc_func(cParser, parser_alloc);\n\n rb_define_method(cParser, \"initialize\", parser_initialize, -1);\n rb_define_method(cParser, \"parse\", parser_parse, 1);\n}\n","old_contents":"#include \n\n#if DEBUG_H\n# define DEBUG(fmt, ...) do { fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__); } while(0)\n#else\n# define DEBUG(...)\n#endif\n\n#define UNUSED(x) (void)(x)\n#define MARK_LEN (p - mark)\n#define MARK_STR_NEW() rb_str_new(mark, MARK_LEN)\n\n#define true 1\n#define false 0\n\ntypedef struct {\n VALUE error;\n long max_frame_size;\n\n VALUE chunk;\n const char *p;\n int cs;\n const char *mark;\n VALUE mark_key;\n VALUE mark_frame;\n long mark_frame_size;\n long mark_content_length;\n} parser_state_t;\n\nVALUE mStompParser = Qnil;\nVALUE cFrame = Qnil;\nVALUE eFrameSizeExceeded = Qnil;\nID g_new;\nID g_write_command;\nID g_write_header;\nID g_write_body;\nID g_content_length;\nID g_build_parse_error;\nID g_max_frame_size;\n\n%%{\n machine frame;\n\n action mark {\n mark = p;\n }\n\n action mark_frame {\n mark_frame = rb_funcallv(cFrame, g_new, 0, NULL);\n mark_frame_size = 0;\n }\n\n action write_command {\n VALUE command = MARK_STR_NEW();\n rb_funcallv(mark_frame, g_write_command, 1, &command);\n mark = NULL;\n }\n\n action mark_key {\n mark_key = MARK_STR_NEW();\n mark = NULL;\n }\n\n action write_header {\n VALUE args[2] = { mark_key, MARK_STR_NEW() };\n rb_funcallv(mark_frame, g_write_header, 2, args);\n mark_key = Qnil;\n mark = NULL;\n }\n\n action finish_headers {\n VALUE length = rb_funcallv(mark_frame, g_content_length, 0, NULL);\n if ( ! NIL_P(length)) {\n mark_content_length = NUM2LONG(length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n VALUE body = MARK_STR_NEW();\n rb_funcallv(mark_frame, g_write_body, 1, &body);\n mark = NULL;\n }\n\n action consume_null {\n ((mark_content_length != -1) && (MARK_LEN < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || (MARK_LEN < mark_content_length))\n }\n\n action check_frame_size {\n mark_frame_size += 1;\n if (mark_frame_size > max_frame_size) {\n rb_raise(eFrameSizeExceeded, \"\");\n }\n }\n\n action finish_frame {\n rb_yield(mark_frame);\n mark_frame = Qnil;\n }\n\n include frame_common \"parser_common.rl\";\n\n write data noprefix;\n}%%\n\nstatic void parser_free(parser_state_t *state) {\n xfree(state);\n}\n\nstatic void parser_mark(parser_state_t *state) {\n rb_gc_mark(state->error);\n rb_gc_mark(state->mark_key);\n rb_gc_mark(state->mark_frame);\n rb_gc_mark(state->chunk);\n}\n\nstatic VALUE parser_alloc(VALUE klass) {\n parser_state_t *state = ALLOC(parser_state_t);\n return Data_Wrap_Struct(klass, parser_mark, parser_free, state);\n}\n\nstatic VALUE parser_initialize(int argc, VALUE *argv, VALUE self) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n VALUE max_frame_size;\n rb_scan_args(argc, argv, \"01\", &max_frame_size);\n\n if (max_frame_size == Qnil) {\n max_frame_size = rb_funcall(mStompParser, g_max_frame_size, 0);\n }\n\n state->error = Qnil;\n state->max_frame_size = FIX2LONG(max_frame_size);\n state->chunk = Qnil;\n state->cs = start;\n state->mark = NULL;\n state->mark_key = Qnil;\n state->mark_frame = Qnil;\n state->mark_frame_size = 0;\n state->mark_content_length = 0;\n\n return self;\n}\n\nstatic VALUE parser_parse(VALUE self, VALUE new_chunk) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n if (NIL_P(state->error)) {\n VALUE chunk = Qnil;\n const char *p = NULL;\n const char *mark = NULL;\n\n if ( ! NIL_P(state->chunk)) {\n long offset = RSTRING_LEN(state->chunk);\n long mark_offset = state->mark - RSTRING_PTR(state->chunk);\n\n chunk = rb_str_append(state->chunk, new_chunk);\n p = RSTRING_PTR(chunk) + offset;\n mark = RSTRING_PTR(chunk) + mark_offset;\n } else {\n chunk = new_chunk;\n p = RSTRING_PTR(chunk);\n }\n\n const char *pe = RSTRING_END(chunk);\n long max_frame_size = state->max_frame_size;\n\n int cs = state->cs;\n VALUE mark_key = state->mark_key;\n VALUE mark_frame = state->mark_frame;\n long mark_frame_size = state->mark_frame_size;\n long mark_content_length = state->mark_content_length;\n\n %% write exec;\n\n if (mark != NULL) {\n state->chunk = chunk;\n } else {\n state->chunk = Qnil;\n }\n\n state->cs = cs;\n state->mark = mark;\n state->mark_key = mark_key;\n state->mark_frame = mark_frame;\n state->mark_frame_size = mark_frame_size;\n state->mark_content_length = mark_content_length;\n\n if (cs == error) {\n long index = p - RSTRING_PTR(chunk);\n state->error = rb_funcall(mStompParser, g_build_parse_error, 2, chunk, LONG2NUM(index));\n }\n }\n\n if ( ! NIL_P(state->error)) {\n rb_exc_raise(state->error);\n }\n\n return Qnil;\n}\n\nvoid Init_c_parser(void) {\n mStompParser = rb_const_get(rb_cObject, rb_intern(\"StompParser\"));\n cFrame = rb_const_get(mStompParser, rb_intern(\"Frame\"));\n eFrameSizeExceeded = rb_const_get(mStompParser, rb_intern(\"FrameSizeExceeded\"));\n\n g_new = rb_intern(\"new\");\n g_write_command = rb_intern(\"write_command\");\n g_write_header = rb_intern(\"write_header\");\n g_write_body = rb_intern(\"write_body\");\n g_content_length = rb_intern(\"content_length\");\n g_build_parse_error = rb_intern(\"build_parse_error\");\n g_max_frame_size = rb_intern(\"max_frame_size\");\n\n VALUE cParser = rb_define_class_under(mStompParser, \"CParser\", rb_cObject);\n rb_define_alloc_func(cParser, parser_alloc);\n\n rb_define_method(cParser, \"initialize\", parser_initialize, -1);\n rb_define_method(cParser, \"parse\", parser_parse, 1);\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f4bb73e30834d0ababbe01b435d263e2fc82399b","subject":"cleanup","message":"cleanup\n","repos":"razum2um\/params_tree","old_file":"hello_world.rl","new_file":"hello_world.rl","new_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ])+ >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); p + 1 == pe and inject_key; };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n puts @hash_stack.inspect\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\nParamsTree::Parser.new.process \"default(all,usadasdid(zczxc(pio),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\n","old_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ])+ >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); p + 1 == pe and @hash[key] = {}; };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n puts @hash_stack.inspect\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\nParamsTree::Parser.new.process \"default(all,usadasdid(zczxc(pio),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e8707687b29321629b8586faf8959acc576ed9d5","subject":"add ability to escape slashes in cap_regex and match_regex","message":"add ability to escape slashes in cap_regex and match_regex\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/hext.rl","new_file":"src\/hext\/hext.rl","new_contents":"%%{\n machine hext;\n\n action error {\n throw_error();\n }\n\n nth_child = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( [^\/{}][^\/{}]** );\n match_literal = ( [^\/{}\"][^\/{}\"]** );\n cap_regex = ( ( [^\/] | '\\\\\/' )** );\n match_regex = ( ( [^\/] | '\\\\\/' )** );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n '@' >{ LX_TK_START(TK_BUILTIN); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_ATTR_NAME); }\n %{ LX_TK_STOP; }\n )\n <:\n (\n '='\n (\n (\n (\n '{' >{ LX_TK_START(TK_CAP_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n cap_var >{ LX_TK_START(TK_CAP_VAR); }\n %{ LX_TK_STOP; }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START(TK_CAP_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )?\n (\n '}' >{ LX_TK_START(TK_CAP_END); }\n %{ LX_TK_STOP; }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex >{ LX_TK_START(TK_MATCH_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )\n |\n (\n '\"'\n (\n match_literal >{ LX_TK_START(TK_MATCH_LITERAL); }\n %{ LX_TK_STOP; }\n )\n '\"'\n )\n )\n )\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' >{ LX_TK_START(TK_INDENT); }\n %{ LX_TK_STOP; }\n )*\n (\n '<' >{ LX_TK_START(TK_RULE_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n '!' >{ LX_TK_START(TK_DIRECT_DESC); }\n %{ LX_TK_STOP; }\n )?\n (\n nth_child >{ LX_TK_START(TK_NTH_CHILD); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_TAG_NAME); }\n %{ LX_TK_STOP; }\n )?\n attributes?\n (\n '>' >{ LX_TK_START(TK_RULE_END); }\n %{ LX_TK_STOP; }\n )?\n ):>\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n )**\n $err(error) $\/{ LX_TK_START(TK_EOF); fbreak; };\n}%%\n","old_contents":"%%{\n machine hext;\n\n action error {\n throw_error();\n }\n\n nth_child = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( [^\/{}][^\/{}]** );\n match_literal = ( [^\/{}\"][^\/{}\"]** );\n cap_regex = ( [^\/][^\/]** );\n match_regex = ( [^\/][^\/]** );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n '@' >{ LX_TK_START(TK_BUILTIN); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_ATTR_NAME); }\n %{ LX_TK_STOP; }\n )\n <:\n (\n '='\n (\n (\n (\n '{' >{ LX_TK_START(TK_CAP_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n cap_var >{ LX_TK_START(TK_CAP_VAR); }\n %{ LX_TK_STOP; }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START(TK_CAP_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )?\n (\n '}' >{ LX_TK_START(TK_CAP_END); }\n %{ LX_TK_STOP; }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex >{ LX_TK_START(TK_MATCH_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )\n |\n (\n '\"'\n (\n match_literal >{ LX_TK_START(TK_MATCH_LITERAL); }\n %{ LX_TK_STOP; }\n )\n '\"'\n )\n )\n )\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' >{ LX_TK_START(TK_INDENT); }\n %{ LX_TK_STOP; }\n )*\n (\n '<' >{ LX_TK_START(TK_RULE_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n '!' >{ LX_TK_START(TK_DIRECT_DESC); }\n %{ LX_TK_STOP; }\n )?\n (\n nth_child >{ LX_TK_START(TK_NTH_CHILD); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_TAG_NAME); }\n %{ LX_TK_STOP; }\n )?\n attributes?\n (\n '>' >{ LX_TK_START(TK_RULE_END); }\n %{ LX_TK_STOP; }\n )?\n ):>\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n )**\n $err(error) $\/{ LX_TK_START(TK_EOF); fbreak; };\n}%%\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"420f57fd5a99f2b8988bb00bf735b74c2c99b2f7","subject":"Interpret \/serviceValidate responses as UTF-8 codepoints.","message":"Interpret \/serviceValidate responses as UTF-8 codepoints.\n","repos":"NUBIC\/castanet","old_file":"lib\/castanet\/responses\/service_validate.rl","new_file":"lib\/castanet\/responses\/service_validate.rl","new_contents":"require 'castanet'\n\n%%{\n machine service_validate;\n\n action buffer { buffer << fc }\n action save_username { r.username = buffer; buffer = '' }\n action save_failure_code { r.failure_code = buffer; buffer = '' }\n action save_failure_reason { r.failure_reason = buffer.strip; buffer = '' }\n action save_pgt_iou { r.pgt_iou = buffer; buffer = '' }\n action set_authenticated { r.valid = true; eof = -1 }\n\n include common \"common.rl\";\n\n # Leaf tags\n # ---------\n\n code = ( ( upper | '_' ) @buffer )+ %save_failure_code;\n reason = ( xml_content @buffer )+ %save_failure_reason;\n pgt_iou = \"\"\n ( ticket_character @buffer ){,256}\n \"<\/cas:proxyGrantingTicket>\" %save_pgt_iou;\n user = \"\" ( xml_content @buffer )+ \"<\/cas:user>\" %save_username;\n\n # Non-leaf tags\n # -------------\n\n service_response_start = \"\";\n service_response_end = \"<\/cas:serviceResponse>\";\n\n authentication_failure_start = \"\";\n authentication_failure_end = \"<\/cas:authenticationFailure>\";\n\n authentication_success_start = \"\";\n authentication_success_end = \"<\/cas:authenticationSuccess>\";\n\n\n # Top-level elements\n # ------------------\n\n ok_cas_st = ( service_response_start\n space*\n authentication_success_start\n space*\n user\n space*\n pgt_iou?\n space*\n authentication_success_end\n space*\n service_response_end ) @set_authenticated;\n\n failed_cas_st = ( service_response_start\n space*\n authentication_failure_start\n reason\n authentication_failure_end\n space*\n service_response_end );\n\n main := ok_cas_st | failed_cas_st;\n}%%\n\nmodule Castanet::Responses\n class ServiceValidate\n ##\n # Whether or not this response passed CAS authentication.\n #\n # @return [Boolean]\n attr_accessor :valid\n\n alias_method :valid?, :valid\n\n ##\n # The failure code returned on authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_code\n\n ##\n # The reason given by the CAS server for authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_reason\n\n ##\n # The PGT IOU returned by an authentication success message.\n #\n # @return [String, nil]\n attr_accessor :pgt_iou\n\n ##\n # The name of the owner of the validated service or proxy ticket.\n #\n # This information is only present on authentication success.\n #\n # @return [String, nil]\n attr_accessor :username\n\n ##\n # Generates a {ServiceValidate} object from a CAS response.\n #\n # @param [String] response the CAS response\n # @return [ServiceValidate}\n def self.from_cas(response)\n data = response.strip.unpack('U*')\n buffer = ''\n eof = nil\n\n %% write init;\n\n new.tap do |r|\n %% write exec;\n end\n end\n\n def initialize\n self.valid = false\n end\n\n %% write data;\n end\nend\n","old_contents":"require 'castanet'\n\n%%{\n machine service_validate;\n\n action buffer { buffer << fc }\n action save_username { r.username = buffer; buffer = '' }\n action save_failure_code { r.failure_code = buffer; buffer = '' }\n action save_failure_reason { r.failure_reason = buffer.strip; buffer = '' }\n action save_pgt_iou { r.pgt_iou = buffer; buffer = '' }\n action set_authenticated { r.valid = true; eof = -1 }\n\n include common \"common.rl\";\n\n # Leaf tags\n # ---------\n\n code = ( ( upper | '_' ) @buffer )+ %save_failure_code;\n reason = ( xml_content @buffer )+ %save_failure_reason;\n pgt_iou = \"\"\n ( ticket_character @buffer ){,256}\n \"<\/cas:proxyGrantingTicket>\" %save_pgt_iou;\n user = \"\" ( xml_content @buffer )+ \"<\/cas:user>\" %save_username;\n\n # Non-leaf tags\n # -------------\n\n service_response_start = \"\";\n service_response_end = \"<\/cas:serviceResponse>\";\n\n authentication_failure_start = \"\";\n authentication_failure_end = \"<\/cas:authenticationFailure>\";\n\n authentication_success_start = \"\";\n authentication_success_end = \"<\/cas:authenticationSuccess>\";\n\n\n # Top-level elements\n # ------------------\n\n ok_cas_st = ( service_response_start\n space*\n authentication_success_start\n space*\n user\n space*\n pgt_iou?\n space*\n authentication_success_end\n space*\n service_response_end ) @set_authenticated;\n\n failed_cas_st = ( service_response_start\n space*\n authentication_failure_start\n reason\n authentication_failure_end\n space*\n service_response_end );\n\n main := ok_cas_st | failed_cas_st;\n}%%\n\nmodule Castanet::Responses\n class ServiceValidate\n ##\n # Whether or not this response passed CAS authentication.\n #\n # @return [Boolean]\n attr_accessor :valid\n\n alias_method :valid?, :valid\n\n ##\n # The failure code returned on authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_code\n\n ##\n # The reason given by the CAS server for authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_reason\n\n ##\n # The PGT IOU returned by an authentication success message.\n #\n # @return [String, nil]\n attr_accessor :pgt_iou\n\n ##\n # The name of the owner of the validated service or proxy ticket.\n #\n # This information is only present on authentication success.\n #\n # @return [String, nil]\n attr_accessor :username\n\n ##\n # Generates a {ServiceValidate} object from a CAS response.\n #\n # @param [String] response the CAS response\n # @return [ServiceValidate}\n def self.from_cas(response)\n data = response.strip.unpack('c*')\n buffer = ''\n eof = nil\n\n %% write init;\n\n new.tap do |r|\n %% write exec;\n end\n end\n\n def initialize\n self.valid = false\n end\n\n %% write data;\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"c8eb238f31972aa121ba65ac1be6548500cbb7fe","subject":"ifchd-parse: Simplify leftover-buffer copying.","message":"ifchd-parse: Simplify leftover-buffer copying.\n","repos":"niklata\/ndhc","old_file":"src\/ifchd-parse.rl","new_file":"src\/ifchd-parse.rl","new_contents":"\/* ifchd-parse.rl - interface change daemon parser\n *\n * Copyright 2004-2018 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n\n#include \"ifchd-parse.h\"\n#include \"ifchd.h\"\n#include \"ifset.h\"\n#include \"ndhc.h\"\n\n%%{\n machine ipv4set_parser;\n\n action XSt { arg_start = p; }\n action IpEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_addr) {\n have_ip = true;\n memcpy(ip4_addr, arg_start, (size_t)arg_len);\n }\n ip4_addr[arg_len] = 0;\n }\n action SnEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_subnet) {\n have_subnet = true;\n memcpy(ip4_subnet, arg_start, (size_t)arg_len);\n }\n ip4_subnet[arg_len] = 0;\n }\n action BcEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_bcast) {\n have_ip = true;\n memcpy(ip4_bcast, arg_start, (size_t)arg_len);\n }\n ip4_bcast[arg_len] = 0;\n }\n\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip4_nobc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn);\n ip4_bc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn) ','\n (v4addr > XSt % BcEn);\n main := (ip4_bc|ip4_nobc);\n}%%\n\n%% write data;\n\nstatic int perform_ip4set(const char buf[static 1], size_t len)\n{\n char ip4_addr[INET_ADDRSTRLEN];\n char ip4_subnet[INET_ADDRSTRLEN];\n char ip4_bcast[INET_ADDRSTRLEN];\n const char *p = buf;\n const char *pe = p + len;\n const char *eof = pe;\n const char *arg_start = p;\n int cs = 0;\n bool have_ip = false;\n bool have_subnet = false;\n bool have_bcast = false;\n\n %% write init;\n %% write exec;\n\n if (cs < ipv4set_parser_first_final) {\n log_line(\"%s: received invalid arguments\", __func__);\n return -1;\n }\n\n \/\/ These should never trigger because of the above check, but be safe...\n if (!have_ip) {\n log_line(\"%s: No IPv4 address specified.\", __func__);\n return -1;\n }\n if (!have_subnet) {\n log_line(\"%s: No IPv4 subnet specified.\", __func__);\n return -1;\n }\n\n return perform_ip_subnet_bcast(ip4_addr, ip4_subnet,\n have_bcast ? ip4_bcast : (char *)0);\n}\n\n%%{\n machine ifchd_parser;\n\n action Reset { cl.state = STATE_NOTHING; }\n action ArgSt { arg_start = p; }\n action ArgEn {\n ptrdiff_t al = p - arg_start;\n if (al < 0 || (size_t)al > sizeof tb - 1) {\n log_line(\"command argument would overflow\");\n return -99;\n }\n arg_len = (size_t)al;\n memcpy(tb, arg_start, arg_len);\n tb[arg_len] = 0;\n }\n\n action Dispatch {\n int pr = 0;\n switch (cl.state) {\n case STATE_IP4SET: pr = perform_ip4set(tb, arg_len); break;\n case STATE_TIMEZONE: pr = perform_timezone( tb, arg_len); break;\n case STATE_ROUTER: pr = perform_router(tb, arg_len); break;\n case STATE_DNS: pr = perform_dns(tb, arg_len); break;\n case STATE_LPRSVR: pr = perform_lprsvr(tb, arg_len); break;\n case STATE_HOSTNAME: pr = perform_hostname(tb, arg_len); break;\n case STATE_DOMAIN: pr = perform_domain(tb, arg_len); break;\n case STATE_IPTTL: pr = perform_ipttl(tb, arg_len); break;\n case STATE_MTU: pr = perform_mtu(tb, arg_len); break;\n case STATE_NTPSVR: pr = perform_ntpsrv(tb, arg_len); break;\n case STATE_WINS: pr = perform_wins(tb, arg_len); break;\n case STATE_CARRIER: pr = perform_carrier(); break;\n default:\n arg_len = 0;\n log_line(\"error: invalid state in dispatch_work\");\n return -99;\n }\n arg_len = 0;\n if (pr == -99)\n return -99;\n cmdf |= pr;\n }\n\n terminator = ';' > Dispatch;\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip_arg = (v4addr > ArgSt % ArgEn) terminator;\n ip4set_arg = (((v4addr ','){1,2} v4addr) > ArgSt % ArgEn) terminator;\n iplist_arg = (((v4addr ',')* v4addr) > ArgSt % ArgEn) terminator;\n str_arg = ([^;\\0]+ > ArgSt % ArgEn) terminator;\n s32_arg = (extend{4} > ArgSt % ArgEn) terminator;\n u16_arg = (extend{2} > ArgSt % ArgEn) terminator;\n u8_arg = (extend{1} > ArgSt % ArgEn) terminator;\n\n cmd_ip = ('routr:' % { cl.state = STATE_ROUTER; }) ip_arg;\n cmd_ip4set = ('ip4:' % { cl.state = STATE_IP4SET; }) ip4set_arg;\n cmd_iplist = ('dns:' % { cl.state = STATE_DNS; }\n |'lpr:' % { cl.state = STATE_LPRSVR; }\n |'ntp:' % { cl.state = STATE_NTPSVR; }\n |'wins:' % { cl.state = STATE_WINS; }\n ) iplist_arg;\n cmd_str = ('host:' % { cl.state = STATE_HOSTNAME; }\n |'dom:' % { cl.state = STATE_DOMAIN; }\n ) str_arg;\n cmd_s32 = ('tzone:' % { cl.state = STATE_TIMEZONE; }) s32_arg;\n cmd_u16 = ('mtu:' % { cl.state = STATE_MTU; }) u16_arg;\n cmd_u8 = ('ipttl:' % { cl.state = STATE_IPTTL; }) u8_arg;\n cmd_none = ('carrier:' % { cl.state = STATE_CARRIER; }) terminator;\n\n command = (cmd_ip|cmd_ip4set|cmd_iplist|cmd_str|cmd_s32|cmd_u16|cmd_u8|cmd_none);\n main := (command > Reset)+;\n}%%\n\n%% write data;\n\n\/*\n * Returns -99 on fatal error; that leads to peer connection being closed.\n * Returns -1 if one of the commands failed.\n * Returns 0 on success.\n *\/\nint execute_buffer(const char newbuf[static 1])\n{\n char buf[MAX_BUF * 2];\n char tb[MAX_BUF];\n int cmdf = 0;\n\n ssize_t buflen = snprintf(buf, sizeof buf, \"%s%s\", cl.ibuf, newbuf);\n if (buflen < 0) {\n log_line(\"%s: (%s) snprintf1 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)buflen >= sizeof buf) {\n log_line(\"%s: (%s) input is too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n\n const char *p = buf;\n const char *pe = p + strlen(buf);\n const char *arg_start = p;\n size_t arg_len = 0;\n int cs = 0;\n\n %% write init;\n %% write exec;\n\n if (p != pe) {\n ssize_t ilen = snprintf(cl.ibuf, sizeof cl.ibuf, \"%s\", p);\n if (ilen < 0) {\n log_line(\"%s: (%s) snprintf2 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)ilen >= sizeof buf) {\n log_line(\"%s: (%s) unconsumed input too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n }\n\n if (cs < ifchd_parser_first_final) {\n log_line(\"%s: ifch received invalid commands\",\n client_config.interface);\n return -99;\n }\n return !cmdf ? 0 : -1;\n}\n\n","old_contents":"\/* ifchd-parse.rl - interface change daemon parser\n *\n * Copyright 2004-2018 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n\n#include \"ifchd-parse.h\"\n#include \"ifchd.h\"\n#include \"ifset.h\"\n#include \"ndhc.h\"\n\n%%{\n machine ipv4set_parser;\n\n action XSt { arg_start = p; }\n action IpEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_addr) {\n have_ip = true;\n memcpy(ip4_addr, arg_start, (size_t)arg_len);\n }\n ip4_addr[arg_len] = 0;\n }\n action SnEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_subnet) {\n have_subnet = true;\n memcpy(ip4_subnet, arg_start, (size_t)arg_len);\n }\n ip4_subnet[arg_len] = 0;\n }\n action BcEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_bcast) {\n have_ip = true;\n memcpy(ip4_bcast, arg_start, (size_t)arg_len);\n }\n ip4_bcast[arg_len] = 0;\n }\n\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip4_nobc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn);\n ip4_bc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn) ','\n (v4addr > XSt % BcEn);\n main := (ip4_bc|ip4_nobc);\n}%%\n\n%% write data;\n\nstatic int perform_ip4set(const char buf[static 1], size_t len)\n{\n char ip4_addr[INET_ADDRSTRLEN];\n char ip4_subnet[INET_ADDRSTRLEN];\n char ip4_bcast[INET_ADDRSTRLEN];\n const char *p = buf;\n const char *pe = p + len;\n const char *eof = pe;\n const char *arg_start = p;\n int cs = 0;\n bool have_ip = false;\n bool have_subnet = false;\n bool have_bcast = false;\n\n %% write init;\n %% write exec;\n\n if (cs < ipv4set_parser_first_final) {\n log_line(\"%s: received invalid arguments\", __func__);\n return -1;\n }\n\n \/\/ These should never trigger because of the above check, but be safe...\n if (!have_ip) {\n log_line(\"%s: No IPv4 address specified.\", __func__);\n return -1;\n }\n if (!have_subnet) {\n log_line(\"%s: No IPv4 subnet specified.\", __func__);\n return -1;\n }\n\n return perform_ip_subnet_bcast(ip4_addr, ip4_subnet,\n have_bcast ? ip4_bcast : (char *)0);\n}\n\n%%{\n machine ifchd_parser;\n\n action Reset { cl.state = STATE_NOTHING; }\n action ArgSt { arg_start = p; }\n action ArgEn {\n ptrdiff_t al = p - arg_start;\n if (al < 0 || (size_t)al > sizeof tb - 1) {\n log_line(\"command argument would overflow\");\n return -99;\n }\n arg_len = (size_t)al;\n memcpy(tb, arg_start, arg_len);\n tb[arg_len] = 0;\n }\n\n action Dispatch {\n int pr = 0;\n switch (cl.state) {\n case STATE_IP4SET: pr = perform_ip4set(tb, arg_len); break;\n case STATE_TIMEZONE: pr = perform_timezone( tb, arg_len); break;\n case STATE_ROUTER: pr = perform_router(tb, arg_len); break;\n case STATE_DNS: pr = perform_dns(tb, arg_len); break;\n case STATE_LPRSVR: pr = perform_lprsvr(tb, arg_len); break;\n case STATE_HOSTNAME: pr = perform_hostname(tb, arg_len); break;\n case STATE_DOMAIN: pr = perform_domain(tb, arg_len); break;\n case STATE_IPTTL: pr = perform_ipttl(tb, arg_len); break;\n case STATE_MTU: pr = perform_mtu(tb, arg_len); break;\n case STATE_NTPSVR: pr = perform_ntpsrv(tb, arg_len); break;\n case STATE_WINS: pr = perform_wins(tb, arg_len); break;\n case STATE_CARRIER: pr = perform_carrier(); break;\n default:\n arg_len = 0;\n log_line(\"error: invalid state in dispatch_work\");\n return -99;\n }\n arg_len = 0;\n if (pr == -99)\n return -99;\n cmdf |= pr;\n }\n\n terminator = ';' > Dispatch;\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip_arg = (v4addr > ArgSt % ArgEn) terminator;\n ip4set_arg = (((v4addr ','){1,2} v4addr) > ArgSt % ArgEn) terminator;\n iplist_arg = (((v4addr ',')* v4addr) > ArgSt % ArgEn) terminator;\n str_arg = ([^;\\0]+ > ArgSt % ArgEn) terminator;\n s32_arg = (extend{4} > ArgSt % ArgEn) terminator;\n u16_arg = (extend{2} > ArgSt % ArgEn) terminator;\n u8_arg = (extend{1} > ArgSt % ArgEn) terminator;\n\n cmd_ip = ('routr:' % { cl.state = STATE_ROUTER; }) ip_arg;\n cmd_ip4set = ('ip4:' % { cl.state = STATE_IP4SET; }) ip4set_arg;\n cmd_iplist = ('dns:' % { cl.state = STATE_DNS; }\n |'lpr:' % { cl.state = STATE_LPRSVR; }\n |'ntp:' % { cl.state = STATE_NTPSVR; }\n |'wins:' % { cl.state = STATE_WINS; }\n ) iplist_arg;\n cmd_str = ('host:' % { cl.state = STATE_HOSTNAME; }\n |'dom:' % { cl.state = STATE_DOMAIN; }\n ) str_arg;\n cmd_s32 = ('tzone:' % { cl.state = STATE_TIMEZONE; }) s32_arg;\n cmd_u16 = ('mtu:' % { cl.state = STATE_MTU; }) u16_arg;\n cmd_u8 = ('ipttl:' % { cl.state = STATE_IPTTL; }) u8_arg;\n cmd_none = ('carrier:' % { cl.state = STATE_CARRIER; }) terminator;\n\n command = (cmd_ip|cmd_ip4set|cmd_iplist|cmd_str|cmd_s32|cmd_u16|cmd_u8|cmd_none);\n main := (command > Reset)+;\n}%%\n\n%% write data;\n\n\/*\n * Returns -99 on fatal error; that leads to peer connection being closed.\n * Returns -1 if one of the commands failed.\n * Returns 0 on success.\n *\/\nint execute_buffer(const char newbuf[static 1])\n{\n char buf[MAX_BUF * 2];\n char tb[MAX_BUF];\n int cmdf = 0;\n\n ssize_t buflen = snprintf(buf, sizeof buf, \"%s%s\", cl.ibuf, newbuf);\n if (buflen < 0) {\n log_line(\"%s: (%s) snprintf1 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)buflen >= sizeof buf) {\n log_line(\"%s: (%s) input is too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n\n size_t init_siz = strlen(buf);\n const char *p = buf;\n const char *pe = p + init_siz;\n const char *arg_start = p;\n size_t arg_len = 0;\n int cs = 0;\n\n %% write init;\n %% write exec;\n\n ptrdiff_t blt = pe - p;\n size_t bytes_left = blt >= 0 ? (size_t)blt : 0;\n if (bytes_left > 0) {\n size_t taken = init_siz - bytes_left;\n ssize_t ilen = snprintf(cl.ibuf, sizeof cl.ibuf, \"%s\", buf + taken);\n if (ilen < 0) {\n log_line(\"%s: (%s) snprintf2 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)ilen >= sizeof buf) {\n log_line(\"%s: (%s) unconsumed input too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n }\n\n if (cs < ifchd_parser_first_final) {\n log_line(\"%s: ifch received invalid commands\",\n client_config.interface);\n return -99;\n }\n return !cmdf ? 0 : -1;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"7f4e3e2aeb11d2b38d3e132ccd04ee7b6ae864a2","subject":"mark lex_error's single argument constructor explicit","message":"mark lex_error's single argument constructor explicit\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/lexer.rl","new_file":"src\/hext\/lexer.rl","new_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/lexer-util.h\"\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\nclass lexer\n{\npublic:\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg)\n : std::runtime_error(msg) {}\n };\n\n lexer(const char * begin, const char * end)\n : p_begin(begin),\n p(begin),\n pe(end),\n eof(end),\n cs(0)\n {\n using namespace ragel;\n %% write init;\n }\n\n std::vector lex()\n {\n using namespace ragel;\n\n std::vector tokens;\n\n \/\/ this throws on lexing error\n %% write exec;\n\n return tokens;\n }\n\n void throw_error() const\n {\n std::pair pos =\n get_char_position(this->p, this->p_begin, this->pe);\n\n std::string char_name;\n if( this->p == this->pe )\n {\n char_name = \"[eof]\";\n }\n else\n {\n if( this->p != nullptr )\n char_name = get_char_name(*this->p);\n else\n char_name = \"[unknown]\";\n }\n\n std::stringstream error_msg;\n error_msg << \"Error at line \"\n << pos.first + 1\n << \", char \"\n << pos.second + 1\n << \", unexpected character '\"\n << char_name\n << \"'\";\n\n throw lex_error(error_msg.str());\n }\n\nprivate:\n const char * p_begin;\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","old_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/lexer-util.h\"\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\nclass lexer\n{\npublic:\n class lex_error : public std::runtime_error\n {\n public:\n lex_error(const std::string& msg)\n : std::runtime_error(msg) {}\n };\n\n lexer(const char * begin, const char * end)\n : p_begin(begin),\n p(begin),\n pe(end),\n eof(end),\n cs(0)\n {\n using namespace ragel;\n %% write init;\n }\n\n std::vector lex()\n {\n using namespace ragel;\n\n std::vector tokens;\n\n \/\/ this throws on lexing error\n %% write exec;\n\n return tokens;\n }\n\n void throw_error() const\n {\n std::pair pos =\n get_char_position(this->p, this->p_begin, this->pe);\n\n std::string char_name;\n if( this->p == this->pe )\n {\n char_name = \"[eof]\";\n }\n else\n {\n if( this->p != nullptr )\n char_name = get_char_name(*this->p);\n else\n char_name = \"[unknown]\";\n }\n\n std::stringstream error_msg;\n error_msg << \"Error at line \"\n << pos.first + 1\n << \", char \"\n << pos.second + 1\n << \", unexpected character '\"\n << char_name\n << \"'\";\n\n throw lex_error(error_msg.str());\n }\n\nprivate:\n const char * p_begin;\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"30d3e455d18aa2ec09e486dc67e7a0c6e8bfd68d","subject":"Use squote\/dquote everywhere in the lexer.","message":"Use squote\/dquote everywhere in the lexer.\n","repos":"YorickPeterse\/oga,altmetric\/oga,YorickPeterse\/oga,YorickPeterse\/oga,dfockler\/oga,dfockler\/oga,altmetric\/oga,dfockler\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,altmetric\/oga,ttasanen\/oga,altmetric\/oga,dfockler\/oga,ttasanen\/oga,ttasanen\/oga,jeffreybaird\/oga,ttasanen\/oga,jeffreybaird\/oga,ttasanen\/oga,YorickPeterse\/oga,jeffreybaird\/oga,jeffreybaird\/oga,altmetric\/oga","old_file":"lib\/oga\/lexer.rl","new_file":"lib\/oga\/lexer.rl","new_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n private\n\n def advance_line\n @line += 1\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length)\n\n @tokens << token\n end\n\n def emit_text_buffer\n add_token(:T_TEXT, @text_buffer)\n\n @text_buffer = ''\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n action emit_space {\n t(:T_SPACE)\n }\n\n action emit_newline {\n t(:T_NEWLINE)\n advance_line\n }\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n advance_column\n fcall string_dquote;\n }\n\n action string_squote {\n advance_column\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fgoto main;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n\n t(:T_CDATA_END)\n\n fgoto main;\n };\n\n # Consume everything else character by character and store it in a\n # separate buffer.\n any => buffer_text;\n *|;\n\n main := |*\n whitespace => emit_space;\n newline => emit_newline;\n\n doctype_start => {\n t(:T_DOCTYPE_START)\n\n fgoto doctype;\n };\n\n # @cdata_buffer is used to store the content of the CDATA tag.\n cdata_start => {\n t(:T_CDATA_START)\n\n fgoto cdata;\n };\n\n # General rules and actions.\n '<' => { t(:T_SMALLER) };\n '>' => { t(:T_GREATER) };\n '\/' => { t(:T_SLASH) };\n '-' => { t(:T_DASH) };\n ']' => { t(:T_RBRACKET) };\n '[' => { t(:T_LBRACKET) };\n ':' => { t(:T_COLON) };\n '!' => { t(:T_BANG) };\n '=' => { t(:T_EQUALS) };\n\n dquote => { t(:T_DQUOTE) };\n squote => { t(:T_SQUOTE) };\n *|;\n }%%\n end # Lexer\nend # Oga\n","old_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n private\n\n def advance_line\n @line += 1\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length)\n\n @tokens << token\n end\n\n def emit_text_buffer\n add_token(:T_TEXT, @text_buffer)\n\n @text_buffer = ''\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n action emit_space {\n t(:T_SPACE)\n }\n\n action emit_newline {\n t(:T_NEWLINE)\n advance_line\n }\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n advance_column\n fcall string_dquote;\n }\n\n action string_squote {\n advance_column\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fgoto main;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n\n t(:T_CDATA_END)\n\n fgoto main;\n };\n\n # Consume everything else character by character and store it in a\n # separate buffer.\n any => buffer_text;\n *|;\n\n main := |*\n whitespace => emit_space;\n newline => emit_newline;\n\n doctype_start => {\n t(:T_DOCTYPE_START)\n\n fgoto doctype;\n };\n\n # @cdata_buffer is used to store the content of the CDATA tag.\n cdata_start => {\n t(:T_CDATA_START)\n\n fgoto cdata;\n };\n\n # General rules and actions.\n '<' => { t(:T_SMALLER) };\n '>' => { t(:T_GREATER) };\n '\/' => { t(:T_SLASH) };\n '\"' => { t(:T_DQUOTE) };\n \"'\" => { t(:T_SQUOTE) };\n '-' => { t(:T_DASH) };\n ']' => { t(:T_RBRACKET) };\n '[' => { t(:T_LBRACKET) };\n ':' => { t(:T_COLON) };\n '!' => { t(:T_BANG) };\n '=' => { t(:T_EQUALS) };\n *|;\n }%%\n end # Lexer\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"9975c9c430fb27afa75916b8a624eee1a865ce44","subject":"Removed the emit_text_buffer Ragel action.","message":"Removed the emit_text_buffer Ragel action.\n","repos":"ttasanen\/oga,altmetric\/oga,jeffreybaird\/oga,dfockler\/oga,jeffreybaird\/oga,YorickPeterse\/oga,ttasanen\/oga,altmetric\/oga,jeffreybaird\/oga,YorickPeterse\/oga,altmetric\/oga,YorickPeterse\/oga,ttasanen\/oga,YorickPeterse\/oga,altmetric\/oga,dfockler\/oga,dfockler\/oga,dfockler\/oga,altmetric\/oga,jeffreybaird\/oga,dfockler\/oga,ttasanen\/oga,YorickPeterse\/oga,ttasanen\/oga,jeffreybaird\/oga","old_file":"lib\/oga\/lexer.rl","new_file":"lib\/oga\/lexer.rl","new_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n attr_reader :html\n\n HTML_VOID_ELEMENTS = [\n 'area',\n 'base',\n 'br',\n 'col',\n 'command',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n ]\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize(options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n end\n\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n @elements = []\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n def html?\n return !!html\n end\n\n private\n\n def advance_line(amount = 1)\n @line += amount\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length) if value\n\n @tokens << token\n end\n\n def emit_text_buffer\n return if @text_buffer.empty?\n\n add_token(:T_TEXT, @text_buffer)\n\n lines = @text_buffer.count(\"\\n\")\n\n advance_line(lines) if lines > 0\n\n @text_buffer = ''\n end\n\n def buffer_text_until_eof(eof)\n @text_buffer << text\n\n emit_text_buffer if @te == eof\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n def current_element\n return @elements.last\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n fcall string_dquote;\n }\n\n action string_squote {\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n t(:T_CDATA_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the end\n # tag.\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences\n # would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n comment := |*\n comment_end => {\n emit_text_buffer\n t(:T_COMMENT_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and namespace\n # (if any). Remaining work is delegated to a dedicated machine.\n action open_element {\n emit_text_buffer\n add_token(:T_ELEM_OPEN, nil)\n advance_column\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(@ts + 1)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n\n # Advance the column for the colon (:) that separates the namespace\n # and element name.\n advance_column\n end\n\n @elements << name\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element;\n }\n\n element_name = [a-zA-Z0-9\\-_:]+;\n element_start = '<' element_name;\n\n element_text := |*\n ^'<' => {\n buffer_text_until_eof(eof)\n };\n\n '<' => {\n emit_text_buffer\n fhold;\n fret;\n };\n *|;\n\n element_closing_tag := |*\n whitespace => { advance_column };\n\n element_name => {\n emit_text_buffer\n add_token(:T_ELEM_CLOSE, nil)\n\n # Advance the column for the <\/\n advance_column(2)\n\n # Advance the column for the closing name.\n advance_column(text.length)\n\n fret;\n };\n\n '>' => { fret; };\n *|;\n\n element := |*\n whitespace => { advance_column };\n\n element_start => open_element;\n\n # Consume the text inside the element.\n '>' => {\n # If HTML lexing is enabled and we're in a void element we'll bail\n # out right away.\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_CLOSE, nil)\n @elements.pop\n end\n\n advance_column\n\n fcall element_text;\n };\n\n # Attributes and their values.\n element_name %{ t(:T_ATTR, @ts, p) }\n\n # The value of the attribute. Attribute values are not required. e.g.\n # in

<\/p> data-foo would be a boolean attribute.\n (\n '=' >{ advance_column }\n\n # The value of the attribute, wrapped in either single or double\n # quotes.\n (dquote @string_dquote | squote @string_squote)\n )*;\n\n # Non self-closing elements.\n '<\/' => {\n fcall element_closing_tag;\n\n @elements.pop\n\n fret;\n };\n\n # self-closing \/ void elements.\n '\/>' => {\n advance_column\n add_token(:T_ELEM_CLOSE, nil)\n\n @elements.pop\n\n fret;\n };\n *|;\n\n main := |*\n doctype_start => {\n emit_text_buffer\n t(:T_DOCTYPE_START)\n fcall doctype;\n };\n\n cdata_start => {\n emit_text_buffer\n t(:T_CDATA_START)\n fcall cdata;\n };\n\n comment_start => {\n emit_text_buffer\n t(:T_COMMENT_START)\n fcall comment;\n };\n\n element_start => open_element;\n\n any => {\n buffer_text_until_eof(eof)\n };\n *|;\n }%%\n end # Lexer\nend # Oga\n","old_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n attr_reader :html\n\n HTML_VOID_ELEMENTS = [\n 'area',\n 'base',\n 'br',\n 'col',\n 'command',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n ]\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize(options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n end\n\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n @elements = []\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n def html?\n return !!html\n end\n\n private\n\n def advance_line(amount = 1)\n @line += amount\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length) if value\n\n @tokens << token\n end\n\n def emit_text_buffer\n return if @text_buffer.empty?\n\n add_token(:T_TEXT, @text_buffer)\n\n lines = @text_buffer.count(\"\\n\")\n\n advance_line(lines) if lines > 0\n\n @text_buffer = ''\n end\n\n def buffer_text_until_eof(eof)\n @text_buffer << text\n\n emit_text_buffer if @te == eof\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n def current_element\n return @elements.last\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action emit_text_buffer {\n emit_text_buffer\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n fcall string_dquote;\n }\n\n action string_squote {\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n t(:T_CDATA_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the end\n # tag.\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences\n # would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n comment := |*\n comment_end => {\n emit_text_buffer\n t(:T_COMMENT_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and namespace\n # (if any). Remaining work is delegated to a dedicated machine.\n action open_element {\n add_token(:T_ELEM_OPEN, nil)\n advance_column\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(@ts + 1)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n\n # Advance the column for the colon (:) that separates the namespace\n # and element name.\n advance_column\n end\n\n @elements << name\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element;\n }\n\n element_name = [a-zA-Z0-9\\-_:]+;\n element_start = '<' element_name;\n\n element_text := |*\n ^'<' => {\n buffer_text_until_eof(eof)\n };\n\n '<' => {\n emit_text_buffer\n fhold;\n fret;\n };\n *|;\n\n element_closing_tag := |*\n whitespace => { advance_column };\n\n element_name => {\n emit_text_buffer\n add_token(:T_ELEM_CLOSE, nil)\n\n # Advance the column for the <\/\n advance_column(2)\n\n # Advance the column for the closing name.\n advance_column(text.length)\n\n fret;\n };\n\n '>' => { fret; };\n *|;\n\n element := |*\n whitespace => { advance_column };\n\n element_start => open_element;\n\n # Consume the text inside the element.\n '>' => {\n # If HTML lexing is enabled and we're in a void element we'll bail\n # out right away.\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_CLOSE, nil)\n @elements.pop\n end\n\n advance_column\n\n fcall element_text;\n };\n\n # Attributes and their values.\n element_name %{ t(:T_ATTR, @ts, p) }\n\n # The value of the attribute. Attribute values are not required. e.g.\n # in

<\/p> data-foo would be a boolean attribute.\n (\n '=' >{ advance_column }\n\n # The value of the attribute, wrapped in either single or double\n # quotes.\n (dquote @string_dquote | squote @string_squote)\n )*;\n\n # Non self-closing elements.\n '<\/' => {\n fcall element_closing_tag;\n\n @elements.pop\n\n fret;\n };\n\n # self-closing \/ void elements.\n '\/>' => {\n advance_column\n add_token(:T_ELEM_CLOSE, nil)\n\n @elements.pop\n\n fret;\n };\n *|;\n\n main := |*\n doctype_start @emit_text_buffer => {\n t(:T_DOCTYPE_START)\n fcall doctype;\n };\n\n cdata_start @emit_text_buffer => {\n t(:T_CDATA_START)\n fcall cdata;\n };\n\n comment_start @emit_text_buffer => {\n t(:T_COMMENT_START)\n fcall comment;\n };\n\n element_start @emit_text_buffer => open_element;\n\n any => {\n buffer_text_until_eof(eof)\n };\n *|;\n }%%\n end # Lexer\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"a55ca17f8f1fe5f04541504f7e7bd85c90ce0abc","subject":"allow either one of direct-desc or nth-child, not both (every nth-child is also a direct-desc)","message":"allow either one of direct-desc or nth-child, not both (every nth-child is also a direct-desc)\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/hext.rl","new_file":"src\/hext\/hext.rl","new_contents":"%%{\n machine hext;\n\n action error {\n this->throw_unexpected();\n }\n\n action act_newline {\n if( rule_start )\n {\n rule.consume_and_reset();\n rule_start = false;\n }\n else\n {\n rule.reset_indent();\n }\n }\n\n nth_child = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n builtin_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( [^\/{}][^\/{}]** );\n match_literal = ( [^\/{}\"][^\/{}\"]** );\n cap_regex = ( ( [^\/] | '\\\\\/' )** );\n match_regex = ( ( [^\/] | '\\\\\/' )** );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' %act_newline\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n (\n '@'\n (\n builtin_name\n >{ LX_TK_START; }\n %{ LX_TK_STOP;\n {\n bi::builtin_func_ptr bf = bi::get_builtin_by_name(tok);\n if( !bf ) this->throw_unknown_builtin(tok);\n rule.pattern().set_builtin_function(bf);\n }\n }\n )\n )\n |\n (\n attr_name >{ LX_TK_START; }\n %{ LX_TK_STOP; rule.pattern().set_attr_name(tok); }\n )\n )\n (\n '='\n (\n (\n '{'\n (\n cap_var >{ LX_TK_START; }\n %{ LX_TK_STOP; rule.pattern().set_cap_var(tok); }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.pattern().set_cap_regex(tok); }\n )\n '\/'\n )?\n (\n '}' %{ rule.consume_capture_pattern(); }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.pattern().set_attr_regex(tok);\n rule.consume_match_pattern(); }\n )\n '\/'\n )\n |\n (\n '\"'\n (\n match_literal >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.pattern().set_attr_literal(tok);\n rule.consume_match_pattern(); }\n )\n '\"'\n )\n )\n )\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' %{ rule.increment_indent(); }\n )*\n (\n '<' %{ rule_start = true; }\n )\n (\n (\n '!' %{ rule.set_direct_descendant(true); }\n )\n |\n (\n nth_child >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.set_nth_child(std::stoi(tok)); }\n )\n )?\n (\n attr_name >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.set_tag_name(tok); }\n )?\n attributes?\n (\n '>' %{ rule.set_closed(true); }\n )?\n ):>\n (\n '\\n' %act_newline\n )\n )**\n $err(error) $\/act_newline $\/{ fbreak; };\n}%%\n","old_contents":"%%{\n machine hext;\n\n action error {\n this->throw_unexpected();\n }\n\n action act_newline {\n if( rule_start )\n {\n rule.consume_and_reset();\n rule_start = false;\n }\n else\n {\n rule.reset_indent();\n }\n }\n\n nth_child = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n builtin_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( [^\/{}][^\/{}]** );\n match_literal = ( [^\/{}\"][^\/{}\"]** );\n cap_regex = ( ( [^\/] | '\\\\\/' )** );\n match_regex = ( ( [^\/] | '\\\\\/' )** );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' %act_newline\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n (\n '@'\n (\n builtin_name\n >{ LX_TK_START; }\n %{ LX_TK_STOP;\n {\n bi::builtin_func_ptr bf = bi::get_builtin_by_name(tok);\n if( !bf ) this->throw_unknown_builtin(tok);\n rule.pattern().set_builtin_function(bf);\n }\n }\n )\n )\n |\n (\n attr_name >{ LX_TK_START; }\n %{ LX_TK_STOP; rule.pattern().set_attr_name(tok); }\n )\n )\n (\n '='\n (\n (\n '{'\n (\n cap_var >{ LX_TK_START; }\n %{ LX_TK_STOP; rule.pattern().set_cap_var(tok); }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.pattern().set_cap_regex(tok); }\n )\n '\/'\n )?\n (\n '}' %{ rule.consume_capture_pattern(); }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.pattern().set_attr_regex(tok);\n rule.consume_match_pattern(); }\n )\n '\/'\n )\n |\n (\n '\"'\n (\n match_literal >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.pattern().set_attr_literal(tok);\n rule.consume_match_pattern(); }\n )\n '\"'\n )\n )\n )\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' %{ rule.increment_indent(); }\n )*\n (\n '<' %{ rule_start = true; }\n )\n (\n '!' %{ rule.set_direct_descendant(true); }\n )?\n (\n nth_child >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.set_nth_child(std::stoi(tok)); }\n )?\n (\n attr_name >{ LX_TK_START; }\n %{ LX_TK_STOP;\n rule.set_tag_name(tok); }\n )?\n attributes?\n (\n '>' %{ rule.set_closed(true); }\n )?\n ):>\n (\n '\\n' %act_newline\n )\n )**\n $err(error) $\/act_newline $\/{ fbreak; };\n}%%\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"75e3fba36187047e4502cdbac98cd593213ec215","subject":"More cleanup of the ragel file","message":"More cleanup of the ragel file","repos":"ged\/mongrel2,ged\/mongrel2,ged\/mongrel2,ged\/mongrel2","old_file":"examples\/kegogi\/src\/kegogi_lexer.rl","new_file":"examples\/kegogi\/src\/kegogi_lexer.rl","new_contents":"#include \"kegogi_tokens.h\"\n#include \"kegogi_parser.h\"\n\n#include \n\n#include \n#include \n\n%%{\n machine kegogi_lexer;\n defaults = 'defaults';\n send = 'send';\n expect = 'expect';\n\n comment = '#' [^\\n]*;\n\n action mark { m = fpc; }\n action s1 { s1 = blk2bstr(m, fpc-m); }\n action s2 { s2 = blk2bstr(m, fpc-m); }\n action s3 { s3 = blk2bstr(m, fpc-m); }\n\n ustring = (alpha (alnum | '-')*) >mark %s1;\n number = (digit+) >mark %s1;\n qstring = '\\\"' (([^\\\\\\\"] | ('\\\\' any))*) >mark %s1 '\\\"';\n pattern = '(' (([^\\\\)] | ('\\\\' any))*) >mark %s1 ')';\n dict_start = '{';\n dict_end = '}';\n equals = [:=];\n\n host = ([^\/:] - space)+ >mark %s2;\n uri = ('\/' (any - space)*) >mark %s1;\n port = digit+ >mark %s3;\n url = ((alpha+ ':\/\/')? host (':' port)?)? uri;\n \n newline = '\\n';\n\n main := |*\n defaults => {\n TokenList_append0(&token_list, TKDEFAULTS);\n s1 = s2 = s3 = NULL;\n };\n send => {\n TokenList_append0(&token_list, TKSEND);\n s1 = s2 = s3 = NULL;\n };\n expect => {\n TokenList_append0(&token_list, TKEXPECT);\n s1 = s2 = s3 = NULL;\n };\n (ustring|qstring) => {\n TokenList_append1(&token_list, TKSTRING, s1);\n s1 = s2 = s3 = NULL;\n };\n pattern => {\n TokenList_append1(&token_list, TKPATTERN, s1);\n s1 = s2 = s3 = NULL;\n };\n number => {\n TokenList_append1(&token_list, TKNUMBER, s1);\n s1 = s2 = s3 = NULL;\n };\n url => {\n TokenList_append3(&token_list, TKURL, s1, s2, s3);\n s1 = s2 = s3 = NULL;\n };\n newline => {\n TokenList_append0(&token_list, TKNEWLINE);\n s1 = s2 = s3 = NULL;\n };\n dict_start => {\n TokenList_append0(&token_list, TKDICT_START);\n s1 = s2 = s3 = NULL;\n };\n dict_end => {\n TokenList_append0(&token_list, TKDICT_END);\n s1 = s2 = s3 = NULL;\n };\n equals => {\n TokenList_append0(&token_list, TKEQUALS);\n s1 = s2 = s3 = NULL;\n };\n space => { };\n ',' => { };\n comment => { };\n *|;\n}%%\n\n%% write data;\n\nTokenList *get_kegogi_tokens(bstring content) {\n TokenList *token_list = TokenList_create(1024);\n check_mem(token_list);\n\n char *p = bdata(content);\n char *pe = p + blength(content);\n char *m = NULL;\n char *eof = pe;\n int cs = -1;\n int act = -1;\n char *ts = NULL;\n char *te = NULL;\n\n bstring s1 = NULL;\n bstring s2 = NULL;\n bstring s3 = NULL;\n\n %% write init;\n %% write exec;\n\n return token_list;\n\nerror:\n TokenList_destroy(token_list);\n return NULL;\n}","old_contents":"#include \"kegogi_tokens.h\"\n#include \"kegogi_parser.h\"\n\n#include \n\n#include \n#include \n\n%%{\n machine kegogi_lexer;\n defaults = 'defaults';\n send = 'send';\n expect = 'expect';\n\n comment = '#' [^\\n]*;\n\n action mark { m = fpc; }\n action s1 { s1 = blk2bstr(m, fpc-m); }\n action s2 { s2 = blk2bstr(m, fpc-m); }\n action s3 { s3 = blk2bstr(m, fpc-m); }\n\n ustring = (alpha (alnum | '-')*) >mark %s1;\n number = (digit+) >mark %s1;\n qstring = '\\\"' (([^\\\\\\\"] | ('\\\\' any))*) >mark %s1 '\\\"';\n pattern = '(' (([^\\\\)] | ('\\\\' any))*) >mark %s1 ')';\n dict_start = '{';\n dict_end = '}';\n equals = [:=];\n\n host = [^\/: ]+ >mark %s2;\n uri = ('\/' (any - space)*) >mark %s1;\n port = digit+ >mark %s3;\n url = ((alpha+ ':\/\/')? host (':' port)?)? uri;\n \n newline = '\\n';\n\n main := |*\n defaults => {\n TokenList_append0(&token_list, TKDEFAULTS);\n s1 = s2 = s3 = NULL;\n };\n send => {\n TokenList_append0(&token_list, TKSEND);\n s1 = s2 = s3 = NULL;\n };\n expect => {\n TokenList_append0(&token_list, TKEXPECT);\n s1 = s2 = s3 = NULL;\n };\n (ustring|qstring) => {\n TokenList_append1(&token_list, TKSTRING, s1);\n s1 = s2 = s3 = NULL;\n };\n pattern => {\n TokenList_append1(&token_list, TKPATTERN, s1);\n s1 = s2 = s3 = NULL;\n };\n number => {\n TokenList_append1(&token_list, TKNUMBER, s1);\n s1 = s2 = s3 = NULL;\n };\n url => {\n TokenList_append3(&token_list, TKURL, s1, s2, s3);\n s1 = s2 = s3 = NULL;\n };\n newline => {\n TokenList_append0(&token_list, TKNEWLINE);\n s1 = s2 = s3 = NULL;\n };\n dict_start => {\n TokenList_append0(&token_list, TKDICT_START);\n s1 = s2 = s3 = NULL;\n };\n dict_end => {\n TokenList_append0(&token_list, TKDICT_END);\n s1 = s2 = s3 = NULL;\n };\n equals => {\n TokenList_append0(&token_list, TKEQUALS);\n s1 = s2 = s3 = NULL;\n };\n space => { };\n ',' => { };\n comment => { };\n *|;\n}%%\n\n%% write data;\n\nTokenList *get_kegogi_tokens(bstring content) {\n TokenList *token_list = TokenList_create(1024);\n check_mem(token_list);\n\n char *p = bdata(content);\n char *pe = p + blength(content);\n char *m = NULL;\n char *eof = pe;\n int cs = -1;\n int act = -1;\n char *ts = NULL;\n char *te = NULL;\n\n bstring s1 = NULL;\n bstring s2 = NULL;\n bstring s3 = NULL;\n\n %% write init;\n %% write exec;\n\n return token_list;\n\nerror:\n TokenList_destroy(token_list);\n return NULL;\n}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"99475a1e07b14261dabb9d71b53814028da089c4","subject":"- remove the old ragel grammar","message":"- remove the old ragel grammar\n","repos":"opentable\/logstash-kafka,opentable\/logstash-kafka,tinglinux\/logstash-kafka,joekiller\/logstash-kafka,tinglinux\/logstash-kafka,Aloomaio\/logstash-kafka,joekiller\/logstash-kafka,Aloomaio\/logstash-kafka","old_file":"lib\/logstash\/config\/grammar.rl","new_file":"lib\/logstash\/config\/grammar.rl","new_contents":"","old_contents":"require \"logstash\/namespace\"\n\n%%{\n machine logstash_config;\n\n action mark {\n @tokenstack.push(p)\n #puts \"Mark: #{self.line(string, p)}##{self.column(string, p)}\"\n }\n\n action stack_numeric {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"numeric: #{token}\"\n #puts \"numeric?: #{string[startpos,50]}\"\n #puts [startpos, endpos].join(\",\")\n # TODO(sissel): Don't do 'to_i' here. Type coersion is the job of the\n # plugin and the validator.\n @stack << token.to_i\n }\n\n action stack_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"string: #{token}\"\n @stack << token\n }\n\n action stack_quoted_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos + 1 ... endpos - 1] # Skip quotations\n\n # Parse escapes.\n token.gsub(\/\\\\.\/) { |m| m[1,1] }\n #puts \"quotedstring: #{token}\"\n @stack << token\n }\n\n action array_init {\n @array = []\n @stack << :array_init\n }\n\n action array_push {\n while @stack.last != :array_init\n @array.unshift @stack.pop\n end\n @stack.pop # pop :array_init\n\n @stack << @array\n }\n\n action parameter_init {\n # nothing\n }\n\n action parameter {\n value = @stack.pop\n name = @stack.pop\n #puts \"parameter: #{name} => #{value}\"\n if value.is_a?(Array)\n @parameters[name] += value\n else\n @parameters[name] << value\n end\n }\n\n action plugin {\n @components ||= []\n name = @stack.pop\n #@components << { :name => name, :parameters => @parameters }\n @components << { name => @parameters }\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action component_init {\n @components = []\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action component {\n name = @stack.pop\n @config ||= Hash.new { |h,k| h[k] = [] }\n @config[name] += @components\n #puts \"Config component: #{name}\"\n }\n\n #%{ e = @tokenstack.pop; puts \"Comment: #{string[e ... p]}\" };\n comment = \"#\" (any - [\\r\\n])* >mark ; \n ws = ([ \\t\\r\\n] | comment)** ;\n #ws = ([ \\t\\n])** ;\n\n # TODO(sissel): Support floating point values?\n numeric = ( (\"+\" | \"-\")? [0-9] :>> [0-9]** ) >mark %stack_numeric;\n quoted_string = ( \n ( \"\\\"\" ( ( (any - [\\\\\"\\r\\n]) | \"\\\\\" any )* ) \"\\\"\" )\n | ( \"'\" ( ( (any - [\\\\'\\r\\n]) | \"\\\\\" any )* ) \"'\" ) \n ) >mark %stack_quoted_string ;\n naked_string = ( [A-Za-z_] :>> [A-Za-z0-9_]* ) >mark %stack_string ;\n string = ( quoted_string | naked_string ) ;\n\n # TODO(sissel): allow use of this.\n regexp_literal = ( \"\/\" ( ( (any - [\\\\'\\r\\n]) | \"\\\\\" any )* ) \"\/\" ) ;\n\n array = (\n ( \"[\" ( ws | \"\" ) \"]\" )\n | ( \"[\" ws ( string | numeric ) ws (\",\" ws (string | numeric ) ws)* \"]\" )\n ) >array_init %array_push;\n # TODO(sissel): Implement hash syntax { key => value, ... }\n # TODO(sissel): hashes should support arrays as values.\n\n parameter_value = ( numeric | string | array );\n parameter = ( string ws \"=>\" ws parameter_value ) %parameter ;\n parameters = ( parameter ( ws parameter )** ) >parameter_init ;\n\n # Statement:\n # component {\n # plugin_name {\n # bar => ...\n # baz => ...\n # }\n # ...\n # }\n\n plugin = (\n (\n naked_string ws \"{\" ws\n parameters\n ws \"}\"\n ) | ( \n naked_string ws \"{\" ws \"}\" \n )\n ) %plugin ; \n\n component = (\n naked_string ws \"{\"\n >component_init\n ( ws plugin )**\n ws \"}\"\n ) %component ;\n\n config = (ws component? )** ;\n\n main := config %{ puts \"END\" }\n $err { \n # Compute line and column of the cursor (p)\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n # TODO(sissel): Note what we were expecting?\n } ;\n}%%\n\nclass LogStash::Config::Grammar\n attr_accessor :eof\n attr_accessor :config\n\n def initialize\n # BEGIN RAGEL DATA\n %% write data;\n # END RAGEL DATA\n\n @tokenstack = Array.new\n @stack = Array.new\n\n @types = Hash.new { |h,k| h[k] = [] }\n @edges = []\n end\n\n def parse(string)\n # TODO(sissel): Due to a bug in my parser, we need one trailing whitespace\n # at the end of the string. I'll fix this later.\n string += \"\\n\"\n\n data = string.unpack(\"c*\")\n\n\n # BEGIN RAGEL INIT\n %% write init;\n # END RAGEL INIT\n\n begin \n # BEGIN RAGEL EXEC \n %% write exec;\n # END RAGEL EXEC\n rescue => e\n # Compute line and column of the cursor (p)\n raise e\n end\n\n if cs < self.logstash_config_first_final\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n raise \"Invalid Configuration. Check syntax of config file.\"\n end\n return cs\n end # def parse\n\n def line(str, pos)\n return str[0 .. pos].count(\"\\n\") + 1\n end\n\n def column(str, pos)\n return str[0 .. pos].split(\"\\n\").last.length\n end\nend # class LogStash::Config::Grammar\n\n#def parse(string)\n #cfgparser = LogStash::Config::Grammar.new\n #result = cfgparser.parse(string)\n #puts \"result %s\" % result\n #ap cfgparser.config\n#end\n\n#parse(File.open(ARGV[0]).read)\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"056c56f358e26979b358bc5a2a44ef6bc1de5c5c","subject":"Added send token. Got rid of util.h include","message":"Added send token. Got rid of util.h include","repos":"pjkundert\/mongrel2,ameuret\/mongrel2,dermoth\/mongrel2,elo80ka\/mongrel2,jasom\/mongrel2,ralphbean\/mongrel2,yoink00\/mongrel2,jablkopp\/mongrel2,elo80ka\/mongrel2,AlexVPopov\/mongrel2,chickenkiller\/mongrel2,jasom\/mongrel2,jagguli\/mongrel2,ralphbean\/mongrel2,bashi-bazouk\/mongrel2,niedbalski\/mongrel2,moai\/mongrel2,krakensden\/mongrel2,dermoth\/mongrel2,markokr\/mongrel2,AlexVPopov\/mongrel2,steamraven\/mongrel2,yoink00\/mongrel2,mongrel2\/mongrel2,elo80ka\/mongrel2,ralphbean\/mongrel2,rpeterson\/mongrel2,ameuret\/mongrel2,krakensden\/mongrel2,mongrel2\/mongrel2,fanout\/mongrel2,cpick\/mongrel2,minrk\/mongrel2,duaneg\/mongrel2,bashi-bazouk\/mongrel2,moai\/mongrel2,cpick\/mongrel2,rpeterson\/mongrel2,mbj\/mongrel2,apjanke\/mongrel2,jablkopp\/mongrel2,ralphbean\/mongrel2,jablkopp\/mongrel2,reshefm\/mongrel2,jagguli\/mongrel2,mongrel2\/mongrel2,xrl\/mongrel2,moai\/mongrel2,elo80ka\/mongrel2,bashi-bazouk\/mongrel2,nickdesaulniers\/mongrel2,cpick\/mongrel2,griffordson\/mongrel2,issuu\/mongrel2,AlexVPopov\/mongrel2,aidenkeating\/mongrel2,jablkopp\/mongrel2,griffordson\/mongrel2,dermoth\/mongrel2,pjkundert\/mongrel2,AvdN\/mongrel2,aidenkeating\/mongrel2,chickenkiller\/mongrel2,musl\/mongrel2,jdesgats\/mongrel2,niedbalski\/mongrel2,AvdN\/mongrel2,nickdesaulniers\/mongrel2,steamraven\/mongrel2,nickdesaulniers\/mongrel2,yoink00\/mongrel2,jasom\/mongrel2,mongrel2\/mongrel2,aidenkeating\/mongrel2,sshirokov\/mongrel2,AustinWise\/mongrel2,wayneeseguin\/mongrel2,fanout\/mongrel2,winks\/mongrel2,chickenkiller\/mongrel2,markokr\/mongrel2,krakensden\/mongrel2,jagguli\/mongrel2,fanout\/mongrel2,pjkundert\/mongrel2,winks\/mongrel2,aidenkeating\/mongrel2,issuu\/mongrel2,chickenkiller\/mongrel2,jasom\/mongrel2,ameuret\/mongrel2,markokr\/mongrel2,fanout\/mongrel2,issuu\/mongrel2,musl\/mongrel2,sshirokov\/mongrel2,griffordson\/mongrel2,metadave\/mongrel2,bashi-bazouk\/mongrel2,jagguli\/mongrel2,winks\/mongrel2,sshirokov\/mongrel2,dermoth\/mongrel2,jasom\/mongrel2,jablkopp\/mongrel2,apjanke\/mongrel2,wayneeseguin\/mongrel2,nickdesaulniers\/mongrel2,xrl\/mongrel2,jiffyjeff\/mongrel2,nmandery\/mongrel2,apjanke\/mongrel2,AvdN\/mongrel2,musl\/mongrel2,winks\/mongrel2,Gibheer\/mongrel2,ameuret\/mongrel2,jdesgats\/mongrel2,issuu\/mongrel2,musl\/mongrel2,aidenkeating\/mongrel2,jubarajborgohain\/mongrel2,steamraven\/mongrel2,chickenkiller\/mongrel2,moai\/mongrel2,jdesgats\/mongrel2,AustinWise\/mongrel2,bashi-bazouk\/mongrel2,AustinWise\/mongrel2,mbj\/mongrel2,msteinert\/mongrel2,markokr\/mongrel2,wayneeseguin\/mongrel2,nmandery\/mongrel2,fanout\/mongrel2,jiffyjeff\/mongrel2,jdesgats\/mongrel2,minrk\/mongrel2,steamraven\/mongrel2,reshefm\/mongrel2,duaneg\/mongrel2,nmandery\/mongrel2,ameuret\/mongrel2,xrl\/mongrel2,aidenkeating\/mongrel2,krakensden\/mongrel2,msteinert\/mongrel2,sshirokov\/mongrel2,jagguli\/mongrel2,jiffyjeff\/mongrel2,cpick\/mongrel2,elo80ka\/mongrel2,nickdesaulniers\/mongrel2,apjanke\/mongrel2,xrl\/mongrel2,xrl\/mongrel2,minrk\/mongrel2,wayneeseguin\/mongrel2,AustinWise\/mongrel2,yoink00\/mongrel2,krakensden\/mongrel2,AlexVPopov\/mongrel2,apjanke\/mongrel2,jubarajborgohain\/mongrel2,Gibheer\/mongrel2,minrk\/mongrel2,issuu\/mongrel2,jiffyjeff\/mongrel2,chickenkiller\/mongrel2,rpeterson\/mongrel2,reshefm\/mongrel2,cpick\/mongrel2,mbj\/mongrel2,markokr\/mongrel2,moai\/mongrel2,mongrel2\/mongrel2,AvdN\/mongrel2,AlexVPopov\/mongrel2,duaneg\/mongrel2,yoink00\/mongrel2,jubarajborgohain\/mongrel2,rpeterson\/mongrel2,mbj\/mongrel2,nmandery\/mongrel2,steamraven\/mongrel2,musl\/mongrel2,xrl\/mongrel2,ameuret\/mongrel2,pjkundert\/mongrel2,duaneg\/mongrel2,mongrel2\/mongrel2,msteinert\/mongrel2,griffordson\/mongrel2,metadave\/mongrel2,reshefm\/mongrel2,minrk\/mongrel2,pjkundert\/mongrel2,jiffyjeff\/mongrel2,jdesgats\/mongrel2,Gibheer\/mongrel2,metadave\/mongrel2,yoink00\/mongrel2,jubarajborgohain\/mongrel2,Gibheer\/mongrel2,niedbalski\/mongrel2,metadave\/mongrel2,niedbalski\/mongrel2,msteinert\/mongrel2,cpick\/mongrel2","old_file":"examples\/kegogi\/src\/kegogi_parser.rl","new_file":"examples\/kegogi\/src\/kegogi_parser.rl","new_contents":"#include \n#include \n\n#include \"kegogi_parser.h\"\n\n#include \n#include \"kegogi.h\"\n#include \"httpclient.h\"\n\n%%{\n machine kegogi;\n action command {\n if(idx < max_commands && uri != NULL && method != NULL) {\n host = host ? host : bstrcpy(default_host);\n\t int numPort = port ? atoi(bdata(port)) : default_port;\n\t if(port) bdestroy(port);\n\t Request *req = Request_create(host, numPort, method, uri);\n\t commands[idx++].request = req;\n }\n\telse\n\t printf(\"error\\n\");\n }\n\n action clear {\n method = NULL;\n \tport = NULL;\n\thost = NULL;\n\turi = NULL;\n }\n\n action mark {\n mark = fpc;\n }\n\n action method {\n method = blk2bstr(mark, fpc - mark);\n }\n\n action host {\n host = blk2bstr(mark, fpc - mark);\n }\n\n action port {\n port = blk2bstr(mark, fpc - mark);\n }\n\n action uri {\n uri = blk2bstr(mark, fpc - mark);\n }\n\n action status_code {\n status_code = atoin(mark, fpc - mark);\n } \n\n action param_name {\n param_name = blk2bstr(mark, fpc - mark);\n } \n\n action dictionary {\n\n }\n\n action pattern {\n pattern = blk2bstr(mark, fpc - mark);\n }\n\n\n ws = (space - '\\n')+;\n\n method = (upper | digit){1,20} >mark %method;\n\n protocol = alpha+ ':\/\/';\n host = ([^:\/]+) >mark %host;\n port = ':' (digit+) >mark %port;\n uri = ('\/' (^space)*) >mark %uri;\n\n url = ((protocol? host port?)? uri);\n \n comment = '#' [^\\n]*;\n\n command = (ws? \"send\" ws+ method ws+ url ws? comment? '\\n') >clear @command;\n empty_line = ws? comment? '\\n';\n \n main := (command | empty_line)*;\n}%%\n\n\n%% write data;\n\nint parse_kegogi_file(const char *path, Command commands[], int max_commands) {\n FILE *f = fopen(path, \"r\");\n fseek(f, 0L, SEEK_END);\n int size = ftell(f);\n fseek(f, 0L, SEEK_SET);\n char *buffer = malloc(size);\n fread(buffer, 1, size, f);\n\n int idx = 0;\n\n bstring default_host = bfromcstr(\"localhost\");\n int default_port = 80;\n\n bstring host, port, uri, method;\n char *mark, *p = buffer, *pe = buffer + size, *eof = pe;\n int cs;\n\n %% write init;\n %% write exec;\n\n return idx;\n}\n","old_contents":"#include \n#include \n\n#include \"kegogi_parser.h\"\n\n#include \n#include \"kegogi.h\"\n#include \"httpclient.h\"\n#include \"util.h\"\n\n%%{\n machine kegogi;\n action command {\n if(idx < max_commands && uri != NULL && method != NULL) {\n host = host ? host : bstrcpy(default_host);\n\t int numPort = port ? atoi(bdata(port)) : default_port;\n\t if(port) bdestroy(port);\n\t Request *req = Request_create(host, numPort, method, uri);\n\t commands[idx++].request = req;\n }\n\telse\n\t printf(\"error\\n\");\n }\n\n action clear {\n method = NULL;\n \tport = NULL;\n\thost = NULL;\n\turi = NULL;\n }\n\n action mark {\n mark = fpc;\n }\n\n action method {\n method = blk2bstr(mark, fpc - mark);\n }\n\n action host {\n host = blk2bstr(mark, fpc - mark);\n }\n\n action port {\n port = blk2bstr(mark, fpc - mark);\n }\n\n action uri {\n uri = blk2bstr(mark, fpc - mark);\n }\n\n action status_code {\n status_code = atoin(mark, fpc - mark);\n } \n\n action param_name {\n param_name = blk2bstr(mark, fpc - mark);\n } \n\n action dictionary {\n\n }\n\n action pattern {\n pattern = blk2bstr(mark, fpc - mark);\n }\n\n\n ws = (space - '\\n')+;\n\n method = (upper | digit){1,20} >mark %method;\n\n protocol = alpha+ ':\/\/';\n host = ([^:\/]+) >mark %host;\n port = ':' (digit+) >mark %port;\n uri = ('\/' (^space)*) >mark %uri;\n\n url = ((protocol? host port?)? uri);\n \n comment = '#' [^\\n]*;\n\n command = (ws? method ws url ws? comment? '\\n') >clear @command;\n empty_line = ws? comment? '\\n';\n \n main := (command | empty_line)*;\n}%%\n\n\n%% write data;\n\nint parse_kegogi_file(const char *path, Command commands[], int max_commands) {\n FILE *f = fopen(path, \"r\");\n fseek(f, 0L, SEEK_END);\n int size = ftell(f);\n fseek(f, 0L, SEEK_SET);\n char *buffer = malloc(size);\n fread(buffer, 1, size, f);\n\n int idx = 0;\n\n bstring default_host = bfromcstr(\"localhost\");\n int default_port = 80;\n\n bstring host, port, uri, method;\n char *mark, *p = buffer, *pe = buffer + size, *eof = pe;\n int cs;\n\n %% write init;\n %% write exec;\n\n return idx;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"85d1bab3aec60f591f320e4b55001c053b0234f4","subject":"SSA: Fix alignment without a text position.","message":"SSA: Fix alignment without a text position.\n","repos":"JanX2\/Perian,JanX2\/Perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,JanX2\/Perian,MaddTheSane\/perian,JanX2\/Perian,JanX2\/Perian,MaddTheSane\/perian,MaddTheSane\/perian","old_file":"SSATagParsing.m.rl","new_file":"SSATagParsing.m.rl","new_contents":"\/*\n * SSARenderCodec.m\n * Copyright (c) 2007 Perian Project\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"\\\"%@\\\", %d styles, %@\", nstext, style_count,\n\t\t (posx != 1) ? [NSString stringWithFormat:@\"pos (%d,%d)\",posx,posy] : [NSString stringWithFormat:@\"h %d v %d\", halign, valign]];\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nvoid SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\n\/\/not worth it\n\/*\nstatic void PruneIdenticalStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\t\n\tif (re->multipart_drawing || re->style_count <= 1) return;\n\n\tsize_t style_count_new = 1, remaining = re->style_count-1;\n\tint i=1;\n\t\n\t\n\tstyles_new[0] = re->styles[0];\n\t\n\twhile (remaining) {\n\t\tATSUStyleComparison asc;\n\t\tATSUCompareStyles(styles_new[style_count_new-1]->astyle,re->styles[i]->astyle,&asc);\n\t\t\n\t\tif (asc == kATSUStyleEquals) {\n styles_new[style_count_new-1]->range.length += re->styles[i]->range.length;\n\t\t\t[re->styles[i] release];\n re->styles[i] = nil;\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t\t\n\t\ti++;\n\t\tremaining--;\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n*\/\n\nstatic void UpdateAlignment(int inum, int cur_posx, int *valign, int *halign, ATSUTextLayout cur_layout)\n{\n\tint cur_halign, cur_valign;\n\t\n\tswitch (inum) \n\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\n\tswitch (inum)\n\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\n\t*halign = cur_halign;\n\t*valign = cur_valign;\n\tFract alignment;\n\t\n\tswitch(cur_halign) {\n\t\tcase S_LeftAlign:\n\t\t\talignment = FloatToFract(0.);\n\t\t\tbreak;\n\t\tcase S_CenterAlign: default:\n\t\t\talignment = kATSUCenterAlignment; \n\t\t\tbreak;\n\t\tcase S_RightAlign: \n\t\t\talignment = FloatToFract(1.);\n\t}\n\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i=0, j, pcount = 1; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\n\tfor (; i < pcount; i ++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:(ssa->collisiontype == NormalCollisions) ? i : (pcount - i - 1)]\n\t\t\t\t\t\t componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipart_drawing=NO;\n\t\tre->is_shape=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\tif (cur_range.length) {[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->angle = cur_frz;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;}\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin = p, *strbegin = p, *skipbegin = p, *intbegin = p, *pb = p, *posbegin=p, *strparambegin=p;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow, cur_scalex = re->style->scalex, cur_scaley = re->style->scaley, cur_frz=re->style->angle;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx=-1, cur_posy=-1;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\tCGAffineTransform matrix;\n\t\t\t\n\t\t\tunsigned long inum=0;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag=0, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {cur_frz = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tnum *= (72.\/96.); \/\/ scale from Windows 96dpi\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction ftrack {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUTrackingTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscalex {\n\t\t\t\t\tcur_scalex = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscaley {\n\t\t\t\t\tcur_scaley = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction strp_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(inum, cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\n\t\t\t\taction ssa_alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\n\t\t\t\t\tUpdateAlignment(SSA2ASSAlignment(inum), cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondarycolor {\n\t\t\t\t\tcur_color.secondary = ParseColorTag(inum,cur_color.secondary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primaryalpha {\n\t\t\t\t\tcur_color.primary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondaryalpha {\n\t\t\t\t\tcur_color.secondary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinealpha {\n\t\t\t\t\tcur_color.outline.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowalpha {\n\t\t\t\t\tcur_color.shadow.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tNSString *append = @\"\\n\";\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\tif (*(p - 1) == 'h') append = @\" \";\n \n\t\t\t\t\t[output appendString:append];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tunsigned taglen = p - skipbegin;\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:taglen];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n \n if (cur_range.length) {\n [re increasestyles];\n re->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n re->styles[re->style_count-1]->outline = cur_outline;\n re->styles[re->style_count-1]->shadow = cur_shadow;\n re->styles[re->style_count-1]->angle = cur_frz;\n re->styles[re->style_count-1]->astyle = cur_style;\n re->styles[re->style_count-1]->range = cur_range;\n re->styles[re->style_count-1]->outlineblur = cur_be;\n re->styles[re->style_count-1]->color = cur_color;\n ATSUCreateAndCopyStyle(cur_style,&cur_style);\n }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\t\/\/ XXX exit_tag ideally should run one char later, so we just pretend it does\n\t\t\t\t\tp++;\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n \n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[[SSARenderEntity alloc] init] autorelease];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipart_drawing = NO;\n\t\t\t\t\t\tnre->is_shape = re->is_shape;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction styleset {\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t\tssastyleline *the_style = re->style;\n\t\t\t\t\tNSString *searchsn = [NSString stringWithCharacters:strparambegin length:p-strparambegin];\n\t\t\t\t\t\n\t\t\t\t\tif ([searchsn length] > 0) {\n\t\t\t\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\t\t\t\tif ([searchsn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\t\t\t\tthe_style = &ssa->styles[j]; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tATSUCopyAttributes(the_style->atsustyle,cur_style);\n\t\t\t\t\tcur_color = the_style->color;\n\t\t\t\t\tcur_outline = the_style->outline;\n\t\t\t\t\tcur_shadow = the_style->shadow;\n\t\t\t\t\tcur_frz = the_style->angle;\n\t\t\t\t\tcur_scalex = cur_scaley = 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction skip_t_tag {\n\t\t\t\t\twhile (p != pe && *p != ')' && *p != '}') p++;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction draw_mode {\n\t\t\t\t\tre->is_shape = inum != 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (fl == '0' || fl == '1') flag = fl - '0';})? > {flag = 0;};\n\t\t\t\tnum_ = \"-\"? digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = \"-\"? (digit+) > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|\"fsp\" num %ftrack\n\t\t\t\t\t\t\t\t|\"fscx\" num %fscalex\n\t\t\t\t\t\t\t\t|\"fscy\" num %fscaley\n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > strp_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"a\" intnum %ssa_alignment\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"1c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"2c\" color %secondarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t|(\"1a\"|\"alpha\") color %primaryalpha\n\t\t\t\t\t\t\t\t|\"2a\" color %secondaryalpha\n\t\t\t\t\t\t\t\t|\"3a\" color %outlinealpha\n\t\t\t\t\t\t\t\t|\"4a\" color %shadowalpha\n\t\t\t\t\t\t\t\t|(\"r\" [^\\\\}]* > strp_begin %styleset)\n\t\t\t\t\t\t\t\t|(\"fe\"|\"k\"|\"kf\"|\"K\"|\"ko\"|\"q\"|\"fr\"|\"fad\"|\"move\"|\"clip\"|\"o\"|\"frx\"|\"fry\") [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"p\" num %draw_mode\n\t\t\t\t\t\t\t\t#|\"t\" [^)}]* # enabling this crashes ragel\n\t\t\t\t\t\t\t\t|\"t(\" % skip_t_tag\n\t\t\t\t\t\t\t\t|\"\"\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = (\"\\\\\" :> cmd_specific)+;\n\t\t\t\t\n\t\t\t\tplaintext = [^}]*;\n\n\t\t\t\ttag = \"{\" (cmd | plaintext) % exit_tag \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nnh];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | (tag > enter_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (pb[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\t\t\tif (!cur_range.length) ATSUDisposeStyle(cur_style);\n \/\/PruneIdenticalStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\treturn rentities;\n}\n","old_contents":"\/*\n * SSARenderCodec.m\n * Copyright (c) 2007 Perian Project\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"\\\"%@\\\", %d styles, %@\", nstext, style_count,\n\t\t (posx != 1) ? [NSString stringWithFormat:@\"pos (%d,%d)\",posx,posy] : [NSString stringWithFormat:@\"h %d v %d\", halign, valign]];\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nvoid SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\n\/\/not worth it\n\/*\nstatic void PruneIdenticalStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\t\n\tif (re->multipart_drawing || re->style_count <= 1) return;\n\n\tsize_t style_count_new = 1, remaining = re->style_count-1;\n\tint i=1;\n\t\n\t\n\tstyles_new[0] = re->styles[0];\n\t\n\twhile (remaining) {\n\t\tATSUStyleComparison asc;\n\t\tATSUCompareStyles(styles_new[style_count_new-1]->astyle,re->styles[i]->astyle,&asc);\n\t\t\n\t\tif (asc == kATSUStyleEquals) {\n styles_new[style_count_new-1]->range.length += re->styles[i]->range.length;\n\t\t\t[re->styles[i] release];\n re->styles[i] = nil;\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t\t\n\t\ti++;\n\t\tremaining--;\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n*\/\n\nstatic void UpdateAlignment(int inum, int cur_posx, int *valign, int *halign, ATSUTextLayout cur_layout)\n{\n\tint cur_halign, cur_valign;\n\t\n\tswitch (inum) \n\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\n\tswitch (inum)\n\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\n\t*halign = cur_halign;\n\t*valign = cur_valign;\n\tFract alignment;\n\t\n\tif (cur_posx != -1) {\n\t\tswitch(cur_halign) {\n\t\t\tcase S_LeftAlign:\n\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\tbreak;\n\t\t\tcase S_CenterAlign: default:\n\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\tbreak;\n\t\t\tcase S_RightAlign: \n\t\t\t\talignment = FloatToFract(1.);\n\t\t}\n\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t} \n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i=0, j, pcount = 1; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\n\tfor (; i < pcount; i ++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:(ssa->collisiontype == NormalCollisions) ? i : (pcount - i - 1)]\n\t\t\t\t\t\t componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipart_drawing=NO;\n\t\tre->is_shape=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\tif (cur_range.length) {[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->angle = cur_frz;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;}\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin = p, *strbegin = p, *skipbegin = p, *intbegin = p, *pb = p, *posbegin=p, *strparambegin=p;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow, cur_scalex = re->style->scalex, cur_scaley = re->style->scaley, cur_frz=re->style->angle;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx=-1, cur_posy=-1;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\tCGAffineTransform matrix;\n\t\t\t\n\t\t\tunsigned long inum=0;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag=0, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {cur_frz = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tnum *= (72.\/96.); \/\/ scale from Windows 96dpi\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction ftrack {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUTrackingTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscalex {\n\t\t\t\t\tcur_scalex = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscaley {\n\t\t\t\t\tcur_scaley = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction strp_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(inum, cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\n\t\t\t\taction ssa_alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\n\t\t\t\t\tUpdateAlignment(SSA2ASSAlignment(inum), cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondarycolor {\n\t\t\t\t\tcur_color.secondary = ParseColorTag(inum,cur_color.secondary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primaryalpha {\n\t\t\t\t\tcur_color.primary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondaryalpha {\n\t\t\t\t\tcur_color.secondary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinealpha {\n\t\t\t\t\tcur_color.outline.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowalpha {\n\t\t\t\t\tcur_color.shadow.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tNSString *append = @\"\\n\";\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\tif (*(p - 1) == 'h') append = @\" \";\n \n\t\t\t\t\t[output appendString:append];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tunsigned taglen = p - skipbegin;\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:taglen];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n \n if (cur_range.length) {\n [re increasestyles];\n re->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n re->styles[re->style_count-1]->outline = cur_outline;\n re->styles[re->style_count-1]->shadow = cur_shadow;\n re->styles[re->style_count-1]->angle = cur_frz;\n re->styles[re->style_count-1]->astyle = cur_style;\n re->styles[re->style_count-1]->range = cur_range;\n re->styles[re->style_count-1]->outlineblur = cur_be;\n re->styles[re->style_count-1]->color = cur_color;\n ATSUCreateAndCopyStyle(cur_style,&cur_style);\n }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\t\/\/ XXX exit_tag ideally should run one char later, so we just pretend it does\n\t\t\t\t\tp++;\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n \n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[[SSARenderEntity alloc] init] autorelease];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipart_drawing = NO;\n\t\t\t\t\t\tnre->is_shape = re->is_shape;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction styleset {\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t\tssastyleline *the_style = re->style;\n\t\t\t\t\tNSString *searchsn = [NSString stringWithCharacters:strparambegin length:p-strparambegin];\n\t\t\t\t\t\n\t\t\t\t\tif ([searchsn length] > 0) {\n\t\t\t\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\t\t\t\tif ([searchsn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\t\t\t\tthe_style = &ssa->styles[j]; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tATSUCopyAttributes(the_style->atsustyle,cur_style);\n\t\t\t\t\tcur_color = the_style->color;\n\t\t\t\t\tcur_outline = the_style->outline;\n\t\t\t\t\tcur_shadow = the_style->shadow;\n\t\t\t\t\tcur_frz = the_style->angle;\n\t\t\t\t\tcur_scalex = cur_scaley = 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction skip_t_tag {\n\t\t\t\t\twhile (p != pe && *p != ')' && *p != '}') p++;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction draw_mode {\n\t\t\t\t\tre->is_shape = inum != 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (fl == '0' || fl == '1') flag = fl - '0';})? > {flag = 0;};\n\t\t\t\tnum_ = \"-\"? digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = \"-\"? (digit+) > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|\"fsp\" num %ftrack\n\t\t\t\t\t\t\t\t|\"fscx\" num %fscalex\n\t\t\t\t\t\t\t\t|\"fscy\" num %fscaley\n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > strp_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"a\" intnum %ssa_alignment\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"1c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"2c\" color %secondarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t|(\"1a\"|\"alpha\") color %primaryalpha\n\t\t\t\t\t\t\t\t|\"2a\" color %secondaryalpha\n\t\t\t\t\t\t\t\t|\"3a\" color %outlinealpha\n\t\t\t\t\t\t\t\t|\"4a\" color %shadowalpha\n\t\t\t\t\t\t\t\t|(\"r\" [^\\\\}]* > strp_begin %styleset)\n\t\t\t\t\t\t\t\t|(\"fe\"|\"k\"|\"kf\"|\"K\"|\"ko\"|\"q\"|\"fr\"|\"fad\"|\"move\"|\"clip\"|\"o\"|\"frx\"|\"fry\") [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"p\" num %draw_mode\n\t\t\t\t\t\t\t\t#|\"t\" [^)}]* # enabling this crashes ragel\n\t\t\t\t\t\t\t\t|\"t(\" % skip_t_tag\n\t\t\t\t\t\t\t\t|\"\"\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = (\"\\\\\" :> cmd_specific)+;\n\t\t\t\t\n\t\t\t\tplaintext = [^}]*;\n\n\t\t\t\ttag = \"{\" (cmd | plaintext) % exit_tag \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nnh];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | (tag > enter_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (pb[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\t\t\tif (!cur_range.length) ATSUDisposeStyle(cur_style);\n \/\/PruneIdenticalStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\treturn rentities;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"5f54040ae9df381f377cf9bab83f31cdc05f649a","subject":"[OHCOUNT-15, OHCOUNT-16] Addressed code review comments","message":"[OHCOUNT-15, OHCOUNT-16] Addressed code review comments\n","repos":"mpujari\/ohcount4j,blackducksoftware\/ohcount4j,mpujari\/ohcount4j,blackducksoftware\/ohcount4j,blackducksoftware\/ohcount4j,mpujari\/ohcount4j,mpujari\/ohcount4j,mpujari\/ohcount4j,blackducksoftware\/ohcount4j,mpujari\/ohcount4j,blackducksoftware\/ohcount4j","old_file":"src\/scanners\/ragel\/BfkScanner.java.rl","new_file":"src\/scanners\/ragel\/BfkScanner.java.rl","new_contents":"package net.ohloh.ohcount4j.scan;\n\npublic class BfkScanner extends BaseScanner{\n\n\t%%{\n\t\tmachine bfk;\n\t\tinclude common \"common.rl\";\n\t\t\n\t\tbfk_operator = [+\\-<>.,\\[\\]] @code;\n\t\t\n\t\tbfk_line := |*\n \t\tspaces;\n \t\tnewline;\n \t\tbfk_operator => code;\n \t\t^space => comment;\n \t\t*|;\n\t\t\n\t}%%\n\t\n\t%% write data;\n\t\n\t@Override\n\tpublic void doScan(){\n\t\t\/\/ variables and data is set up in BaseScanner\n\t\t%% write init;\n\t\tinit();\n\t\t%% write exec;\n\t}\n}","old_contents":"package net.ohloh.ohcount4j.scan;\n\npublic class BfkScanner extends BaseScanner{\n\n\t%%{\n\t\tmachine brainfuck;\n\t\tinclude common \"common.rl\";\n\t\t\n\t\tbrainfuck_operator = [+\\-<>.,\\[\\]] @code;\n\t\t\n\t\tbrainfuck_line := |*\n \t\tspaces;\n \t\tnewline;\n \t\tbrainfuck_operator => code;\n \t\t^space => comment;\n \t\t*|;\n\t\t\n\t}%%\n\t\n\t%% write data;\n\t\n\t@Override\n\tpublic void doScan(){\n\t\t\/\/ variables and data is set up in BaseScanner\n\t\t%% write init;\n\t\tinit();\n\t\t%% write exec;\n\t}\n}","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"b5dd3690ce40c4783b0f4d7ec6e7a8c78308e733","subject":"Ragel: refactoring","message":"Ragel: refactoring\n","repos":"CuppenResearch\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf,pjotrp\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Parser for VCF-header info and format fields\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action endquoted {\n emit.call(:value,data,ts,p)\n }\n\n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %endquoted squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %endquoted dquote;\n\n integer = ('+'|'-')?digit+;\n float = ('+'|'-')?digit+'.'digit+;\n assignment = '=';\n identifier = (alpha alnum+); \n str = (ss|dd)* ; \n boolean = '.';\n key_word = ( ('ID'|'Number'|'Type'|'Description') >mark %{ emit.call(:key_word,data,ts,p) } );\n value = ( (integer|float|boolean|identifier|str) >mark %{ emit.call(:value,data,ts,p) } );\n\n key_value = ( key_word '=' value ) ;\n \n main := ('##FORMAT'|'##INFO') '=' (('<'|',') key_value )*;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef self.run_lexer(data, options = {})\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n values = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\" if options[:debug]==true\n values << [type,data[ts...p].pack('c*')]\n }\n\n %% write init;\n %% write exec;\n\n values.each do | v |\n p v\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s|\n p s\n VcfHeader::RagelKeyValues.run_lexer(s, debug: false)\n}\n\nend","old_contents":"# Parser for VCF-header info and format fields\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action endquoted {\n quoted_text = data[ts...p].pack('c*')\n # do something with the quoted text!\n emit.call(:value,data,ts,p)\n }\n\n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %endquoted squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %endquoted dquote;\n\n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = ([a-zA-Z][a-zA-Z_0-9]+); \n str = (ss|dd)* ; \n boolean = '.';\n key_word = ( ('ID'|'Number'|'Type'|'Description') >mark %{ emit.call(:key_word,data,ts,p) } );\n value = ( (integer|float|boolean|identifier|str) >mark %{ emit.call(:value,data,ts,p) } );\n\n key_value = ( key_word '=' value ) ;\n \n main := ('##FORMAT'|'##INFO') '=' (('<'|',') key_value )*;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef self.run_lexer(data, options = {})\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n values = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\" if options[:debug]==true\n values << [type,data[ts...p].pack('c*')]\n }\n\n %% write init;\n %% write exec;\n\n values.each do | v |\n p v\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s|\n p s\n VcfHeader::RagelKeyValues.run_lexer(s, debug: false)\n}\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e640bafc78580a3a86e7d57e1f2bff0a7e89a7c9","subject":"set wrong print routine for OP_PUTA","message":"set wrong print routine for OP_PUTA\n","repos":"wahern\/dns,wahern\/dns","old_file":"src\/spf.rl","new_file":"src\/spf.rl","new_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (spf_unlikely(SPF_DEBUG > 0)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#if __GNUC__ >= 3\n#define spf_likely(e)\t__builtin_expect((e), 1)\n#define spf_unlikely(e)\t__builtin_expect((e), 0)\n#else\n#define spf_likely(e)\t(e)\n#define spf_unlikely(e)\t(e)\n#endif\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (spf_unlikely(!(cond))) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic inline void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic inline int vm_indexof(struct spf_vm *vm, int p) {\n\tif (spf_likely(p < 0))\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic inline enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic inline intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic inline intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic inline intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic inline intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic inline int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puta, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (spf_unlikely(SPF_DEBUG >= 2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tcontinue;\n\t\t\t\tsub_emit(&sub, code);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t}\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","old_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (spf_unlikely(SPF_DEBUG > 0)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#if __GNUC__ >= 3\n#define spf_likely(e)\t__builtin_expect((e), 1)\n#define spf_unlikely(e)\t__builtin_expect((e), 0)\n#else\n#define spf_likely(e)\t(e)\n#define spf_unlikely(e)\t(e)\n#endif\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (spf_unlikely(!(cond))) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic inline void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic inline int vm_indexof(struct spf_vm *vm, int p) {\n\tif (spf_likely(p < 0))\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic inline enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic inline intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic inline intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic inline intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic inline intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic inline int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puti, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (spf_unlikely(SPF_DEBUG >= 2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tcontinue;\n\t\t\t\tsub_emit(&sub, code);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t}\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"51bfe9aba3b1f692431816a4d08b9eaaaab5bdf8","subject":"remove commented out print","message":"remove commented out print\n","repos":"diku-kmc\/repg,diku-kmc\/repg,diku-kmc\/kleenexlang,diku-kmc\/kleenexlang,diku-kmc\/repg,diku-kmc\/kleenexlang,diku-kmc\/repg,diku-kmc\/kleenexlang,diku-kmc\/repg,diku-kmc\/repg,diku-kmc\/kleenexlang,diku-kmc\/kleenexlang","old_file":"bench\/ragel\/src\/csv_project3.rl","new_file":"bench\/ragel\/src\/csv_project3.rl","new_contents":"#include \"..\/common.h\"\n\n#define P(C) fputs(C, stdout);\n\nint echo = 0;\n\n%%{\n machine csv_project3;\n\n action echo_on { echo = 1; }\n action echo_off { echo = 0; }\n action dump {\n if(echo) {\n fprintf(stdout, \"%c\", fc);\n }\n }\n\n col = [^,\\n]*;\n dropCol = col > echo_off;\n keepCol = col > echo_on % echo_off;\n row = dropCol ','\n keepCol ',' > { P(\"\\t\") }\n dropCol ','\n dropCol ','\n keepCol ','\n dropCol;\n csvProj3 = (row '\\n' > { P(\"\\n\") })*;\n\n main := csvProj3 $ dump;\n}%%\n\n%% write data;\n\n\nint main(int argc, char **argv) {\n\n PRE;\n\n while(fgets(buffer, sizeof(buffer), stdin)) {\n INIT_LINE;\n %% write init;\n %% write exec;\n\n if(p != pe) {\n FAIL;\n }\n }\n\n POST;\n\n return 0;\n}\n","old_contents":"#include \"..\/common.h\"\n\n#define P(C) fputs(C, stdout);\n\nint echo = 0;\n\n%%{\n machine csv_project3;\n\n action echo_on { echo = 1; }\n action echo_off { echo = 0; }\n action dump {\n if(echo) {\n \/\/ fprintf(stdout, \"%.*s\", 1, &fc);\n fprintf(stdout, \"%c\", fc);\n }\n }\n\n col = [^,\\n]*;\n dropCol = col > echo_off;\n keepCol = col > echo_on % echo_off;\n row = dropCol ','\n keepCol ',' > { P(\"\\t\") }\n dropCol ','\n dropCol ','\n keepCol ','\n dropCol;\n csvProj3 = (row '\\n' > { P(\"\\n\") })*;\n\n main := csvProj3 $ dump;\n}%%\n\n%% write data;\n\n\nint main(int argc, char **argv) {\n\n PRE;\n\n while(fgets(buffer, sizeof(buffer), stdin)) {\n INIT_LINE;\n %% write init;\n %% write exec;\n\n if(p != pe) {\n FAIL;\n }\n }\n\n POST;\n\n return 0;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"2b3a6be24d71ac722ab87ada54f1860cf64cc290","subject":"Use liboga as a prefix in the C code.","message":"Use liboga as a prefix in the C code.\n\nNamespaces? What are those?\n","repos":"YorickPeterse\/oga,ttasanen\/oga,YorickPeterse\/oga,ttasanen\/oga,jeffreybaird\/oga,ttasanen\/oga,jeffreybaird\/oga,jeffreybaird\/oga,ttasanen\/oga,YorickPeterse\/oga,altmetric\/oga,YorickPeterse\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,jeffreybaird\/oga,altmetric\/oga,dfockler\/oga,altmetric\/oga,dfockler\/oga,dfockler\/oga,altmetric\/oga,altmetric\/oga,dfockler\/oga,ttasanen\/oga","old_file":"ext\/liboga\/lexer.rl","new_file":"ext\/liboga\/lexer.rl","new_contents":"#include \"lexer.h\"\n\nVALUE oga_cLexer;\n\n%%machine lexer;\n\n\/**\n * Calls a method defined in the Ruby side of the lexer. The String value is\n * created based on the values of `ts` and `te` and uses the encoding specified\n * in `encoding`.\n *\n * @example\n * rb_encoding *encoding = rb_enc_get(...);\n * liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n *\/\nvoid liboga_xml_lexer_callback(\n VALUE self,\n const char *name,\n rb_encoding *encoding,\n const char *ts,\n const char *te\n)\n{\n VALUE value = rb_enc_str_new(ts, te - ts, encoding);\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 1, value);\n}\n\n\/**\n * Calls a method defined in the Ruby side of the lexer without passing it any\n * arguments.\n *\n * @example\n * liboga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n *\/\nvoid liboga_xml_lexer_callback_simple(VALUE self, const char *name)\n{\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 0);\n}\n\n%% write data;\n\n\/**\n * Lexes the input String specified in the instance variable `@data`. Lexed\n * values have the same encoding as the input value. This instance variable\n * is set in the Ruby layer of the lexer.\n *\n * The Ragel loop dispatches method calls back to Ruby land to make it easier\n * to implement complex actions without having to fiddle around with C. This\n * introduces a small performance overhead compared to a pure C implementation.\n * However, this is worth the overhead due to it being much easier to maintain.\n *\/\nVALUE oga_xml_lexer_advance(VALUE self)\n{\n \/* Pull the data in from Ruby land. *\/\n VALUE data_ivar = rb_ivar_get(self, rb_intern(\"@data\"));\n\n \/* Make sure that all data passed back to Ruby has the proper encoding. *\/\n rb_encoding *encoding = rb_enc_get(data_ivar);\n\n char *data_str_val = StringValuePtr(data_ivar);\n\n const char *p = data_str_val;\n const char *pe = data_str_val + strlen(data_str_val);\n const char *eof = pe;\n const char *ts, *te;\n\n int act = 0;\n int cs = 0;\n int top = 0;\n\n \/*\n Fixed stack size is enough since the lexer doesn't use that many nested\n fcalls.\n *\/\n int stack[8];\n\n %% write init;\n %% write exec;\n\n return Qnil;\n}\n\n%%{\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n ^dquote+ => {\n liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n };\n\n dquote => { fret; };\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n ^squote+ => {\n liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n };\n\n squote => { fret; };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n liboga_xml_lexer_callback(self, \"on_doctype_type\", encoding, ts, te);\n };\n\n # Lex the public\/system IDs as regular strings.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n liboga_xml_lexer_callback(self, \"on_doctype_name\", encoding, ts, te);\n };\n\n '>' => {\n liboga_xml_lexer_callback_simple(self, \"on_doctype_end\");\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n liboga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n any* cdata_end => {\n liboga_xml_lexer_callback(self, \"on_text\", encoding, ts, te - 3);\n liboga_xml_lexer_callback_simple(self, \"on_cdata_end\");\n fret;\n };\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n liboga_xml_lexer_callback_simple(self, \"on_comment_start\");\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n any* comment_end => {\n liboga_xml_lexer_callback(self, \"on_text\", encoding, ts, te - 3);\n liboga_xml_lexer_callback_simple(self, \"on_comment_end\");\n fret;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n liboga_xml_lexer_callback_simple(self, \"on_xml_decl_start\");\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n liboga_xml_lexer_callback_simple(self, \"on_xml_decl_end\");\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n liboga_xml_lexer_callback(self, \"on_attribute\", encoding, ts, te);\n };\n\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n liboga_xml_lexer_callback(self, \"on_element_start\", encoding, ts + 1, te);\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => {\n liboga_xml_lexer_callback_simple(self, \"on_newline\");\n };\n\n # Attribute names.\n identifier => {\n liboga_xml_lexer_callback(self, \"on_attribute\", encoding, ts, te);\n };\n\n # Attribute values.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n liboga_xml_lexer_callback_simple(self, \"on_element_open_end\");\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n liboga_xml_lexer_callback_simple(self, \"on_element_end\");\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n liboga_xml_lexer_callback_simple(self, \"on_element_end\");\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n ^('<' | '>')+ => {\n liboga_xml_lexer_callback(self, \"on_text\", encoding, ts, te);\n };\n *|;\n}%%\n\nvoid Init_liboga_xml_lexer()\n{\n oga_cLexer = rb_define_class_under(oga_mXML, \"Lexer\", rb_cObject);\n\n rb_define_method(oga_cLexer, \"advance_native\", oga_xml_lexer_advance, 0);\n}\n","old_contents":"#include \"lexer.h\"\n\nVALUE oga_cLexer;\n\n%%machine lexer;\n\n\/**\n * Calls a method defined in the Ruby side of the lexer. The String value is\n * created based on the values of `ts` and `te` and uses the encoding specified\n * in `encoding`.\n *\n * @example\n * rb_encoding *encoding = rb_enc_get(...);\n * oga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n *\/\nvoid oga_xml_lexer_callback(\n VALUE self,\n const char *name,\n rb_encoding *encoding,\n const char *ts,\n const char *te\n)\n{\n VALUE value = rb_enc_str_new(ts, te - ts, encoding);\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 1, value);\n}\n\n\/**\n * Calls a method defined in the Ruby side of the lexer without passing it any\n * arguments.\n *\n * @example\n * oga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n *\/\nvoid oga_xml_lexer_callback_simple(VALUE self, const char *name)\n{\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 0);\n}\n\n%% write data;\n\n\/**\n * Lexes the input String specified in the instance variable `@data`. Lexed\n * values have the same encoding as the input value. This instance variable\n * is set in the Ruby layer of the lexer.\n *\n * The Ragel loop dispatches method calls back to Ruby land to make it easier\n * to implement complex actions without having to fiddle around with C. This\n * introduces a small performance overhead compared to a pure C implementation.\n * However, this is worth the overhead due to it being much easier to maintain.\n *\/\nVALUE oga_xml_lexer_advance(VALUE self)\n{\n \/* Pull the data in from Ruby land. *\/\n VALUE data_ivar = rb_ivar_get(self, rb_intern(\"@data\"));\n\n \/* Make sure that all data passed back to Ruby has the proper encoding. *\/\n rb_encoding *encoding = rb_enc_get(data_ivar);\n\n char *data_str_val = StringValuePtr(data_ivar);\n\n const char *p = data_str_val;\n const char *pe = data_str_val + strlen(data_str_val);\n const char *eof = pe;\n const char *ts, *te;\n\n int act = 0;\n int cs = 0;\n int top = 0;\n\n \/*\n Fixed stack size is enough since the lexer doesn't use that many nested\n fcalls.\n *\/\n int stack[8];\n\n %% write init;\n %% write exec;\n\n return Qnil;\n}\n\n%%{\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n ^dquote+ => {\n oga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n };\n\n dquote => { fret; };\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n ^squote+ => {\n oga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n };\n\n squote => { fret; };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n oga_xml_lexer_callback(self, \"on_doctype_type\", encoding, ts, te);\n };\n\n # Lex the public\/system IDs as regular strings.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n oga_xml_lexer_callback(self, \"on_doctype_name\", encoding, ts, te);\n };\n\n '>' => {\n oga_xml_lexer_callback_simple(self, \"on_doctype_end\");\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n oga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n any* cdata_end => {\n oga_xml_lexer_callback(self, \"on_text\", encoding, ts, te - 3);\n oga_xml_lexer_callback_simple(self, \"on_cdata_end\");\n fret;\n };\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n oga_xml_lexer_callback_simple(self, \"on_comment_start\");\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n any* comment_end => {\n oga_xml_lexer_callback(self, \"on_text\", encoding, ts, te - 3);\n oga_xml_lexer_callback_simple(self, \"on_comment_end\");\n fret;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n oga_xml_lexer_callback_simple(self, \"on_xml_decl_start\");\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n oga_xml_lexer_callback_simple(self, \"on_xml_decl_end\");\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n oga_xml_lexer_callback(self, \"on_attribute\", encoding, ts, te);\n };\n\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n oga_xml_lexer_callback(self, \"on_element_start\", encoding, ts + 1, te);\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => {\n oga_xml_lexer_callback_simple(self, \"on_newline\");\n };\n\n # Attribute names.\n identifier => {\n oga_xml_lexer_callback(self, \"on_attribute\", encoding, ts, te);\n };\n\n # Attribute values.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n oga_xml_lexer_callback_simple(self, \"on_element_open_end\");\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n oga_xml_lexer_callback_simple(self, \"on_element_end\");\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n oga_xml_lexer_callback_simple(self, \"on_element_end\");\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n ^('<' | '>')+ => {\n oga_xml_lexer_callback(self, \"on_text\", encoding, ts, te);\n };\n *|;\n}%%\n\nvoid Init_liboga_xml_lexer()\n{\n oga_cLexer = rb_define_class_under(oga_mXML, \"Lexer\", rb_cObject);\n\n rb_define_method(oga_cLexer, \"advance_native\", oga_xml_lexer_advance, 0);\n}\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"544de16ff0009ce11ccf524b9bca8e0daaa04b82","subject":"Use 'tok' instead of '@source[@ts...@te]'","message":"Use 'tok' instead of '@source[@ts...@te]'\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n @need_encode = nil\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n @need_encode = @has_encode && @encoding != Encoding::UTF_8\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n @need_encode = @has_encode && @encoding != Encoding::UTF_32LE\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source_pts.size + 2\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source_pts.size + 1\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n source = @source[s...e]\n return source unless @need_encode\n source.encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG, '&.' => :tANDDOT,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @need_encode\n end\n\n current_literal = literal\n if !current_literal.heredoc? &&\n (token = current_literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n current_literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n current_literal = literal\n if current_literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if current_literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if current_literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n current_literal.extend_string(tok, @ts, @te)\n else\n current_literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if current_literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n current_literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n current_literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n current_literal = literal\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(current_literal.str_s, current_literal.str_s + 1)\n end\n\n if current_literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if current_literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit_table(KEYWORDS_BEGIN);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = @source[@ts].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = @source[@ts].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], @source[@te - 1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, @source[@te - 1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[@source[@ts + 1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit(:tLBRACE)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack\n => { emit(:tLBRACK)\n fbreak; };\n\n # a()\n e_lparen\n => { emit(:tLPAREN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit(:kRESCUE, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((@source[@ts] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label or 2.2 quoted label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n # \"bar\", 'baz'\n ['\"] # '\n => {\n fgoto *push_literal(tok, tok, @ts, nil, false, false);\n };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit(:tLAMBDA, tok(@ts, @ts + 2), @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit(:tLCURLY)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n unless !@static_env.nil? && @static_env.declared?(tok)\n fnext *arg_or_cmdarg;\n end\n else\n emit(:k__ENCODING__)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, @source[@te - 1].chr\n fgoto *push_literal(type, delimiter, @ts, nil, false, true);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '&.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit(:tEH)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit(:tLBRACK2)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit(:tSEMI)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* %{ tm = p } ('.' | '&.')\n => { p = tm - 1; fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n @need_encode = nil\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n @need_encode = @has_encode && @encoding != Encoding::UTF_8\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n @need_encode = @has_encode && @encoding != Encoding::UTF_32LE\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source_pts.size + 2\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source_pts.size + 1\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n source = @source[s...e]\n return source unless @need_encode\n source.encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG, '&.' => :tANDDOT,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @need_encode\n end\n\n current_literal = literal\n if !current_literal.heredoc? &&\n (token = current_literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n current_literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n current_literal = literal\n if current_literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if current_literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if current_literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n current_literal.extend_string(tok, @ts, @te)\n else\n current_literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if current_literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n current_literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n current_literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n current_literal = literal\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(current_literal.str_s, current_literal.str_s + 1)\n end\n\n if current_literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if current_literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit_table(KEYWORDS_BEGIN);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = @source[@ts].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = @source[@ts].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], @source[@te - 1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, @source[@te - 1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[@source[@ts + 1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit(:tLBRACE)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack\n => { emit(:tLBRACK)\n fbreak; };\n\n # a()\n e_lparen\n => { emit(:tLPAREN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit(:kRESCUE, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((@source[@ts] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label or 2.2 quoted label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n # \"bar\", 'baz'\n ['\"] # '\n => {\n fgoto *push_literal(tok, tok, @ts, nil, false, false);\n };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit(:tLAMBDA, tok(@ts, @ts + 2), @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit(:tLCURLY)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n unless !@static_env.nil? && @static_env.declared?(tok)\n fnext *arg_or_cmdarg;\n end\n else\n emit(:k__ENCODING__)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, @source[@te - 1].chr\n fgoto *push_literal(type, delimiter, @ts, nil, false, true);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '&.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit(:tEH)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit(:tLBRACK2)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit(:tSEMI)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* %{ tm = p } ('.' | '&.')\n => { p = tm - 1; fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"37fe6460f4e86c3bdc1875f8d5d20aa2777470e5","subject":"lexer.rl: recude encode method calls if not need","message":"lexer.rl: recude encode method calls if not need\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n @need_encode = nil\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n @need_encode = @has_encode && @encoding != Encoding::UTF_8\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n @need_encode = @has_encode && @encoding != Encoding::UTF_32LE\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n s = @source[s...e]\n return s unless @need_encode\n s.encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @need_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"ba25e40ae8fdfee7daed9731fc20894ba07b47ff","subject":"lexer.rl: remove duplicate operator.","message":"lexer.rl: remove duplicate operator.\n","repos":"modulexcite\/parser,bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n\n attr_accessor :cond, :cmdarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n end\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source + \"\\0\"\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if defined?(Encoding)\n @encoding = @source.encoding\n end\n\n if @source_pts.size > 1_000_000 && @source.respond_to?(:encode)\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_actions = self.class.send :_lex_actions\n _lex_key_offsets = self.class.send :_lex_key_offsets\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_single_lengths = self.class.send :_lex_single_lengths\n _lex_range_lengths = self.class.send :_lex_range_lengths\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n _lex_eof_trans = self.class.send :_lex_eof_trans\n\n p, pe, eof = @p, @source.length + 1, @source.length + 1\n\n @command_state = (@cs == self.class.lex_en_expr_value ||\n @cs == self.class.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n [ false, [ '$eof', range(p - 1, p) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, message, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, message, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:unicode_point_too_large],\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n @escape = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }.fetch(@source[p - 1].chr, @source[p - 1].chr)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_escape]\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_hex_escape],\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_unicode_escape],\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, Parser::ERRORS[:unterminated_unicode],\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, Parser::ERRORS[:escape_eof],\n range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts < extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n message = Parser::ERRORS[:regexp_options] % { :options => unknown_options.join }\n diagnostic :error, message\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n message = Parser::ERRORS[:cvar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n message = Parser::ERRORS[:ivar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a ?b\n # Character literal.\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n w_space+ ( [%\/] ( c_any - c_space_nl - '=' ) # \/\n # a < { fhold; fhold; fgoto expr_beg; };\n\n # x \/1\n # Ambiguous regexp literal.\n w_space+ '\/'\n => {\n diagnostic :warning, Parser::ERRORS[:ambiguous_literal],\n range(@te - 1, @te)\n\n fhold; fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n message = Parser::ERRORS[:ambiguous_prefix] % { :prefix => tok(tm, @te) }\n diagnostic :warning, message,\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:string_eof],\n range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = $2.empty? ? '\"' : $2\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | c_any - c_space_nl - e_bs % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n message = Parser::ERRORS[:invalid_escape_use] % { :escape => escape }\n diagnostic :warning, message, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:incomplete_escape],\n range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p }\n ( xdigit+ '_' )* xdigit* '_'?\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p }\n ( [01]+ '_' )* [01]* '_'?\n | [1-9] digit*\n %{ @num_base = 10; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n | '0' digit*\n %{ @num_base = 8; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n )\n => {\n digits = tok(@num_digits_s)\n\n if digits.end_with? '_'\n diagnostic :error, Parser::ERRORS[:trailing_in_number] % { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, Parser::ERRORS[:empty_numeric]\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, Parser::ERRORS[:invalid_octal],\n range(invalid_s, invalid_s + 1)\n end\n\n emit(:tINTEGER, digits.to_i(@num_base))\n fbreak;\n };\n\n '.' ( digit+ '_' )* digit+\n => {\n diagnostic :error, Parser::ERRORS[:no_dot_digit_literal]\n };\n\n (\n ( [1-9] [0-9]* ( '_' digit+ )* | '0' )\n ) [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n Parser::ERRORS[:trailing_in_number] % { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n (\n ( [1-9] [0-9]* ( '_' digit+ )* | '0' )\n ( '.' ( digit+ '_' )* digit+ )?\n ) [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n Parser::ERRORS[:trailing_in_number] % { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n (\n ( [1-9] [0-9]* ( '_' digit+ )* | '0' )\n ( '.' ( digit+ '_' )* digit+ )?\n ( [eE] [+\\-]? ( digit+ '_' )* digit+ )?\n )\n => {\n emit(:tFLOAT, tok.to_f)\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_arg; fbreak; };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, Parser::ERRORS[:bare_backslash],\n range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n message = Parser::ERRORS[:unexpected] % { :character => tok.inspect[1..-2] }\n diagnostic :fatal, message\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, Parser::ERRORS[:embedded_document],\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' c_nl_zlen\n => { p = pe - 1 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n\n attr_accessor :cond, :cmdarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n end\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source + \"\\0\"\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if defined?(Encoding)\n @encoding = @source.encoding\n end\n\n if @source_pts.size > 1_000_000 && @source.respond_to?(:encode)\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_actions = self.class.send :_lex_actions\n _lex_key_offsets = self.class.send :_lex_key_offsets\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_single_lengths = self.class.send :_lex_single_lengths\n _lex_range_lengths = self.class.send :_lex_range_lengths\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n _lex_eof_trans = self.class.send :_lex_eof_trans\n\n p, pe, eof = @p, @source.length + 1, @source.length + 1\n\n @command_state = (@cs == self.class.lex_en_expr_value ||\n @cs == self.class.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n [ false, [ '$eof', range(p - 1, p) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, message, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, message, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '**' | '<<' | '>>' |\n '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:unicode_point_too_large],\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n @escape = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }.fetch(@source[p - 1].chr, @source[p - 1].chr)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_escape]\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_hex_escape],\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_unicode_escape],\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, Parser::ERRORS[:unterminated_unicode],\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, Parser::ERRORS[:escape_eof],\n range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts < extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n message = Parser::ERRORS[:regexp_options] % { :options => unknown_options.join }\n diagnostic :error, message\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n message = Parser::ERRORS[:cvar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n message = Parser::ERRORS[:ivar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a ?b\n # Character literal.\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n w_space+ ( [%\/] ( c_any - c_space_nl - '=' ) # \/\n # a < { fhold; fhold; fgoto expr_beg; };\n\n # x \/1\n # Ambiguous regexp literal.\n w_space+ '\/'\n => {\n diagnostic :warning, Parser::ERRORS[:ambiguous_literal],\n range(@te - 1, @te)\n\n fhold; fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n message = Parser::ERRORS[:ambiguous_prefix] % { :prefix => tok(tm, @te) }\n diagnostic :warning, message,\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:string_eof],\n range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = $2.empty? ? '\"' : $2\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | c_any - c_space_nl - e_bs % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n message = Parser::ERRORS[:invalid_escape_use] % { :escape => escape }\n diagnostic :warning, message, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:incomplete_escape],\n range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p }\n ( xdigit+ '_' )* xdigit* '_'?\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p }\n ( [01]+ '_' )* [01]* '_'?\n | [1-9] digit*\n %{ @num_base = 10; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n | '0' digit*\n %{ @num_base = 8; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n )\n => {\n digits = tok(@num_digits_s)\n\n if digits.end_with? '_'\n diagnostic :error, Parser::ERRORS[:trailing_in_number] % { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, Parser::ERRORS[:empty_numeric]\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, Parser::ERRORS[:invalid_octal],\n range(invalid_s, invalid_s + 1)\n end\n\n emit(:tINTEGER, digits.to_i(@num_base))\n fbreak;\n };\n\n '.' ( digit+ '_' )* digit+\n => {\n diagnostic :error, Parser::ERRORS[:no_dot_digit_literal]\n };\n\n (\n ( [1-9] [0-9]* ( '_' digit+ )* | '0' )\n ) [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n Parser::ERRORS[:trailing_in_number] % { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n (\n ( [1-9] [0-9]* ( '_' digit+ )* | '0' )\n ( '.' ( digit+ '_' )* digit+ )?\n ) [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n Parser::ERRORS[:trailing_in_number] % { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n (\n ( [1-9] [0-9]* ( '_' digit+ )* | '0' )\n ( '.' ( digit+ '_' )* digit+ )?\n ( [eE] [+\\-]? ( digit+ '_' )* digit+ )?\n )\n => {\n emit(:tFLOAT, tok.to_f)\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_arg; fbreak; };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, Parser::ERRORS[:bare_backslash],\n range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n message = Parser::ERRORS[:unexpected] % { :character => tok.inspect[1..-2] }\n diagnostic :fatal, message\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, Parser::ERRORS[:embedded_document],\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' c_nl_zlen\n => { p = pe - 1 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"44e26e3b86e43e876183d6ce11d7ed47be260479","subject":"abstr property has been handled incorrectly","message":"abstr property has been handled incorrectly\n\nThis fixes bug #143\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner.rl","new_file":"src\/mfilescanner.rl","new_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # white space or line continuation\n WS =\n ( [ \\t]+\n | ('...'.[\\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n |\n ( ('=' . [ ]*) %st_tok . ( matrix | [^[{;\\n%])* . (';' | EOL | '%' @{ fhold; } ))\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n for (unsigned int i = 0; i < defaultprop_.length(); ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = '\\\\';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n }\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n std::string defvalue;\n get_default(paramlist_[i], defvalue);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"COPY_TYPIFIED_FIELD_DOCU\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"COPY_TYPIFIED_FIELD_DOCU\")][0] == string(\"true\"))\n {\n runMode_.copy_typified_field_docu = true;\n }\n else\n {\n runMode_.copy_typified_field_docu = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOCPP:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n std::string name = (*lit).first;\n if (name.substr(0, 6) == std::string(\"unused\")\n && name.find_first_not_of(\"0123456789\", 7) == std::string::npos)\n continue;\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << name << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty() && runMode_.copy_typified_field_docu)\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n string defval;\n extract_default(docubody_, defval);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n if(!defaultprop_.empty())\n {\n fout_ << \"* @b Default: \" << defaultprop_ << \"\\n\";\n }\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n \/* param_defaults_.clear(); *\/\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams\n && docuheader_.empty()\n && !methodparams_.abstr)\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No definition for function \" << cfuncname_\n << \" found in class \" << classname_ << \"!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::extract_default(DocuBlock & db, std::string & defvalue)\n{\n typedef DocuBlock :: iterator DBIt;\n\n for(DBIt dit = db.begin(); dit != db.end(); ++dit)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t deflength = std::string(\"(default\").length();\n found = line.find(\"(default\");\n if(found != std::string::npos)\n {\n size_t tmp;\n if(line[found+1] == '=')\n tmp = found + deflength + 1;\n else if (line[found+2] == '=')\n tmp = found + deflength + 2;\n else\n found = std::string::npos;\n\n if (found != std::string::npos)\n {\n defvalue = line.substr(tmp+1);\n defvalue = defvalue.substr(0, defvalue.length() - 1);\n }\n }\n if(found == std::string::npos)\n {\n deflength = string(\"@default \").length();\n found = line.find(\"@default \");\n if (found != std::string::npos)\n {\n size_t end = line.find(\"@\", found+1);\n if (end == std::string::npos)\n end = line.find(\"of type\");\n if (end == std::string::npos)\n end = line.length();\n end = end - 1;\n size_t start = found + deflength + 1;\n defvalue = line.substr(start, end - start);\n line[found] = '(';\n line[found+8] = '=';\n line = line.substr(0, found) + \"@b Default: \"\n + line.substr(found+9,end-found-9) + \" \" + line.substr(end);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n }\n }\n}\n\nvoid MFileScanner::get_default(const std::string & paramname, std::string & defvalue)\n{\n typedef DocuList :: iterator DLIt;\n DLIt it = param_list_.find(paramname);\n if(it != param_list_.end() && !(it->second).empty())\n {\n DocuBlock & db = it->second;\n extract_default(db, defvalue);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\\n\\0\", typenstart );\n if (typenstart == std::string::npos)\n {\n \/\/ read in next line\n if (remove)\n (*dit).erase(found, line.length() - found - 1);\n\n ++dit;\n if (dit == db.end())\n break;\n line = *dit;\n found = 0;\n typenstart = line.find_first_not_of( \" \\t\");\n }\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ (*dit).replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n (*dit).erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess + \", \"\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.abstr)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nvoid MFileScanner::postprocess_unused_params(std::string & param, DocuList & doculist)\n{\n if (param == std::string(\"~\"))\n {\n int counter = 1;\n bool found = true;\n while ( found )\n {\n std::ostringstream oss;\n oss << \"unused\" << counter;\n if (doculist.find(oss.str()) == doculist.end())\n {\n param = oss.str();\n found = false;\n }\n ++counter;\n }\n }\n}\n\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","old_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # white space or line continuation\n WS =\n ( [ \\t]+\n | ('...'.[\\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n |\n ( ('=' . [ ]*) %st_tok . ( matrix | [^[{;\\n%])* . (';' | EOL | '%' @{ fhold; } ))\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n for (unsigned int i = 0; i < defaultprop_.length(); ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = '\\\\';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n }\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n std::string defvalue;\n get_default(paramlist_[i], defvalue);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"COPY_TYPIFIED_FIELD_DOCU\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"COPY_TYPIFIED_FIELD_DOCU\")][0] == string(\"true\"))\n {\n runMode_.copy_typified_field_docu = true;\n }\n else\n {\n runMode_.copy_typified_field_docu = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOCPP:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n std::string name = (*lit).first;\n if (name.substr(0, 6) == std::string(\"unused\")\n && name.find_first_not_of(\"0123456789\", 7) == std::string::npos)\n continue;\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << name << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty() && runMode_.copy_typified_field_docu)\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n string defval;\n extract_default(docubody_, defval);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n if(!defaultprop_.empty())\n {\n fout_ << \"* @b Default: \" << defaultprop_ << \"\\n\";\n }\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n \/* param_defaults_.clear(); *\/\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams\n && docuheader_.empty()\n && !methodparams_.abstr)\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No definition for function \" << cfuncname_\n << \" found in class \" << classname_ << \"!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::extract_default(DocuBlock & db, std::string & defvalue)\n{\n typedef DocuBlock :: iterator DBIt;\n\n for(DBIt dit = db.begin(); dit != db.end(); ++dit)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t deflength = std::string(\"(default\").length();\n found = line.find(\"(default\");\n if(found != std::string::npos)\n {\n size_t tmp;\n if(line[found+1] == '=')\n tmp = found + deflength + 1;\n else if (line[found+2] == '=')\n tmp = found + deflength + 2;\n else\n found = std::string::npos;\n\n if (found != std::string::npos)\n {\n defvalue = line.substr(tmp+1);\n defvalue = defvalue.substr(0, defvalue.length() - 1);\n }\n }\n if(found == std::string::npos)\n {\n deflength = string(\"@default \").length();\n found = line.find(\"@default \");\n if (found != std::string::npos)\n {\n size_t end = line.find(\"@\", found+1);\n if (end == std::string::npos)\n end = line.find(\"of type\");\n if (end == std::string::npos)\n end = line.length();\n end = end - 1;\n size_t start = found + deflength + 1;\n defvalue = line.substr(start, end - start);\n line[found] = '(';\n line[found+8] = '=';\n line = line.substr(0, found) + \"@b Default: \"\n + line.substr(found+9,end-found-9) + \" \" + line.substr(end);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n }\n }\n}\n\nvoid MFileScanner::get_default(const std::string & paramname, std::string & defvalue)\n{\n typedef DocuList :: iterator DLIt;\n DLIt it = param_list_.find(paramname);\n if(it != param_list_.end() && !(it->second).empty())\n {\n DocuBlock & db = it->second;\n extract_default(db, defvalue);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\\n\\0\", typenstart );\n if (typenstart == std::string::npos)\n {\n \/\/ read in next line\n if (remove)\n (*dit).erase(found, line.length() - found - 1);\n\n ++dit;\n if (dit == db.end())\n break;\n line = *dit;\n found = 0;\n typenstart = line.find_first_not_of( \" \\t\");\n }\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ (*dit).replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n (*dit).erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess + \", \"\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nvoid MFileScanner::postprocess_unused_params(std::string & param, DocuList & doculist)\n{\n if (param == std::string(\"~\"))\n {\n int counter = 1;\n bool found = true;\n while ( found )\n {\n std::ostringstream oss;\n oss << \"unused\" << counter;\n if (doculist.find(oss.str()) == doculist.end())\n {\n param = oss.str();\n found = false;\n }\n ++counter;\n }\n }\n}\n\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"0900bb4618499117a9e3a1d928a83b0b862b44cc","subject":"SSA: Don't call the parser actions for tags no renderer supports ATM.","message":"SSA: Don't call the parser actions for tags no renderer supports ATM.\n\n","repos":"JanX2\/Perian,JanX2\/Perian,JanX2\/Perian,JanX2\/Perian,JanX2\/Perian","old_file":"Subtitles\/SubParsing.m.rl","new_file":"Subtitles\/SubParsing.m.rl","new_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = STUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = STUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum\n\t\t\t\t\t\t\t|\"fry\" floatnum\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","old_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = STUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = STUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum %bluredge\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum %frx\n\t\t\t\t\t\t\t|\"fry\" floatnum %fry\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"17565abf693532e963b4b1c1af546b579abe94ec","subject":"more verbose warning messages","message":"more verbose warning messages\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner.rl","new_file":"src\/mfilescanner.rl","new_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << '\"';\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << '\"';\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n std::string defvalue;\n get_default(paramlist_[i], defvalue);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOCPP:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n string defval;\n extract_default(docubody_, defval);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n \/* param_defaults_.clear(); *\/\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No definition for function \" << cfuncname_\n << \" found in class \" << classname_ << \"!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::extract_default(DocuBlock & db, std::string & defvalue)\n{\n typedef DocuBlock :: iterator DBIt;\n\n for(DBIt dit = db.begin(); dit != db.end(); ++dit)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t deflength = std::string(\"(default\").length();\n found = line.find(\"(default\");\n if(found != std::string::npos)\n {\n size_t tmp;\n if(line[found+1] == '=')\n tmp = found + deflength + 1;\n else if (line[found+2] == '=')\n tmp = found + deflength + 2;\n else\n found = std::string::npos;\n\n if (found != std::string::npos)\n {\n defvalue = line.substr(tmp+1);\n defvalue = defvalue.substr(0, defvalue.length() - 1);\n }\n }\n if(found == std::string::npos)\n {\n deflength = string(\"@default \").length();\n found = line.find(\"@default \");\n if (found != std::string::npos)\n {\n defvalue = line.substr(found + deflength + 1);\n line[found] = '(';\n line[found+8] = '=';\n line = line.substr(0, line.length()-1) + \")\\n\";\n }\n else\n {\n defvalue = std::string(\"\");\n }\n }\n }\n}\n\nvoid MFileScanner::get_default(const std::string & paramname, std::string & defvalue)\n{\n typedef DocuList :: iterator DLIt;\n DLIt it = param_list_.find(paramname);\n if(it != param_list_.end() && !(it->second).empty())\n {\n DocuBlock & db = it->second;\n extract_default(db, defvalue);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","old_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << '\"';\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << '\"';\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n std::string defvalue;\n get_default(paramlist_[i], defvalue);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n string defval;\n extract_default(docubody_, defval);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n \/* param_defaults_.clear(); *\/\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::extract_default(DocuBlock & db, std::string & defvalue)\n{\n typedef DocuBlock :: iterator DBIt;\n\n for(DBIt dit = db.begin(); dit != db.end(); ++dit)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t deflength = std::string(\"(default\").length();\n found = line.find(\"(default\");\n if(found != std::string::npos)\n {\n size_t tmp;\n if(line[found+1] == '=')\n tmp = found + deflength + 1;\n else if (line[found+2] == '=')\n tmp = found + deflength + 2;\n else\n found = std::string::npos;\n\n if (found != std::string::npos)\n {\n defvalue = line.substr(tmp+1);\n defvalue = defvalue.substr(0, defvalue.length() - 1);\n }\n }\n if(found == std::string::npos)\n {\n deflength = string(\"@default \").length();\n found = line.find(\"@default \");\n if (found != std::string::npos)\n {\n defvalue = line.substr(found + deflength + 1);\n line[found] = '(';\n line[found+8] = '=';\n line = line.substr(0, line.length()-1) + \")\\n\";\n }\n else\n {\n defvalue = std::string(\"\");\n }\n }\n }\n}\n\nvoid MFileScanner::get_default(const std::string & paramname, std::string & defvalue)\n{\n typedef DocuList :: iterator DLIt;\n DLIt it = param_list_.find(paramname);\n if(it != param_list_.end() && !(it->second).empty())\n {\n DocuBlock & db = it->second;\n extract_default(db, defvalue);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"e3bbf2851d62817e0bae436025e757460e75f858","subject":"update postprocessor","message":"update postprocessor\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/postprocess.rl","new_file":"src\/postprocess.rl","new_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\/\/ New for directory recursion\n#ifdef WIN32\n\t#include \n#else\n\t#include \n#endif\n\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US);\n\n '_tsbus_cotm' => { fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n ('::mtoc_subst_') => { fout << '.'; fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:.,;_\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>()[\\]{}\\t:.;,_\\&]) => {fout << *ts;};\n\n # a single dot stays a dot\n ('.') => {fout << '.';};\n *|;\n}%%\n\nclass PostProcess {\n\nprivate:\n string docdir_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n\npublic:\n \/**\n * @class PostProcess\n *\n * @change{1,2,dw,2011-11-04} Changed the postprocessor interface from taking a single file argument to\n * assuming the passed string to be a folder whos contents are to be postprocessed.\n *\/\n \/\/ constructor\n PostProcess(const string &docdir) :\n docdir_(docdir),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false)\n { }\n\n int execute()\n {\n DIR *dp;\n if ((dp = opendir(docdir_.c_str())) == NULL) {\n cerr << \"Error opening directory \" << docdir_ << endl;\n return -1;\n }\n\n struct dirent* dirp;\n string file;\n while ((dirp = readdir(dp)) != NULL) {\n file = string(dirp->d_name);\n \/\/ Process only html files\n if (file.substr(file.find_last_of(\".\") + 1) == \"html\" && file.find(\"8rl\") == string::npos) {\n postprocess(docdir_ + string(\"\/\") + file);\n }\n }\n closedir(dp);\n return 0;\n }\n\n \/\/ run postprocessor\n int postprocess(string file)\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try {\n is.open(file.c_str());\n } catch (std::ifstream::failure e) {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char* buf = new char[(int)(1.1*length)];\n char* p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n \n ofstream fout;\n try {\n fout.open(file.c_str(), ios_base::trunc);\n } catch (std::ofstream::failure e) {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << file << \": PARSE ERROR in line \" << line << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string docdir;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n docdir = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n cout << \"Running mtoc++ postprocessor on directory \" << docdir << endl;\n \n PostProcess scanner(docdir);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","old_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\/\/ New for directory recursion\n#ifdef WIN32\n\t#include \n#else\n\t#include \n#endif\n\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US);\n\n '_tsbus_cotm' => { fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:,;_\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>()[\\]{}\\t:;,_\\&]) => {fout << *ts;};\n *|;\n}%%\n\nclass PostProcess {\n\nprivate:\n string docdir_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n\npublic:\n \/**\n * @class PostProcess\n *\n * @change{1,2,dw,2011-11-04} Changed the postprocessor interface from taking a single file argument to\n * assuming the passed string to be a folder whos contents are to be postprocessed.\n *\/\n \/\/ constructor\n PostProcess(const string &docdir) :\n docdir_(docdir),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false)\n { }\n\n int execute()\n {\n DIR *dp;\n if ((dp = opendir(docdir_.c_str())) == NULL) {\n cerr << \"Error opening directory \" << docdir_ << endl;\n return -1;\n }\n\n struct dirent* dirp;\n string file;\n while ((dirp = readdir(dp)) != NULL) {\n file = string(dirp->d_name);\n \/\/ Process only html files\n if (file.substr(file.find_last_of(\".\") + 1) == \"html\" && file.find(\"8rl\") == string::npos) {\n postprocess(docdir_ + string(\"\/\") + file);\n }\n }\n closedir(dp);\n return 0;\n }\n\n \/\/ run postprocessor\n int postprocess(string file)\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try {\n is.open(file.c_str());\n } catch (std::ifstream::failure e) {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char* buf = new char[(int)(1.1*length)];\n char* p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n \n ofstream fout;\n try {\n fout.open(file.c_str(), ios_base::trunc);\n } catch (std::ofstream::failure e) {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << file << \": PARSE ERROR in line \" << line << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string docdir;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n docdir = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n cout << \"Running mtoc++ postprocessor on directory \" << docdir << endl;\n \n PostProcess scanner(docdir);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"dd1a39f16cd4597d5b6156379c0f55cee8a6a452","subject":"fix ragel warning 'applying kleene star to a machine that accepts zero length word'","message":"fix ragel warning 'applying kleene star to a machine that accepts zero length word'\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/hext.rl","new_file":"src\/hext\/hext.rl","new_contents":"%%{\n machine hext;\n\n action error {\n throw_error();\n }\n\n cap_limit = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( alpha (alnum | '-' | '_')** );\n match_literal = ( alpha (alnum | '-' | '_' | ' ')** );\n cap_regex = ( [^\/]+* );\n match_regex = ( [^\/]+* );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n '@' >{ LX_TK_START(TK_BUILTIN); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_ATTR_NAME); }\n %{ LX_TK_STOP; }\n )\n <:\n (\n '=\"'\n (\n (\n (\n '{' >{ LX_TK_START(TK_CAP_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n cap_var** >{ LX_TK_START(TK_CAP_VAR); }\n %{ LX_TK_STOP; }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START(TK_CAP_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )?\n (\n '}' >{ LX_TK_START(TK_CAP_END); }\n %{ LX_TK_STOP; }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex >{ LX_TK_START(TK_MATCH_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )\n |\n (\n match_literal** >{ LX_TK_START(TK_MATCH_LITERAL); }\n %{ LX_TK_STOP; }\n )\n )\n )\n '\"'\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' >{ LX_TK_START(TK_INDENT); }\n %{ LX_TK_STOP; }\n )*\n (\n '<' >{ LX_TK_START(TK_RULE_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n '!' >{ LX_TK_START(TK_DIRECT_DESC); }\n %{ LX_TK_STOP; }\n )?\n (\n cap_limit >{ LX_TK_START(TK_CAP_LIMIT); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_TAG_NAME); }\n %{ LX_TK_STOP; }\n )?\n attributes?\n (\n '>' >{ LX_TK_START(TK_RULE_END); }\n %{ LX_TK_STOP; }\n )\n )\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n )**\n $err(error) $\/{ LX_TK_START(TK_EOF); fbreak; };\n}%%\n","old_contents":"%%{\n machine hext;\n\n action error {\n throw_error();\n }\n\n cap_limit = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( alpha (alnum | '-' | '_')** );\n match_literal = ( alpha (alnum | '-' | '_' | ' ')** );\n cap_regex = ( [^\/]+* );\n match_regex = ( [^\/]+* );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n '@' >{ LX_TK_START(TK_BUILTIN); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_ATTR_NAME); }\n %{ LX_TK_STOP; }\n )\n <:\n (\n '=\"'\n (\n (\n (\n '{' >{ LX_TK_START(TK_CAP_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n cap_var** >{ LX_TK_START(TK_CAP_VAR); }\n %{ LX_TK_STOP; }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START(TK_CAP_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )?\n (\n '}' >{ LX_TK_START(TK_CAP_END); }\n %{ LX_TK_STOP; }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex** >{ LX_TK_START(TK_MATCH_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )\n |\n (\n match_literal** >{ LX_TK_START(TK_MATCH_LITERAL); }\n %{ LX_TK_STOP; }\n )\n )\n )\n '\"'\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' >{ LX_TK_START(TK_INDENT); }\n %{ LX_TK_STOP; }\n )*\n (\n '<' >{ LX_TK_START(TK_RULE_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n '!' >{ LX_TK_START(TK_DIRECT_DESC); }\n %{ LX_TK_STOP; }\n )?\n (\n cap_limit >{ LX_TK_START(TK_CAP_LIMIT); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_TAG_NAME); }\n %{ LX_TK_STOP; }\n )?\n attributes?\n (\n '>' >{ LX_TK_START(TK_RULE_END); }\n %{ LX_TK_STOP; }\n )\n )\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n )**\n $err(error) $\/{ LX_TK_START(TK_EOF); fbreak; };\n}%%\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"d960eb7cd522a31d2ff8ec83ca2c8902f009e4cd","subject":"Removed CSS lexer code that was commented out.","message":"Removed CSS lexer code that was commented out.\n","repos":"YorickPeterse\/oga,jeffreybaird\/oga,jeffreybaird\/oga,YorickPeterse\/oga,ttasanen\/oga,altmetric\/oga,YorickPeterse\/oga,dfockler\/oga,dfockler\/oga,dfockler\/oga,ttasanen\/oga,altmetric\/oga,jeffreybaird\/oga,ttasanen\/oga,ttasanen\/oga,jeffreybaird\/oga,dfockler\/oga,altmetric\/oga,jeffreybaird\/oga,ttasanen\/oga,YorickPeterse\/oga,YorickPeterse\/oga,altmetric\/oga,dfockler\/oga,altmetric\/oga","old_file":"lib\/oga\/css\/lexer.rl","new_file":"lib\/oga\/css\/lexer.rl","new_contents":"%%machine css_lexer; # %\n\nmodule Oga\n module CSS\n ##\n # Lexer for turning CSS expressions into a sequence of tokens. Tokens are\n # returned as arrays with every array having two values:\n #\n # 1. The token type as a Symbol\n # 2. The token value, or nil if there is no value.\n #\n # ## Thread Safety\n #\n # Similar to the XPath lexer this lexer keeps track of an internal state. As\n # a result it's not safe to share the same instance of this lexer between\n # multiple threads. However, no global state is used so you can use separate\n # instances in threads just fine.\n #\n class Lexer\n %% write data;\n\n # % fix highlight\n\n ##\n # @param [String] data The data to lex.\n #\n def initialize(data)\n @data = data\n end\n\n ##\n # Gathers all the tokens for the input and returns them as an Array.\n #\n # @see [#advance]\n # @return [Array]\n #\n def lex\n tokens = []\n\n advance do |type, value|\n tokens << [type, value]\n end\n\n return tokens\n end\n\n ##\n # Advances through the input and generates the corresponding tokens. Each\n # token is yielded to the supplied block.\n #\n # This method stores the supplied block in `@block` and resets it after\n # the lexer loop has finished.\n #\n # @see [#add_token]\n #\n def advance(&block)\n @block = block\n\n data = @data # saves ivar lookups while lexing.\n ts = nil\n te = nil\n stack = []\n top = 0\n cs = self.class.css_lexer_start\n act = 0\n eof = @data.bytesize\n p = 0\n pe = eof\n\n _css_lexer_eof_trans = self.class.send(:_css_lexer_eof_trans)\n _css_lexer_from_state_actions = self.class.send(:_css_lexer_from_state_actions)\n _css_lexer_index_offsets = self.class.send(:_css_lexer_index_offsets)\n _css_lexer_indicies = self.class.send(:_css_lexer_indicies)\n _css_lexer_key_spans = self.class.send(:_css_lexer_key_spans)\n _css_lexer_to_state_actions = self.class.send(:_css_lexer_to_state_actions)\n _css_lexer_trans_actions = self.class.send(:_css_lexer_trans_actions)\n _css_lexer_trans_keys = self.class.send(:_css_lexer_trans_keys)\n _css_lexer_trans_targs = self.class.send(:_css_lexer_trans_targs)\n\n %% write exec;\n\n # % fix highlight\n ensure\n @block = nil\n end\n\n private\n\n ##\n # Emits a token of which the value is based on the supplied start\/stop\n # position.\n #\n # @param [Symbol] type The token type.\n # @param [Fixnum] start\n # @param [Fixnum] stop\n #\n # @see [#text]\n # @see [#add_token]\n #\n def emit(type, start, stop)\n value = slice_input(start, stop)\n\n add_token(type, value)\n end\n\n ##\n # Returns the text between the specified start and stop position.\n #\n # @param [Fixnum] start\n # @param [Fixnum] stop\n # @return [String]\n #\n def slice_input(start, stop)\n return @data.byteslice(start, stop - start)\n end\n\n ##\n # Yields a new token to the supplied block.\n #\n # @param [Symbol] type The token type.\n # @param [String] value The token value.\n #\n # @yieldparam [Symbol] type\n # @yieldparam [String|NilClass] value\n #\n def add_token(type, value = nil)\n @block.call(type, value)\n end\n\n %%{\n getkey (data.getbyte(p) || 0);\n\n whitespace = [\\t ]+;\n\n comma = ',' %{ add_token(:T_COMMA) };\n hash = '#' %{ add_token(:T_HASH) };\n dot = '.' %{ add_token(:T_DOT) };\n lbrack = '[' %{ add_token(:T_LBRACK) };\n rbrack = ']' %{ add_token(:T_RBRACK) };\n colon = ':' %{ add_token(:T_COLON) };\n lparen = '(';\n rparen = ')';\n pipe = '|';\n odd = 'odd';\n even = 'even';\n minus = '-';\n nth = 'n';\n\n # Identifiers\n #\n # Identifiers are used for element and attribute names. Identifiers have\n # to start with a letter.\n\n identifier = '*' | [a-zA-Z]+ [a-zA-Z\\-_0-9]*;\n\n action emit_identifier {\n emit(:T_IDENT, ts, te)\n }\n\n # Operators\n #\n # Various operators that can be used for filtering nodes. For example,\n # \"$=\" can be used to select attribute values that end with a given\n # string.\n #\n # http:\/\/www.w3.org\/TR\/css3-selectors\/#selectors\n\n op_eq = '=';\n op_space_in = '~=';\n op_starts_with = '^=';\n op_ends_with = '$=';\n op_in = '*=';\n op_hyphen_in = '|=';\n op_child = '>';\n op_fol_direct = '+';\n op_fol = '~';\n\n # Numbers\n #\n # CSS selectors only understand integers, floating points are not\n # supported.\n\n integer = ('-' | '+')* digit+;\n\n action emit_integer {\n value = slice_input(ts, te).to_i\n\n add_token(:T_INT, value)\n }\n\n # Strings\n #\n # Strings can be single or double quoted. They are mainly used for\n # attribute values.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote* dquote);\n string_squote = (squote ^squote* squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n emit(:T_STRING, ts + 1, te - 1)\n }\n\n # Pseudo Classes\n #\n # http:\/\/www.w3.org\/TR\/css3-selectors\/#structural-pseudos\n\n action emit_lparen {\n add_token(:T_LPAREN)\n\n fnext pseudo_args;\n }\n\n action emit_rparen {\n add_token(:T_RPAREN)\n\n fnext main;\n }\n\n # Machine used for processing the arguments of a pseudo class. These are\n # handled in a separate machine as these arguments can contain data not\n # allowed elsewhere. For example, \"2n\" is not allowed to appear outside\n # of the arguments list.\n pseudo_args := |*\n nth => { add_token(:T_NTH) };\n minus => { add_token(:T_MINUS) };\n odd => { add_token(:T_ODD) };\n even => { add_token(:T_EVEN) };\n integer => emit_integer;\n rparen => emit_rparen;\n *|;\n\n main := |*\n whitespace | comma | hash | dot | lbrack | rbrack | colon;\n\n # Some of the operators have similar characters (e.g. the \"=\"). As a\n # result we can't use rules like the following:\n #\n # '=' %{ ... };\n # '*=' %{ ... };\n #\n # This would result in both machines being executed for the input\n # \"*=\". The syntax below ensures that only the first match is handled.\n\n op_eq => { add_token(:T_EQ) };\n op_space_in => { add_token(:T_SPACE_IN) };\n op_starts_with => { add_token(:T_STARTS_WITH) };\n op_ends_with => { add_token(:T_ENDS_WITH) };\n op_in => { add_token(:T_IN) };\n op_hyphen_in => { add_token(:T_HYPHEN_IN) };\n op_child => { add_token(:T_CHILD) };\n op_fol_direct => { add_token(:T_FOLLOWING_DIRECT) };\n op_fol => { add_token(:T_FOLLOWING) };\n\n # The pipe character is also used in the |= operator so the action for\n # this is handled separately.\n pipe => { add_token(:T_PIPE) };\n\n lparen => emit_lparen;\n identifier => emit_identifier;\n integer => emit_integer;\n string => emit_string;\n\n any;\n *|;\n }%%\n end # Lexer\n end # CSS\nend # Oga\n","old_contents":"%%machine css_lexer; # %\n\nmodule Oga\n module CSS\n ##\n # Lexer for turning CSS expressions into a sequence of tokens. Tokens are\n # returned as arrays with every array having two values:\n #\n # 1. The token type as a Symbol\n # 2. The token value, or nil if there is no value.\n #\n # ## Thread Safety\n #\n # Similar to the XPath lexer this lexer keeps track of an internal state. As\n # a result it's not safe to share the same instance of this lexer between\n # multiple threads. However, no global state is used so you can use separate\n # instances in threads just fine.\n #\n class Lexer\n %% write data;\n\n # % fix highlight\n\n ##\n # @param [String] data The data to lex.\n #\n def initialize(data)\n @data = data\n end\n\n ##\n # Gathers all the tokens for the input and returns them as an Array.\n #\n # @see [#advance]\n # @return [Array]\n #\n def lex\n tokens = []\n\n advance do |type, value|\n tokens << [type, value]\n end\n\n return tokens\n end\n\n ##\n # Advances through the input and generates the corresponding tokens. Each\n # token is yielded to the supplied block.\n #\n # This method stores the supplied block in `@block` and resets it after\n # the lexer loop has finished.\n #\n # @see [#add_token]\n #\n def advance(&block)\n @block = block\n\n data = @data # saves ivar lookups while lexing.\n ts = nil\n te = nil\n stack = []\n top = 0\n cs = self.class.css_lexer_start\n act = 0\n eof = @data.bytesize\n p = 0\n pe = eof\n\n _css_lexer_eof_trans = self.class.send(:_css_lexer_eof_trans)\n _css_lexer_from_state_actions = self.class.send(:_css_lexer_from_state_actions)\n _css_lexer_index_offsets = self.class.send(:_css_lexer_index_offsets)\n _css_lexer_indicies = self.class.send(:_css_lexer_indicies)\n _css_lexer_key_spans = self.class.send(:_css_lexer_key_spans)\n _css_lexer_to_state_actions = self.class.send(:_css_lexer_to_state_actions)\n _css_lexer_trans_actions = self.class.send(:_css_lexer_trans_actions)\n _css_lexer_trans_keys = self.class.send(:_css_lexer_trans_keys)\n _css_lexer_trans_targs = self.class.send(:_css_lexer_trans_targs)\n\n %% write exec;\n\n # % fix highlight\n ensure\n @block = nil\n end\n\n private\n\n ##\n # Emits a token of which the value is based on the supplied start\/stop\n # position.\n #\n # @param [Symbol] type The token type.\n # @param [Fixnum] start\n # @param [Fixnum] stop\n #\n # @see [#text]\n # @see [#add_token]\n #\n def emit(type, start, stop)\n value = slice_input(start, stop)\n\n add_token(type, value)\n end\n\n ##\n # Returns the text between the specified start and stop position.\n #\n # @param [Fixnum] start\n # @param [Fixnum] stop\n # @return [String]\n #\n def slice_input(start, stop)\n return @data.byteslice(start, stop - start)\n end\n\n ##\n # Yields a new token to the supplied block.\n #\n # @param [Symbol] type The token type.\n # @param [String] value The token value.\n #\n # @yieldparam [Symbol] type\n # @yieldparam [String|NilClass] value\n #\n def add_token(type, value = nil)\n @block.call(type, value)\n end\n\n %%{\n getkey (data.getbyte(p) || 0);\n\n whitespace = [\\t ]+;\n\n comma = ',' %{ add_token(:T_COMMA) };\n hash = '#' %{ add_token(:T_HASH) };\n dot = '.' %{ add_token(:T_DOT) };\n lbrack = '[' %{ add_token(:T_LBRACK) };\n rbrack = ']' %{ add_token(:T_RBRACK) };\n colon = ':' %{ add_token(:T_COLON) };\n lparen = '(';\n rparen = ')';\n pipe = '|';\n odd = 'odd';\n even = 'even';\n minus = '-';\n nth = 'n';\n\n # Identifiers\n #\n # Identifiers are used for element and attribute names. Identifiers have\n # to start with a letter.\n\n identifier = '*' | [a-zA-Z]+ [a-zA-Z\\-_0-9]*;\n\n action emit_identifier {\n emit(:T_IDENT, ts, te)\n }\n\n # Operators\n #\n # Various operators that can be used for filtering nodes. For example,\n # \"$=\" can be used to select attribute values that end with a given\n # string.\n #\n # http:\/\/www.w3.org\/TR\/css3-selectors\/#selectors\n\n op_eq = '=';\n op_space_in = '~=';\n op_starts_with = '^=';\n op_ends_with = '$=';\n op_in = '*=';\n op_hyphen_in = '|=';\n op_child = '>';\n op_fol_direct = '+';\n op_fol = '~';\n\n # Numbers\n #\n # CSS selectors only understand integers, floating points are not\n # supported.\n\n integer = ('-' | '+')* digit+;\n\n action emit_integer {\n value = slice_input(ts, te).to_i\n\n add_token(:T_INT, value)\n }\n\n # Strings\n #\n # Strings can be single or double quoted. They are mainly used for\n # attribute values.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote* dquote);\n string_squote = (squote ^squote* squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n emit(:T_STRING, ts + 1, te - 1)\n }\n\n # Nth numbers\n #\n # These numbers are in the form of 2n+1 and are used for\n # pseudo-selectors such as nth-child(2n+1). The following parts such as\n # \"-1\" and \"+1\" are handled by the `integer` type and the corresponding\n # `emit_integer` action.\n\n #nth_integer = integer 'n';\n #nth_identifier = '+n' | '-n';\n\n #action emit_nth_integer {\n # value = slice_input(ts, te - 1).to_i\n\n # add_token(:T_INT, value)\n # add_token(:T_NTH, nil)\n #}\n\n #action emit_nth_identifier {\n # emit(:T_NTH, ts, te)\n #}\n\n # Pseudo Classes\n #\n # http:\/\/www.w3.org\/TR\/css3-selectors\/#structural-pseudos\n\n action emit_lparen {\n add_token(:T_LPAREN)\n\n fnext pseudo_args;\n }\n\n action emit_rparen {\n add_token(:T_RPAREN)\n\n fnext main;\n }\n\n # Machine used for processing the arguments of a pseudo class. These are\n # handled in a separate machine as these arguments can contain data not\n # allowed elsewhere. For example, \"2n\" is not allowed to appear outside\n # of the arguments list.\n pseudo_args := |*\n nth => { add_token(:T_NTH) };\n minus => { add_token(:T_MINUS) };\n odd => { add_token(:T_ODD) };\n even => { add_token(:T_EVEN) };\n integer => emit_integer;\n rparen => emit_rparen;\n *|;\n\n main := |*\n whitespace | comma | hash | dot | lbrack | rbrack | colon;\n\n # Some of the operators have similar characters (e.g. the \"=\"). As a\n # result we can't use rules like the following:\n #\n # '=' %{ ... };\n # '*=' %{ ... };\n #\n # This would result in both machines being executed for the input\n # \"*=\". The syntax below ensures that only the first match is handled.\n\n op_eq => { add_token(:T_EQ) };\n op_space_in => { add_token(:T_SPACE_IN) };\n op_starts_with => { add_token(:T_STARTS_WITH) };\n op_ends_with => { add_token(:T_ENDS_WITH) };\n op_in => { add_token(:T_IN) };\n op_hyphen_in => { add_token(:T_HYPHEN_IN) };\n op_child => { add_token(:T_CHILD) };\n op_fol_direct => { add_token(:T_FOLLOWING_DIRECT) };\n op_fol => { add_token(:T_FOLLOWING) };\n\n # The pipe character is also used in the |= operator so the action for\n # this is handled separately.\n pipe => { add_token(:T_PIPE) };\n\n lparen => emit_lparen;\n identifier => emit_identifier;\n integer => emit_integer;\n string => emit_string;\n\n any;\n *|;\n }%%\n end # Lexer\n end # CSS\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"861e5c0eb79b8cb267f2881f060460f2f9f0098b","subject":"[testing] allow configurable IO chunk size","message":"[testing] allow configurable IO chunk size\n\nThis allows the IO chunk size to be configured for the BEL Script\nparser. It enables testing how the chunk size may impact parsing.\n","repos":"nbargnesi\/bel.rb,OpenBEL\/bel.rb,OpenBEL\/bel.rb,OpenBEL\/bel.rb,OpenBEL\/bel.rb,OpenBEL\/bel.rb,nbargnesi\/bel.rb,nbargnesi\/bel.rb,OpenBEL\/bel.rb,OpenBEL\/bel.rb,nbargnesi\/bel.rb,nbargnesi\/bel.rb,nbargnesi\/bel.rb","old_file":"lib\/bel\/ragel\/bel.rl","new_file":"lib\/bel\/ragel\/bel.rl","new_contents":"=begin\n%%{\nmachine bel;\n\n include 'common.rl';\n include 'define.rl';\n include 'set.rl';\n include 'statement.rl';\n include 'term.rl';\n\n document_main :=\n (\n\t\t SP* <: (\n\t\t\t DEFINE_KW SP+ ANNOTATION_KW @call_define_annotation |\n\t\t\t DEFINE_KW SP+ NAMESPACE_KW @call_define_namespace |\n\t\t\t SET_KW @call_set |\n\t\t\t COMMENT ^NL+ >s $n NL %comment |\n\t\t\t UNSET_KW @call_unset |\n\t\t\t ^('\\r' | '\\n' | '#' | 'D' | 'S' | 'U') >{fpc -= 1;} >statement_init >call_statement |\n\t\t\t NL @newline\n\t\t\t)\n )+;\n}%%\n=end\n\nrequire_relative 'language'\nrequire_relative 'namespace'\nrequire_relative 'evidence_model'\nrequire_relative 'nonblocking_io_wrapper'\n\nmodule BEL\n module Script\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n # Parse BEL Script +content+ into an enumerator of objects.\n #\n\t\t\t# @param [String, IO] content the BEL Script data to parse\n\t\t\t# @param [Hash] namespaces the\n\t\t\t# {BEL::Namespace::NamespaceDefinition} to use when matching\n\t\t\t#\t\t\t\t prefixes in BEL statements; defaults to empty meaning use the\n\t\t\t#\t\t\t\t +DEFINE NAMESPACE+ definitions in the content\n\t\t\t# @return [Enumerator] the parsed objects\n def parse(content, namespaces = {})\n return nil unless content\n\n parser =\n if content.is_a? String\n\t\t\t\t\t if !content.end_with?(\"\\n\")\n\t\t\t\t\t\t\tcontent << \"\\n\"\n\t\t\t\t\t\tend\n Parser.new(content, namespaces)\n elsif content.respond_to? :read\n IOParser.new(content, namespaces, MAX_LENGTH)\n else\n nil\n end\n\n unless parser\n fail ArgumentError, \"content: expected string or io-like\"\n end\n\n if block_given?\n parser.each do |obj|\n yield obj\n end\n else\n if parser.respond_to? :lazy\n parser.lazy\n else\n parser\n end\n end\n end\n\n # Parse BEL Script +content+, in chunks, into an enumerator of objects.\n # The length of the chunks can be configured with +chunk_length+.\n #\n\t\t\t# @param [IO] io the BEL Script data to parse; if a {String}\n\t\t\t# then {#parse} will be called instead\n\t\t\t# @param [Hash] namespaces the\n\t\t\t# {BEL::Namespace::NamespaceDefinition} to use when matching\n\t\t\t#\t\t\t\t prefixes in BEL statements; defaults to empty meaning use the\n\t\t\t#\t\t\t\t +DEFINE NAMESPACE+ definitions in the content\n\t\t\t# @param [Integer] chunk_length determines how many bytes are\n\t\t\t# buffered at a time when +io+ is an {IO}\n\t\t\t# @return [Enumerator] the parsed objects\n\t\t\tdef parse_chunked(io, namespaces = {}, chunk_length = MAX_LENGTH)\n\t\t\t\tparser =\n\t\t\t\t\tif io.is_a? String\n\t\t\t\t\t\tparse(io, namespaces)\n\t\t\t\t\telsif io.respond_to? :read\n\t\t\t\t\t\tIOParser.new(io, namespaces, chunk_length)\n\t\t\t\t\telse\n\t\t\t\t\t\tnil\n\t\t\t\t\tend\n\n\t\t\t\tunless parser\n\t\t\t\t\tfail ArgumentError, \"content: expected string or io-like\"\n\t\t\t\tend\n\n\t\t\t\tif block_given?\n\t\t\t\t\tparser.each do |obj|\n\t\t\t\t\t\tyield obj\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tif parser.respond_to? :lazy\n\t\t\t\t\t\tparser.lazy\n\t\t\t\t\telse\n\t\t\t\t\t\tparser\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n end\n\n\n private\n\n class Parser\n include Enumerable\n\n def initialize(content, namespaces = {})\n @content = content\n @namespaces =\n case namespaces\n when BEL::Namespace::ResourceIndex\n Hash[namespaces.namespaces.map { |ns| [ns.prefix, ns] }]\n when Hash\n namespaces\n end\n @annotations = {}\n @statement_group = nil\n %% write data;\n end\n\n def each\n eof = :ignored\n buffer = []\n stack = []\n data = @content.unpack('C*')\n\n %% write init;\n %% write exec;\n end\n end\n\n class IOParser\n include Enumerable\n\n def initialize(io, namespaces = {}, max_chunk_length)\n @io = NonblockingIOWrapper.new(io, max_chunk_length)\n @namespaces =\n case namespaces\n when BEL::Namespace::ResourceIndex\n Hash[namespaces.namespaces.map { |ns| [ns.prefix, ns] }]\n when Hash\n namespaces\n end\n @annotations = {}\n @statement_group = nil\n %% write data;\n end\n\n def each\n pe = :ignored\n eof = :ignored\n buffer = []\n stack = []\n\n %% write init;\n\n\t\t\t\t@io.each do |chunk|\n\t\t\t\t\tdata = chunk.unpack('C*')\n\t\t\t\t\tp = 0\n\t\t\t\t\tpe = data.length\n\n\t\t\t\t\t%% write exec;\n\t\t\t\tend\n end\n end\n end\nend\n# vim: ts=2 sw=2:\n# encoding: utf-8\n","old_contents":"=begin\n%%{\nmachine bel;\n\n include 'common.rl';\n include 'define.rl';\n include 'set.rl';\n include 'statement.rl';\n include 'term.rl';\n\n document_main :=\n (\n\t\t SP* <: (\n\t\t\t DEFINE_KW SP+ ANNOTATION_KW @call_define_annotation |\n\t\t\t DEFINE_KW SP+ NAMESPACE_KW @call_define_namespace |\n\t\t\t SET_KW @call_set |\n\t\t\t COMMENT ^NL+ >s $n NL %comment |\n\t\t\t UNSET_KW @call_unset |\n\t\t\t ^('\\r' | '\\n' | '#' | 'D' | 'S' | 'U') >{fpc -= 1;} >statement_init >call_statement |\n\t\t\t NL @newline\n\t\t\t)\n )+;\n}%%\n=end\n\nrequire_relative 'language'\nrequire_relative 'namespace'\nrequire_relative 'evidence_model'\nrequire_relative 'nonblocking_io_wrapper'\n\nmodule BEL\n module Script\n\n class << self\n def parse(content, namespaces = {})\n return nil unless content\n\n parser =\n if content.is_a? String\n\t\t\t\t\t if !content.end_with?(\"\\n\")\n\t\t\t\t\t\t\tcontent << \"\\n\"\n\t\t\t\t\t\tend\n Parser.new(content, namespaces)\n elsif content.respond_to? :read\n IOParser.new(content, namespaces)\n else\n nil\n end\n\n unless parser\n fail ArgumentError, \"content: expected string or io-like\"\n end\n\n if block_given?\n parser.each do |obj|\n yield obj\n end\n else\n if parser.respond_to? :lazy\n parser.lazy\n else\n parser\n end\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n\n def initialize(content, namespaces = {})\n @content = content\n @namespaces =\n case namespaces\n when BEL::Namespace::ResourceIndex\n Hash[namespaces.namespaces.map { |ns| [ns.prefix, ns] }]\n when Hash\n namespaces\n end\n @annotations = {}\n @statement_group = nil\n %% write data;\n end\n\n def each\n eof = :ignored\n buffer = []\n stack = []\n data = @content.unpack('C*')\n\n %% write init;\n %% write exec;\n end\n end\n\n class IOParser\n include Enumerable\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def initialize(io, namespaces = {})\n @io = NonblockingIOWrapper.new(io, MAX_LENGTH)\n @namespaces =\n case namespaces\n when BEL::Namespace::ResourceIndex\n Hash[namespaces.namespaces.map { |ns| [ns.prefix, ns] }]\n when Hash\n namespaces\n end\n @annotations = {}\n @statement_group = nil\n %% write data;\n end\n\n def each\n pe = :ignored\n eof = :ignored\n buffer = []\n stack = []\n\n %% write init;\n\n leftover = []\n my_ts = nil\n my_te = nil\n \n\t\t\t\t@io.each do |chunk|\n\t\t\t\t\tdata = leftover + chunk.unpack('C*')\n\t\t\t\t\tp = 0\n\t\t\t\t\tpe = data.length\n\t\t\t\t\t%% write exec;\n\t\t\t\t\tif my_ts\n\t\t\t\t\t\tleftover = data[my_ts..-1]\n\t\t\t\t\t\tmy_te = my_te - my_ts if my_te\n\t\t\t\t\t\tmy_ts = 0\n\t\t\t\t\telse\n\t\t\t\t\t\tleftover = []\n\t\t\t\t\tend\n\t\t\t\tend\n end\n end\n end\nend\n\nif __FILE__ == $0\n namespaces = BEL::Namespace::DEFAULT_NAMESPACES.map { |ns|\n [ns.prefix, ns]\n }.to_h\n\n if ARGV[0]\n File.open(ARGV[0], 'r:UTF-8') do |f|\n BEL::Script.parse(f, namespaces).each do |obj|\n puts obj\n end\n end\n else\n BEL::Script.parse($stdin, namespaces).each do |obj|\n puts obj\n end\n end\nend\n# vim: ts=2 sw=2:\n# encoding: utf-8\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"db2d0d482e072be2bc1d0b9e7df41952667eb429","subject":"cfg: Use log_* instead of fmt.","message":"cfg: Use log_* instead of fmt.\n","repos":"niklata\/ndhs,niklata\/ndhs","old_file":"cfg.rl","new_file":"cfg.rl","new_contents":"\/* cfg.rl - configure file parser for ndhs\n *\n * Copyright 2016-2020 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"dhcp_state.hpp\"\nextern \"C\" {\n#include \"nk\/log.h\"\n}\nextern void set_user_runas(size_t linenum, std::string &&username);\nextern void set_chroot_path(size_t linenum, std::string &&path);\n\n#define MAX_LINE 2048\n\nextern void create_dns_search_blob();\n\nstruct cfg_parse_state {\n cfg_parse_state() : st(nullptr), cs(0), last_addr(addr_type::null), default_lifetime(7200),\n default_preference(0), parse_error(false) {}\n void newline() {\n duid.clear();\n iaid.clear();\n macaddr.clear();\n ipaddr.clear();\n ipaddr2.clear();\n last_addr = addr_type::null;\n parse_error = false;\n }\n const char *st;\n int cs;\n\n std::string duid;\n std::string iaid;\n std::string macaddr;\n std::string ipaddr;\n std::string ipaddr2;\n addr_type last_addr;\n std::string interface;\n uint32_t default_lifetime;\n uint8_t default_preference;\n bool parse_error;\n};\n\nstatic inline std::string lc_string(const char *s, size_t slen)\n{\n auto r = std::string(s, slen);\n for (auto &i: r) i = tolower(i);\n return r;\n}\n\n%%{\n machine cfg_line_m;\n access cps.;\n\n action St { cps.st = p; }\n\n action DuidEn { cps.duid = lc_string(cps.st, p - cps.st); }\n action IaidEn { cps.iaid = lc_string(cps.st, p - cps.st); }\n action MacAddrEn { cps.macaddr = lc_string(cps.st, p - cps.st); }\n action V4AddrEn {\n cps.ipaddr = lc_string(cps.st, p - cps.st);\n cps.last_addr = addr_type::v4;\n }\n action V6AddrEn {\n cps.ipaddr = lc_string(cps.st, p - cps.st);\n cps.last_addr = addr_type::v6;\n }\n action Bind4En { emplace_bind(linenum, std::string(cps.st, p - cps.st), true); }\n action Bind6En { emplace_bind(linenum, std::string(cps.st, p - cps.st), false); }\n action UserEn { set_user_runas(linenum, std::string(cps.st, p - cps.st)); }\n action ChrootEn { set_chroot_path(linenum, std::string(cps.st, p - cps.st)); }\n action DefLifeEn {\n if (auto t = nk::from_string(cps.st, p - cps.st)) cps.default_lifetime = *t; else {\n cps.parse_error = true;\n fbreak;\n }\n }\n action DefPrefEn {\n if (auto t = nk::from_string(cps.st, p - cps.st)) cps.default_preference = *t; else {\n log_warning(\"default_preference on line %zu out of range [0,255]: %s\",\n linenum, std::string(cps.st, p - cps.st));\n cps.parse_error = true;\n fbreak;\n }\n }\n action InterfaceEn {\n cps.interface = std::string(cps.st, p - cps.st);\n emplace_interface(linenum, cps.interface, cps.default_preference);\n }\n action DnsServerEn {\n emplace_dns_server(linenum, cps.interface, cps.ipaddr, cps.last_addr);\n }\n action DnsSearchEn {\n emplace_dns_search(linenum, cps.interface, std::string(cps.st, p - cps.st));\n }\n action NtpServerEn {\n emplace_ntp_server(linenum, cps.interface, cps.ipaddr, cps.last_addr);\n }\n action SubnetEn {\n emplace_subnet(linenum, cps.interface, cps.ipaddr);\n }\n action GatewayEn {\n emplace_gateway(linenum, cps.interface, cps.ipaddr);\n }\n action BroadcastEn {\n emplace_broadcast(linenum, cps.interface, cps.ipaddr);\n }\n action DynRangePreEn {\n cps.ipaddr2 = std::move(cps.ipaddr);\n }\n action DynRangeEn {\n emplace_dynamic_range(linenum, cps.interface, cps.ipaddr2, cps.ipaddr,\n cps.default_lifetime);\n }\n action DynamicV6En {\n emplace_dynamic_v6(linenum, cps.interface);\n }\n action V4EntryEn {\n emplace_dhcp_state(linenum, cps.interface, cps.macaddr, cps.ipaddr,\n cps.default_lifetime);\n }\n action V6EntryEn {\n if (auto iaid = nk::from_string(cps.iaid)) {\n emplace_dhcp_state(linenum, cps.interface, std::move(cps.duid),\n *iaid, cps.ipaddr, cps.default_lifetime);\n } else {\n cps.parse_error = true;\n fbreak;\n }\n }\n\n duid = (xdigit+ | (xdigit{2} ('-' xdigit{2})*)+) >St %DuidEn;\n iaid = digit+ >St %IaidEn;\n macaddr = ((xdigit{2} ':'){5} xdigit{2}) >St %MacAddrEn;\n v4_addr = (digit{1,3} | '.')+ >St %V4AddrEn;\n v6_addr = (xdigit{1,4} | ':')+ >St %V6AddrEn;\n\n comment = space* ('\/\/' any*)?;\n tcomment = (space+ '\/\/' any*)?;\n bind4 = space* 'bind4' (space+ alnum+ >St %Bind4En)+ tcomment;\n bind6 = space* 'bind6' (space+ alnum+ >St %Bind6En)+ tcomment;\n user = space* 'user' space+ graph+ >St %UserEn tcomment;\n chroot = space* 'chroot' space+ graph+ >St %ChrootEn tcomment;\n default_lifetime = space* 'default_lifetime' space+ digit+ >St %DefLifeEn tcomment;\n default_preference = space* 'default_preference' space+ digit+ >St %DefPrefEn tcomment;\n interface = space* 'interface' space+ alnum+ >St %InterfaceEn tcomment;\n dns_server = space* 'dns_server' (space+ (v4_addr | v6_addr) %DnsServerEn)+ tcomment;\n dns_search = space* 'dns_search' (space+ graph+ >St %DnsSearchEn)+ tcomment;\n ntp_server = space* 'ntp_server' (space+ (v4_addr | v6_addr) %NtpServerEn)+ tcomment;\n subnet = space* 'subnet' space+ v4_addr %SubnetEn tcomment;\n gateway = space* 'gateway' space+ v4_addr %GatewayEn tcomment;\n broadcast = space* 'broadcast' space+ v4_addr %BroadcastEn tcomment;\n dynamic_range = space* 'dynamic_range' space+ v4_addr %DynRangePreEn space+ v4_addr %DynRangeEn tcomment;\n dynamic_v6 = space* 'dynamic_v6' %DynamicV6En tcomment;\n v4_entry = space* 'v4' space+ macaddr space+ v4_addr tcomment;\n v6_entry = space* 'v6' space+ duid space+ iaid space+ v6_addr tcomment;\n\n main := comment | bind4 | bind6 | user | chroot | default_lifetime | default_preference\n | interface | dns_server | dns_search | ntp_server | subnet | gateway | broadcast\n | dynamic_range | dynamic_v6 | v6_entry %V6EntryEn | v4_entry %V4EntryEn;\n}%%\n\n%% write data;\n\nstatic int do_parse_cfg_line(cfg_parse_state &cps, const char *p, size_t plen,\n const size_t linenum)\n{\n const char *pe = p + plen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (cps.parse_error) return -1;\n if (cps.cs >= cfg_line_m_first_final)\n return 1;\n if (cps.cs == cfg_line_m_error)\n return -1;\n return -2;\n}\n\nvoid parse_config(const std::string &path)\n{\n char buf[MAX_LINE];\n auto f = fopen(path.c_str(), \"r\");\n if (!f) {\n log_warning(\"%s: failed to open config file \\\"%s\\\" for read: %s\",\n __func__, path.c_str(), strerror(errno));\n return;\n }\n SCOPE_EXIT{ fclose(f); };\n size_t linenum = 0;\n cfg_parse_state ps;\n while (!feof(f)) {\n if (!fgets(buf, sizeof buf, f)) {\n if (!feof(f))\n log_warning(\"%s: io error fetching line of '%s'\", __func__, path.c_str());\n break;\n }\n auto llen = strlen(buf);\n if (llen == 0)\n continue;\n if (buf[llen-1] == '\\n')\n buf[--llen] = 0;\n ++linenum;\n ps.newline();\n const auto r = do_parse_cfg_line(ps, buf, llen, linenum);\n if (r < 0) {\n if (r == -2)\n log_warning(\"%s: Incomplete configuration at line %zu; ignoring\",\n __func__, linenum);\n else\n log_warning(\"%s: Malformed configuration at line %zu; ignoring.\",\n __func__, linenum);\n continue;\n }\n }\n create_blobs();\n}\n\n","old_contents":"\/* cfg.rl - configure file parser for ndhs\n *\n * Copyright 2016-2017 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"dhcp_state.hpp\"\nextern void set_user_runas(size_t linenum, std::string &&username);\nextern void set_chroot_path(size_t linenum, std::string &&path);\n\n#define MAX_LINE 2048\n\nextern void create_dns_search_blob();\n\nstruct cfg_parse_state {\n cfg_parse_state() : st(nullptr), cs(0), last_addr(addr_type::null), default_lifetime(7200),\n default_preference(0), parse_error(false) {}\n void newline() {\n duid.clear();\n iaid.clear();\n macaddr.clear();\n ipaddr.clear();\n ipaddr2.clear();\n last_addr = addr_type::null;\n parse_error = false;\n }\n const char *st;\n int cs;\n\n std::string duid;\n std::string iaid;\n std::string macaddr;\n std::string ipaddr;\n std::string ipaddr2;\n addr_type last_addr;\n std::string interface;\n uint32_t default_lifetime;\n uint8_t default_preference;\n bool parse_error;\n};\n\nstatic inline std::string lc_string(const char *s, size_t slen)\n{\n auto r = std::string(s, slen);\n for (auto &i: r) i = tolower(i);\n return r;\n}\n\n%%{\n machine cfg_line_m;\n access cps.;\n\n action St { cps.st = p; }\n\n action DuidEn { cps.duid = lc_string(cps.st, p - cps.st); }\n action IaidEn { cps.iaid = lc_string(cps.st, p - cps.st); }\n action MacAddrEn { cps.macaddr = lc_string(cps.st, p - cps.st); }\n action V4AddrEn {\n cps.ipaddr = lc_string(cps.st, p - cps.st);\n cps.last_addr = addr_type::v4;\n }\n action V6AddrEn {\n cps.ipaddr = lc_string(cps.st, p - cps.st);\n cps.last_addr = addr_type::v6;\n }\n action Bind4En { emplace_bind(linenum, std::string(cps.st, p - cps.st), true); }\n action Bind6En { emplace_bind(linenum, std::string(cps.st, p - cps.st), false); }\n action UserEn { set_user_runas(linenum, std::string(cps.st, p - cps.st)); }\n action ChrootEn { set_chroot_path(linenum, std::string(cps.st, p - cps.st)); }\n action DefLifeEn {\n if (auto t = nk::from_string(cps.st, p - cps.st)) cps.default_lifetime = *t; else {\n cps.parse_error = true;\n fbreak;\n }\n }\n action DefPrefEn {\n if (auto t = nk::from_string(cps.st, p - cps.st)) cps.default_preference = *t; else {\n fmt::print(stderr, \"default_preference on line {} out of range [0,255]: {}\\n\",\n linenum, std::string(cps.st, p - cps.st));\n cps.parse_error = true;\n fbreak;\n }\n }\n action InterfaceEn {\n cps.interface = std::string(cps.st, p - cps.st);\n emplace_interface(linenum, cps.interface, cps.default_preference);\n }\n action DnsServerEn {\n emplace_dns_server(linenum, cps.interface, cps.ipaddr, cps.last_addr);\n }\n action DnsSearchEn {\n emplace_dns_search(linenum, cps.interface, std::string(cps.st, p - cps.st));\n }\n action NtpServerEn {\n emplace_ntp_server(linenum, cps.interface, cps.ipaddr, cps.last_addr);\n }\n action SubnetEn {\n emplace_subnet(linenum, cps.interface, cps.ipaddr);\n }\n action GatewayEn {\n emplace_gateway(linenum, cps.interface, cps.ipaddr);\n }\n action BroadcastEn {\n emplace_broadcast(linenum, cps.interface, cps.ipaddr);\n }\n action DynRangePreEn {\n cps.ipaddr2 = std::move(cps.ipaddr);\n }\n action DynRangeEn {\n emplace_dynamic_range(linenum, cps.interface, cps.ipaddr2, cps.ipaddr,\n cps.default_lifetime);\n }\n action DynamicV6En {\n emplace_dynamic_v6(linenum, cps.interface);\n }\n action V4EntryEn {\n emplace_dhcp_state(linenum, cps.interface, cps.macaddr, cps.ipaddr,\n cps.default_lifetime);\n }\n action V6EntryEn {\n if (auto iaid = nk::from_string(cps.iaid)) {\n emplace_dhcp_state(linenum, cps.interface, std::move(cps.duid),\n *iaid, cps.ipaddr, cps.default_lifetime);\n } else {\n cps.parse_error = true;\n fbreak;\n }\n }\n\n duid = (xdigit+ | (xdigit{2} ('-' xdigit{2})*)+) >St %DuidEn;\n iaid = digit+ >St %IaidEn;\n macaddr = ((xdigit{2} ':'){5} xdigit{2}) >St %MacAddrEn;\n v4_addr = (digit{1,3} | '.')+ >St %V4AddrEn;\n v6_addr = (xdigit{1,4} | ':')+ >St %V6AddrEn;\n\n comment = space* ('\/\/' any*)?;\n tcomment = (space+ '\/\/' any*)?;\n bind4 = space* 'bind4' (space+ alnum+ >St %Bind4En)+ tcomment;\n bind6 = space* 'bind6' (space+ alnum+ >St %Bind6En)+ tcomment;\n user = space* 'user' space+ graph+ >St %UserEn tcomment;\n chroot = space* 'chroot' space+ graph+ >St %ChrootEn tcomment;\n default_lifetime = space* 'default_lifetime' space+ digit+ >St %DefLifeEn tcomment;\n default_preference = space* 'default_preference' space+ digit+ >St %DefPrefEn tcomment;\n interface = space* 'interface' space+ alnum+ >St %InterfaceEn tcomment;\n dns_server = space* 'dns_server' (space+ (v4_addr | v6_addr) %DnsServerEn)+ tcomment;\n dns_search = space* 'dns_search' (space+ graph+ >St %DnsSearchEn)+ tcomment;\n ntp_server = space* 'ntp_server' (space+ (v4_addr | v6_addr) %NtpServerEn)+ tcomment;\n subnet = space* 'subnet' space+ v4_addr %SubnetEn tcomment;\n gateway = space* 'gateway' space+ v4_addr %GatewayEn tcomment;\n broadcast = space* 'broadcast' space+ v4_addr %BroadcastEn tcomment;\n dynamic_range = space* 'dynamic_range' space+ v4_addr %DynRangePreEn space+ v4_addr %DynRangeEn tcomment;\n dynamic_v6 = space* 'dynamic_v6' %DynamicV6En tcomment;\n v4_entry = space* 'v4' space+ macaddr space+ v4_addr tcomment;\n v6_entry = space* 'v6' space+ duid space+ iaid space+ v6_addr tcomment;\n\n main := comment | bind4 | bind6 | user | chroot | default_lifetime | default_preference\n | interface | dns_server | dns_search | ntp_server | subnet | gateway | broadcast\n | dynamic_range | dynamic_v6 | v6_entry %V6EntryEn | v4_entry %V4EntryEn;\n}%%\n\n%% write data;\n\nstatic int do_parse_cfg_line(cfg_parse_state &cps, const char *p, size_t plen,\n const size_t linenum)\n{\n const char *pe = p + plen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (cps.parse_error) return -1;\n if (cps.cs >= cfg_line_m_first_final)\n return 1;\n if (cps.cs == cfg_line_m_error)\n return -1;\n return -2;\n}\n\nvoid parse_config(const std::string &path)\n{\n char buf[MAX_LINE];\n auto f = fopen(path.c_str(), \"r\");\n if (!f) {\n fmt::print(stderr, \"{}: failed to open config file \\\"{}\\\" for read: {}\\n\",\n __func__, path, strerror(errno));\n return;\n }\n SCOPE_EXIT{ fclose(f); };\n size_t linenum = 0;\n cfg_parse_state ps;\n while (!feof(f)) {\n if (!fgets(buf, sizeof buf, f)) {\n if (!feof(f))\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\", __func__, path);\n break;\n }\n auto llen = strlen(buf);\n if (llen == 0)\n continue;\n if (buf[llen-1] == '\\n')\n buf[--llen] = 0;\n ++linenum;\n ps.newline();\n const auto r = do_parse_cfg_line(ps, buf, llen, linenum);\n if (r < 0) {\n if (r == -2)\n fmt::print(stderr, \"{}: Incomplete configuration at line {}; ignoring\\n\",\n __func__, linenum);\n else\n fmt::print(stderr, \"{}: Malformed configuration at line {}; ignoring.\\n\",\n __func__, linenum);\n continue;\n }\n }\n create_blobs();\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f18e8893def85057e4c9e18b0ef381cecd982f89","subject":"Removed the buffering crap from the lexer.","message":"Removed the buffering crap from the lexer.\n","repos":"jeffreybaird\/oga,ttasanen\/oga,dfockler\/oga,YorickPeterse\/oga,altmetric\/oga,YorickPeterse\/oga,ttasanen\/oga,jeffreybaird\/oga,altmetric\/oga,ttasanen\/oga,dfockler\/oga,jeffreybaird\/oga,altmetric\/oga,YorickPeterse\/oga,jeffreybaird\/oga,altmetric\/oga,dfockler\/oga,YorickPeterse\/oga,ttasanen\/oga,ttasanen\/oga,altmetric\/oga,dfockler\/oga,jeffreybaird\/oga,dfockler\/oga,YorickPeterse\/oga","old_file":"lib\/oga\/xml\/lexer.rl","new_file":"lib\/oga\/xml\/lexer.rl","new_contents":"%%machine lexer; # %\n\nmodule Oga\n module XML\n ##\n # Low level lexer that supports both XML and HTML (using an extra option).\n # To lex HTML input set the `:html` option to `true` when creating an\n # instance of the lexer:\n #\n # lexer = Oga::XML::Lexer.new(:html => true)\n #\n # @!attribute [r] html\n # @return [TrueClass|FalseClass]\n #\n # @!attribute [r] tokens\n # @return [Array]\n #\n class Lexer\n %% write data;\n\n # % fix highlight\n\n attr_reader :html\n\n ##\n # Names of the HTML void elements that should be handled when HTML lexing\n # is enabled.\n #\n # @return [Set]\n #\n HTML_VOID_ELEMENTS = Set.new([\n 'area',\n 'base',\n 'br',\n 'col',\n 'command',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n ])\n\n ##\n # @param [String] data The data to lex.\n #\n # @param [Hash] options\n #\n # @option options [Symbol] :html When set to `true` the lexer will treat\n # the input as HTML instead of SGML\/XML. This makes it possible to lex\n # HTML void elements such as ``.\n #\n def initialize(data, options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n end\n\n @data = data\n\n reset\n end\n\n ##\n # Resets the internal state of the lexer. Typically you don't need to\n # call this method yourself as its called by #lex after lexing a given\n # String.\n #\n def reset\n @line = 1\n @elements = []\n\n @buffer_start_position = nil\n end\n\n ##\n # Gathers all the tokens for the input and returns them as an Array.\n #\n # This method resets the internal state of the lexer after consuming the\n # input.\n #\n # @param [String] data The string to consume.\n # @return [Array]\n # @see #advance\n #\n def lex\n tokens = []\n\n advance do |token|\n tokens << token\n end\n\n reset\n\n return tokens\n end\n\n ##\n # Advances through the input and generates the corresponding tokens. Each\n # token is yielded to the supplied block.\n #\n # Each token is an Array in the following format:\n #\n # [TYPE, VALUE]\n #\n # The type is a symbol, the value is either nil or a String.\n #\n # This method stores the supplied block in `@block` and resets it after\n # the lexer loop has finished.\n #\n # This method does *not* reset the internal state of the lexer.\n #\n #\n # @param [String] data The String to consume.\n # @return [Array]\n #\n def advance(&block)\n @block = block\n\n data = @data\n ts = nil\n te = nil\n stack = []\n top = 0\n cs = self.class.lexer_start\n act = 0\n eof = @data.bytesize\n p = 0\n pe = eof\n\n _lexer_eof_trans = self.class.send(:_lexer_eof_trans)\n _lexer_from_state_actions = self.class.send(:_lexer_from_state_actions)\n _lexer_index_offsets = self.class.send(:_lexer_index_offsets)\n _lexer_indicies = self.class.send(:_lexer_indicies)\n _lexer_key_spans = self.class.send(:_lexer_key_spans)\n _lexer_to_state_actions = self.class.send(:_lexer_to_state_actions)\n _lexer_trans_actions = self.class.send(:_lexer_trans_actions)\n _lexer_trans_keys = self.class.send(:_lexer_trans_keys)\n _lexer_trans_targs = self.class.send(:_lexer_trans_targs)\n\n %% write exec;\n\n # % fix highlight\n ensure\n @block = nil\n end\n\n ##\n # @return [TrueClass|FalseClass]\n #\n def html?\n return !!html\n end\n\n private\n\n ##\n # @param [Fixnum] amount The amount of lines to advance.\n #\n def advance_line(amount = 1)\n @line += amount\n end\n\n ##\n # Emits a token who's value is based on the supplied start\/stop position.\n #\n # @param [Symbol] type The token type.\n # @param [Fixnum] start\n # @param [Fixnum] stop\n #\n # @see #text\n # @see #add_token\n #\n def emit(type, start, stop)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n ##\n # Returns the text of the current buffer based on the supplied start and\n # stop position.\n #\n # @param [Fixnum] start\n # @param [Fixnum] stop\n # @return [String]\n #\n def text(start, stop)\n return @data.byteslice(start, stop - start)\n end\n\n ##\n # Adds a token with the given type and value to the list.\n #\n # @param [Symbol] type The token type.\n # @param [String] value The token value.\n #\n def add_token(type, value = nil)\n token = [type, value, @line]\n\n @block.call(token)\n end\n\n ##\n # Enables buffering starting at the given position.\n #\n # @param [Fixnum] position The start position of the buffer.\n #\n def start_buffer(position)\n @buffer_start_position = position\n end\n\n ##\n # Emits a text token.\n #\n # @param [Fixnum] start\n # @param [Fixnum] stop\n #\n def emit_text(start, stop)\n content = text(start, stop)\n\n unless content.empty?\n add_token(:T_TEXT, content)\n\n lines = content.count(\"\\n\")\n\n advance_line(lines) if lines > 0\n end\n end\n\n ##\n # Returns the name of the element we're currently in.\n #\n # @return [String]\n #\n def current_element\n return @elements.last\n end\n\n %%{\n getkey (data.getbyte(p) || 0);\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n ^dquote+ => {\n emit(:T_STRING, ts, te)\n };\n\n dquote => { fret; };\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n ^squote+ => {\n emit(:T_STRING, ts, te)\n };\n\n squote => { fret; };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { emit(:T_DOCTYPE_TYPE, ts, te) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => { emit(:T_DOCTYPE_NAME, ts, te) };\n\n '>' => {\n add_token(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n add_token(:T_CDATA_START)\n\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n any* cdata_end => {\n emit_text(ts, te - 3)\n add_token(:T_CDATA_END)\n\n fret;\n };\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n add_token(:T_COMMENT_START)\n\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n any* comment_end => {\n emit_text(ts, te - 3)\n add_token(:T_COMMENT_END)\n\n fret;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n add_token(:T_XML_DECL_START)\n\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n add_token(:T_XML_DECL_END)\n\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => { emit(:T_ATTR, ts, te) };\n\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n add_token(:T_ELEM_START)\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(ts + 1, te)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n end\n\n @elements << name if html?\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => { advance_line };\n\n # Attribute names.\n identifier => { emit(:T_ATTR, ts, te) };\n\n # Attribute values.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_END, nil)\n @elements.pop\n end\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n ^('<' | '>')+ => {\n emit_text(ts, te)\n };\n *|;\n }%%\n end # Lexer\n end # XML\nend # Oga\n","old_contents":"%%machine lexer; # %\n\nmodule Oga\n module XML\n ##\n # Low level lexer that supports both XML and HTML (using an extra option).\n # To lex HTML input set the `:html` option to `true` when creating an\n # instance of the lexer:\n #\n # lexer = Oga::XML::Lexer.new(:html => true)\n #\n # @!attribute [r] html\n # @return [TrueClass|FalseClass]\n #\n # @!attribute [r] tokens\n # @return [Array]\n #\n class Lexer\n %% write data;\n\n # % fix highlight\n\n attr_reader :html\n\n ##\n # Names of the HTML void elements that should be handled when HTML lexing\n # is enabled.\n #\n # @return [Set]\n #\n HTML_VOID_ELEMENTS = Set.new([\n 'area',\n 'base',\n 'br',\n 'col',\n 'command',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n ])\n\n ##\n # @param [String] data The data to lex.\n #\n # @param [Hash] options\n #\n # @option options [Symbol] :html When set to `true` the lexer will treat\n # the input as HTML instead of SGML\/XML. This makes it possible to lex\n # HTML void elements such as ``.\n #\n def initialize(data, options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n end\n\n @data = data\n\n reset\n end\n\n ##\n # Resets the internal state of the lexer. Typically you don't need to\n # call this method yourself as its called by #lex after lexing a given\n # String.\n #\n def reset\n @line = 1\n @elements = []\n\n @buffer_start_position = nil\n end\n\n ##\n # Gathers all the tokens for the input and returns them as an Array.\n #\n # This method resets the internal state of the lexer after consuming the\n # input.\n #\n # @param [String] data The string to consume.\n # @return [Array]\n # @see #advance\n #\n def lex\n tokens = []\n\n advance do |token|\n tokens << token\n end\n\n reset\n\n return tokens\n end\n\n ##\n # Advances through the input and generates the corresponding tokens. Each\n # token is yielded to the supplied block.\n #\n # Each token is an Array in the following format:\n #\n # [TYPE, VALUE]\n #\n # The type is a symbol, the value is either nil or a String.\n #\n # This method stores the supplied block in `@block` and resets it after\n # the lexer loop has finished.\n #\n # This method does *not* reset the internal state of the lexer.\n #\n #\n # @param [String] data The String to consume.\n # @return [Array]\n #\n def advance(&block)\n @block = block\n\n data = @data\n ts = nil\n te = nil\n stack = []\n top = 0\n cs = self.class.lexer_start\n act = 0\n eof = @data.bytesize\n p = 0\n pe = eof\n\n _lexer_eof_trans = self.class.send(:_lexer_eof_trans)\n _lexer_from_state_actions = self.class.send(:_lexer_from_state_actions)\n _lexer_index_offsets = self.class.send(:_lexer_index_offsets)\n _lexer_indicies = self.class.send(:_lexer_indicies)\n _lexer_key_spans = self.class.send(:_lexer_key_spans)\n _lexer_to_state_actions = self.class.send(:_lexer_to_state_actions)\n _lexer_trans_actions = self.class.send(:_lexer_trans_actions)\n _lexer_trans_keys = self.class.send(:_lexer_trans_keys)\n _lexer_trans_targs = self.class.send(:_lexer_trans_targs)\n\n %% write exec;\n\n # % fix highlight\n ensure\n @block = nil\n end\n\n ##\n # @return [TrueClass|FalseClass]\n #\n def html?\n return !!html\n end\n\n private\n\n ##\n # @param [Fixnum] amount The amount of lines to advance.\n #\n def advance_line(amount = 1)\n @line += amount\n end\n\n ##\n # Emits a token who's value is based on the supplied start\/stop position.\n #\n # @param [Symbol] type The token type.\n # @param [Fixnum] start\n # @param [Fixnum] stop\n #\n # @see #text\n # @see #add_token\n #\n def emit(type, start, stop)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n ##\n # Returns the text of the current buffer based on the supplied start and\n # stop position.\n #\n # @param [Fixnum] start\n # @param [Fixnum] stop\n # @return [String]\n #\n def text(start, stop)\n return @data.byteslice(start, stop - start)\n end\n\n ##\n # Adds a token with the given type and value to the list.\n #\n # @param [Symbol] type The token type.\n # @param [String] value The token value.\n #\n def add_token(type, value = nil)\n token = [type, value, @line]\n\n @block.call(token)\n end\n\n ##\n # Enables buffering starting at the given position.\n #\n # @param [Fixnum] position The start position of the buffer.\n #\n def start_buffer(position)\n @buffer_start_position = position\n end\n\n ##\n # Emits the current buffer if we have any. The current line number is\n # advanced based on the amount of newlines in the buffer.\n #\n # @param [Fixnum] position The end position of the buffer.\n # @param [Symbol] type The type of node to emit.\n #\n def emit_buffer(position, type = :T_TEXT)\n return unless @buffer_start_position\n\n content = text(@buffer_start_position, position)\n\n unless content.empty?\n add_token(type, content)\n\n lines = content.count(\"\\n\")\n\n advance_line(lines) if lines > 0\n end\n\n @buffer_start_position = nil\n end\n\n ##\n # Returns the name of the element we're currently in.\n #\n # @return [String]\n #\n def current_element\n return @elements.last\n end\n\n %%{\n getkey (data.getbyte(p) || 0);\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n action start_string_dquote {\n start_buffer(te)\n\n fcall string_dquote;\n }\n\n action start_string_squote {\n start_buffer(te)\n\n fcall string_squote;\n }\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n dquote => {\n emit_buffer(ts, :T_STRING)\n fret;\n };\n\n any;\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n squote => {\n emit_buffer(ts, :T_STRING)\n fret;\n };\n\n any;\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { emit(:T_DOCTYPE_TYPE, ts, te) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => { emit(:T_DOCTYPE_NAME, ts, te) };\n\n '>' => {\n add_token(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n emit_buffer(ts)\n add_token(:T_CDATA_START)\n\n start_buffer(te)\n\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n cdata_end => {\n emit_buffer(ts)\n add_token(:T_CDATA_END)\n\n fret;\n };\n\n any;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n emit_buffer(ts)\n add_token(:T_COMMENT_START)\n\n start_buffer(te)\n\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n comment_end => {\n emit_buffer(ts)\n add_token(:T_COMMENT_END)\n\n fret;\n };\n\n any;\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n emit_buffer(ts)\n add_token(:T_XML_DECL_START)\n\n start_buffer(te)\n\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n emit_buffer(ts)\n add_token(:T_XML_DECL_END)\n\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => { emit(:T_ATTR, ts, te) };\n\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n emit_buffer(ts)\n add_token(:T_ELEM_START)\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(ts + 1, te)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n end\n\n @elements << name if html?\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => { advance_line };\n\n # Attribute names.\n identifier => { emit(:T_ATTR, ts, te) };\n\n # Attribute values.\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_END, nil)\n @elements.pop\n end\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n emit_buffer(ts)\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n any => {\n # First character, start buffering (unless we already are buffering).\n start_buffer(ts) unless @buffer_start_position\n\n # EOF, emit the text buffer.\n if te == eof\n emit_buffer(te)\n end\n };\n *|;\n }%%\n end # Lexer\n end # XML\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"4830729d7f2e7e3c4180eedcb7cbb3007a5a6030","subject":"Reduce object allocation in unescape_char lexer action","message":"Reduce object allocation in unescape_char lexer action\n","repos":"bbatsov\/parser,modulexcite\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n\n attr_accessor :cond, :cmdarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n end\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if @source_pts.size > 1_000_000 && @source.respond_to?(:encode)\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_key_spans = self.class.send :_lex_key_spans\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n _lex_eof_trans = self.class.send :_lex_eof_trans\n\n p, pe, eof = @p, @source.length + 1, @source.length + 1\n\n @command_state = (@cs == self.class.lex_en_expr_value ||\n @cs == self.class.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n [ false, [ '$eof', range(p, p) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |value| emit(:tINTEGER, value) } }\n | 'r' % { @num_xfrm = lambda { |value| emit(:tRATIONAL, Rational(value)) } }\n | 'i' % { @num_xfrm = lambda { |value| emit(:tIMAGINARY, Complex(0, value)) } }\n | 'ri' % { @num_xfrm = lambda { |value| emit(:tIMAGINARY, Complex(0, Rational(value))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |digits| emit(:tFLOAT, Float(digits)) } }\n | 'i' % { @num_xfrm = lambda { |digits| emit(:tIMAGINARY, Complex(0, Float(digits))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |digits| emit(:tRATIONAL, Rational(digits)) } }\n | 'ri' % { @num_xfrm = lambda { |digits| emit(:tIMAGINARY, Complex(0, Rational(digits))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n @escape = ESCAPES.fetch(@source[p - 1].chr, @source[p - 1].chr)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :error, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :error, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :error, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts < extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a ?b\n # Character literal.\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n w_space+ ( [%\/] ( c_any - c_space_nl - '=' ) # \/\n # a < { fhold; fhold; fgoto expr_beg; };\n\n # x \/1\n # Ambiguous regexp literal.\n w_space+ '\/'\n => {\n diagnostic :warning, :ambiguous_literal, nil, range(@te - 1, @te)\n\n fhold; fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = $2.empty? ? '\"' : $2\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | c_any - c_space_nl - e_bs % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? '_'\n diagnostic :error, :trailing_in_number, { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_arg; fbreak; };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n\n attr_accessor :cond, :cmdarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n end\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if @source_pts.size > 1_000_000 && @source.respond_to?(:encode)\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_key_spans = self.class.send :_lex_key_spans\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n _lex_eof_trans = self.class.send :_lex_eof_trans\n\n p, pe, eof = @p, @source.length + 1, @source.length + 1\n\n @command_state = (@cs == self.class.lex_en_expr_value ||\n @cs == self.class.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n [ false, [ '$eof', range(p, p) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |value| emit(:tINTEGER, value) } }\n | 'r' % { @num_xfrm = lambda { |value| emit(:tRATIONAL, Rational(value)) } }\n | 'i' % { @num_xfrm = lambda { |value| emit(:tIMAGINARY, Complex(0, value)) } }\n | 'ri' % { @num_xfrm = lambda { |value| emit(:tIMAGINARY, Complex(0, Rational(value))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |digits| emit(:tFLOAT, Float(digits)) } }\n | 'i' % { @num_xfrm = lambda { |digits| emit(:tIMAGINARY, Complex(0, Float(digits))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |digits| emit(:tRATIONAL, Rational(digits)) } }\n | 'ri' % { @num_xfrm = lambda { |digits| emit(:tIMAGINARY, Complex(0, Rational(digits))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n @escape = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }.fetch(@source[p - 1].chr, @source[p - 1].chr)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :error, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :error, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :error, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts < extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a ?b\n # Character literal.\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n w_space+ ( [%\/] ( c_any - c_space_nl - '=' ) # \/\n # a < { fhold; fhold; fgoto expr_beg; };\n\n # x \/1\n # Ambiguous regexp literal.\n w_space+ '\/'\n => {\n diagnostic :warning, :ambiguous_literal, nil, range(@te - 1, @te)\n\n fhold; fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = $2.empty? ? '\"' : $2\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | c_any - c_space_nl - e_bs % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? '_'\n diagnostic :error, :trailing_in_number, { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_arg; fbreak; };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"349e8774a565046bc6bbc2fb72fb1fe2bd91c75b","subject":"Fixed issue in Haskell Scanner to properly mark '|--' as code Previous method worked coincidentally because '|' was marked as code and '--' was marked as comment so line became code. Now properly checks for leading '|' each time '--' is found.","message":"Fixed issue in Haskell Scanner to properly mark '|--' as code\nPrevious method worked coincidentally because '|' was marked as code\nand '--' was marked as comment so line became code. Now properly checks\nfor leading '|' each time '--' is found.\n","repos":"blackducksoftware\/ohcount4j,mpujari\/ohcount4j,blackducksoftware\/ohcount4j,blackducksoftware\/ohcount4j,mpujari\/ohcount4j,blackducksoftware\/ohcount4j,mpujari\/ohcount4j,mpujari\/ohcount4j,blackducksoftware\/ohcount4j,mpujari\/ohcount4j,mpujari\/ohcount4j","old_file":"scanners\/HaskellScanner.java.rl","new_file":"scanners\/HaskellScanner.java.rl","new_contents":"package net.ohloh.ohcount4j.scan;\n\npublic class HaskellScanner extends BaseScanner{\n\n\tprotected int nested_level = 0;\n\n \t%%{\n\t machine haskell;\n\t include common \"common.rl\";\n\t \n\t action inc_nested_level { nested_level++; }\n\t \taction dec_nested_level { nested_level--; if(nested_level == 0) fret; }\n\t \taction is_nested { nested_level > 0 }\n\t \taction printp { System.out.println(\n\t \t\t\t\t\"P='\" + (data[p] == '\\n' ? \"nl\" : data[p]) +\n\t \t\t\t\t\"' P-1='\" + (data[p-1] == '\\n' ? \"nl\" : data[p-1]) + \n\t \t\t\t\t\"' P-2='\" + (data[p-2] == '\\n' ? \"nl\" : data[p-2]) + \"'\"); }\n\n\t\t# Catches instances of '|--' as not a comment properly\n\t\t# If it finds '--' as the first thing in the file, cannot have leading '|'\n\t\t# Otherwise every time a comment is found, checks the char before it for '|'\n\t\thaskell_line_comment = ('--' \n\t\t\t\twhen { p == 0 || data[p-1] != '|' } \n\t\t\t\t\t\t([^>] @comment nonnewline* | [^>])?) @comment;\n\n\n\t # For handeling nested nature block comments {- -}\n\t haskell_block_comment_begin = '{-' @comment @inc_nested_level;\n\t haskell_block_comment_end = '-}' @comment when is_nested @dec_nested_level;\n\t haskell_block_comment := |*\n\t \t\tnewline;\n\t \t\tspaces;\n\t \t\t(any - newline) => comment;\n\t \thaskell_block_comment_begin;\n\t \thaskell_block_comment_end;\n\t *|;\n\t \n\t haskell_char = '\\'' @code string_char '\\'' @code;\n\t haskell_string_literal = string_literal_dq | haskell_char;\n\t \n\t \thaskell_line := |*\n\t \t\thaskell_block_comment_begin => { fhold; fcall haskell_block_comment; };\n\t \t\thaskell_string_literal;\n\t \thaskell_line_comment;\n\t \tspaces;\n\t \tnewline;\n\t \t(any - newline) => code;\n\t \t*|; \n\t}%%\n\t\n\t%% write data;\n\t \n\t@Override\n\tpublic void doScan(){\n\t\t\/\/ variables and data is set up in BaseScanner\n\t %% write init;\n\t init();\n\t %% write exec;\n\t}\n\t \n}\n","old_contents":"package net.ohloh.ohcount4j.scan;\n\npublic class HaskellScanner extends BaseScanner{\n\n\tprotected int nested_level = 0;\n\n \t%%{\n\t machine haskell;\n\t include common \"common.rl\";\n\t \n\t action inc_nested_level { nested_level++; }\n\t \taction dec_nested_level { nested_level--; if(nested_level == 0) fret; }\n\t \taction is_nested { nested_level > 0 }\n\n\t\t# TODO verify |--\n\t\t\n\t\thaskell_line_comment = ([^|]? '--' ([^>] @comment nonnewline* | [^>])?) @comment;\n\n\t # For handeling nested nature block comments { }\n\t haskell_block_comment_begin = '{-' @comment @inc_nested_level;\n\t haskell_block_comment_end = '-}' @comment when is_nested @dec_nested_level;\n\t haskell_block_comment := |*\n\t \t\tnewline;\n\t \t\tspaces;\n\t \t\t(any - newline) => comment;\n\t \thaskell_block_comment_begin;\n\t \thaskell_block_comment_end;\n\t *|;\n\t \n\t haskell_string_literal = string_literal_dq | ('\\'' @code string_char '\\'' @code);\n\t \n\t \thaskell_line := |*\n\t \t\thaskell_block_comment_begin => { fhold; fcall haskell_block_comment; };\n\t \t\thaskell_string_literal;\n\t \thaskell_line_comment;\n\t \tspaces;\n\t \tnewline;\n\t \t(any - newline) => code;\n\t \t*|; \n\t}%%\n\t\n\t%% write data;\n\t \n\t@Override\n\tpublic void doScan(){\n\t\t\/\/ variables and data is set up in BaseScanner\n\t %% write init;\n\t init();\n\t %% write exec;\n\t}\n\t \n}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"7c04b753ca41c4de5eaf03f80de4ea9b054c9bf0","subject":"interpret two single quotes ('') as a single one (')","message":"interpret two single quotes ('') as a single one (')\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner.rl","new_file":"src\/mfilescanner.rl","new_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << '\"';\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << '\"';\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","old_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << '\"';\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << '\"';\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"a2f8e16565b9c79483c8035d871f725b8b88d218","subject":"[jancy] test_qt had incorrect highlighting for dynamiclib","message":"[jancy] test_qt had incorrect highlighting for dynamiclib\n","repos":"vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy","old_file":"test\/test_qt\/jancyhighlighter.rl","new_file":"test\/test_qt\/jancyhighlighter.rl","new_contents":"\/\/.............................................................................\n\n%%{\n\nmachine jancy_lexer;\nwrite data;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n';\nlc_nl = '\\\\' '\\r'? nl;\nesc = '\\\\' [^\\n];\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* ([\"\\\\] | nl);\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* (['\\\\] | nl);\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n(\n'import' |\n'namespace' |\n'extension' |\n'dynamiclib' |\n'using' |\n'friend' |\n'public' |\n'protected' |\n'alignment' |\n'setas' |\n\n'typedef' |\n'alias' |\n'static' |\n'thread' |\n'stack' |\n'heap' |\n'abstract' |\n'virtual' |\n'override' |\n'mutable' |\n'disposable' |\n\n'signed' |\n'unsigned' |\n'bigendian' |\n'const' |\n'readonly' |\n'volatile' |\n'safe' |\n'unsafe' |\n'weak' |\n'thin' |\n'errorcode' |\n'cdecl' |\n'stdcall' |\n'thiscall' |\n'jnccall' |\n'array' |\n'function' |\n'property' |\n'bindable' |\n'autoget' |\n'indexed' |\n'multicast' |\n'event' |\n'reactor' |\n'automaton' |\n\n'auto' |\n'anydata' |\n'void' |\n'variant' |\n'bool' |\n'int8' |\n'int16' |\n'int32' |\n'int64' |\n'float' |\n'double' |\n'char' |\n'int' |\n'intptr' |\n'enum' |\n'struct' |\n'union' |\n'class' |\n'opaque' |\n'exposed' |\n'bitflag' |\n\n'get' |\n'set' |\n'preconstruct' |\n'construct' |\n'destruct' |\n'operator' |\n'postfix' |\n\n'if' |\n'else' |\n'for' |\n'while' |\n'do' |\n'break' |\n'break' [1-9]? |\n'continue' [1-9]? |\n'return' |\n'switch' |\n'case' |\n'default' |\n'once' |\n'onevent' |\n'try' |\n'throw' |\n'catch' |\n'finally' |\n'nestedscope' |\n'assert' |\n\n'basetype' [1-9]? |\n'this' |\n'true' |\n'false' |\n'null' |\n\n'new' |\n'delete' |\n'sizeof' |\n'countof' |\n'offsetof' |\n'typeof' |\n'bindingof' |\n'dynamic'\n\n) { colorize (ts, te, Qt::blue); };\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\nid ;\n(lit_sq | lit_dq) { colorize (ts, te, Qt::darkRed); };\ndec+ { colorize (ts, te, Qt::darkRed); };\n'0' [xX] hex+ { colorize (ts, te, Qt::darkRed); };\n'0' [bB] bin+ { colorize (ts, te, Qt::darkRed); };\n'0' [xX] lit_dq { colorize (ts, te, Qt::darkRed); };\n'0' [bB] lit_dq { colorize (ts, te, Qt::darkRed); };\n'$' lit_dq { colorize (ts, te, Qt::darkRed); };\n\n'%%' { colorize (ts, te, Qt::darkRed); fgoto regexp; };\n'<<<' { colorize (ts, te, Qt::darkRed); fgoto lit_ml; };\n\n'\/\/' any* { colorize (ts, te, Qt::darkGray); };\n'\/*' { colorize (ts, te, Qt::darkGray); fgoto comment; };\n\nws | nl ;\nany ;\n\n*|;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# comment machine\n#\n\ncomment := |*\n\n'*\/' { colorize (ts, te, Qt::darkGray); fgoto main; };\nany { colorize (ts, te, Qt::darkGray); };\n\n*|;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# regexp machine\n#\n\nregexp := |*\n\nany* '\\\\' { colorize (ts, te, Qt::darkRed); };\nany* { colorize (ts, te, Qt::darkRed); fgoto main; };\n\n*|;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\n'>>>' { colorize (ts, te, Qt::darkRed); fgoto main; };\nany { colorize (ts, te, Qt::darkRed); };\n\n*|;\n\n}%%\n\n\/\/.............................................................................\n\n#define BLOCK_STATE_NONE\t0\n#define BLOCK_STATE_COMMENT 1\n#define BLOCK_STATE_REGEXP 2\n#define BLOCK_STATE_LIT_ML 3\n\nvoid JancyHighlighter::ragelInit ()\n{\n\t%% write init;\n}\n\nvoid JancyHighlighter::ragelExec ()\n{\n\t%% write exec;\n}\n\nvoid JancyHighlighter::ragelExecPreEvent (int &ragelState)\n{\n\tsetCurrentBlockState (BLOCK_STATE_NONE);\n\n\tint prevBlockState = previousBlockState ();\t\n\tswitch (prevBlockState)\n\t{\n\tcase BLOCK_STATE_COMMENT:\n\t\tragelState = jancy_lexer_en_comment;\n\t\tbreak;\n\n\tcase BLOCK_STATE_REGEXP:\n\t\tragelState = jancy_lexer_en_regexp;\n\t\tbreak;\n\n\tcase BLOCK_STATE_LIT_ML:\n\t\tragelState = jancy_lexer_en_lit_ml;\n\t\tbreak;\n\t}\n}\n\nvoid JancyHighlighter::ragelExecPostEvent (int ragelState)\n{\n\tswitch (ragelState)\n\t{\n\tcase jancy_lexer_en_comment:\n\t\tsetCurrentBlockState (BLOCK_STATE_COMMENT);\n\t\tbreak;\n\n\tcase jancy_lexer_en_regexp:\n\t\tsetCurrentBlockState (BLOCK_STATE_REGEXP);\n\t\tbreak;\n\n\tcase jancy_lexer_en_lit_ml:\n\t\tsetCurrentBlockState (BLOCK_STATE_LIT_ML);\n\t\tbreak;\n\t}\n}\n\n\/\/.............................................................................\n","old_contents":"\/\/.............................................................................\n\n%%{\n\nmachine jancy_lexer;\nwrite data;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n';\nlc_nl = '\\\\' '\\r'? nl;\nesc = '\\\\' [^\\n];\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* ([\"\\\\] | nl);\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* (['\\\\] | nl);\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n(\n'import' |\n'namespace' |\n'extension' |\n'library' |\n'using' |\n'friend' |\n'public' |\n'protected' |\n'alignment' |\n'setas' |\n\n'typedef' |\n'alias' |\n'static' |\n'thread' |\n'stack' |\n'heap' |\n'abstract' |\n'virtual' |\n'override' |\n'mutable' |\n'disposable' |\n\n'signed' |\n'unsigned' |\n'bigendian' |\n'const' |\n'readonly' |\n'volatile' |\n'safe' |\n'unsafe' |\n'weak' |\n'thin' |\n'errorcode' |\n'cdecl' |\n'stdcall' |\n'thiscall' |\n'jnccall' |\n'array' |\n'function' |\n'property' |\n'bindable' |\n'autoget' |\n'indexed' |\n'multicast' |\n'event' |\n'reactor' |\n'automaton' |\n\n'auto' |\n'anydata' |\n'void' |\n'variant' |\n'bool' |\n'int8' |\n'int16' |\n'int32' |\n'int64' |\n'float' |\n'double' |\n'char' |\n'int' |\n'intptr' |\n'enum' |\n'struct' |\n'union' |\n'class' |\n'opaque' |\n'exposed' |\n'bitflag' |\n\n'get' |\n'set' |\n'preconstruct' |\n'construct' |\n'destruct' |\n'operator' |\n'postfix' |\n\n'if' |\n'else' |\n'for' |\n'while' |\n'do' |\n'break' |\n'break' [1-9]? |\n'continue' [1-9]? |\n'return' |\n'switch' |\n'case' |\n'default' |\n'once' |\n'onevent' |\n'try' |\n'throw' |\n'catch' |\n'finally' |\n'nestedscope' |\n'assert' |\n\n'basetype' [1-9]? |\n'this' |\n'true' |\n'false' |\n'null' |\n\n'new' |\n'delete' |\n'sizeof' |\n'countof' |\n'offsetof' |\n'typeof' |\n'bindingof' |\n'dynamic'\n\n) { colorize (ts, te, Qt::blue); };\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\nid ;\n(lit_sq | lit_dq) { colorize (ts, te, Qt::darkRed); };\ndec+ { colorize (ts, te, Qt::darkRed); };\n'0' [xX] hex+ { colorize (ts, te, Qt::darkRed); };\n'0' [bB] bin+ { colorize (ts, te, Qt::darkRed); };\n'0' [xX] lit_dq { colorize (ts, te, Qt::darkRed); };\n'0' [bB] lit_dq { colorize (ts, te, Qt::darkRed); };\n'$' lit_dq { colorize (ts, te, Qt::darkRed); };\n\n'%%' { colorize (ts, te, Qt::darkRed); fgoto regexp; };\n'<<<' { colorize (ts, te, Qt::darkRed); fgoto lit_ml; };\n\n'\/\/' any* { colorize (ts, te, Qt::darkGray); };\n'\/*' { colorize (ts, te, Qt::darkGray); fgoto comment; };\n\nws | nl ;\nany ;\n\n*|;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# comment machine\n#\n\ncomment := |*\n\n'*\/' { colorize (ts, te, Qt::darkGray); fgoto main; };\nany { colorize (ts, te, Qt::darkGray); };\n\n*|;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# regexp machine\n#\n\nregexp := |*\n\nany* '\\\\' { colorize (ts, te, Qt::darkRed); };\nany* { colorize (ts, te, Qt::darkRed); fgoto main; };\n\n*|;\n\n# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\n'>>>' { colorize (ts, te, Qt::darkRed); fgoto main; };\nany { colorize (ts, te, Qt::darkRed); };\n\n*|;\n\n}%%\n\n\/\/.............................................................................\n\n#define BLOCK_STATE_NONE\t0\n#define BLOCK_STATE_COMMENT 1\n#define BLOCK_STATE_REGEXP 2\n#define BLOCK_STATE_LIT_ML 3\n\nvoid JancyHighlighter::ragelInit ()\n{\n\t%% write init;\n}\n\nvoid JancyHighlighter::ragelExec ()\n{\n\t%% write exec;\n}\n\nvoid JancyHighlighter::ragelExecPreEvent (int &ragelState)\n{\n\tsetCurrentBlockState (BLOCK_STATE_NONE);\n\n\tint prevBlockState = previousBlockState ();\t\n\tswitch (prevBlockState)\n\t{\n\tcase BLOCK_STATE_COMMENT:\n\t\tragelState = jancy_lexer_en_comment;\n\t\tbreak;\n\n\tcase BLOCK_STATE_REGEXP:\n\t\tragelState = jancy_lexer_en_regexp;\n\t\tbreak;\n\n\tcase BLOCK_STATE_LIT_ML:\n\t\tragelState = jancy_lexer_en_lit_ml;\n\t\tbreak;\n\t}\n}\n\nvoid JancyHighlighter::ragelExecPostEvent (int ragelState)\n{\n\tswitch (ragelState)\n\t{\n\tcase jancy_lexer_en_comment:\n\t\tsetCurrentBlockState (BLOCK_STATE_COMMENT);\n\t\tbreak;\n\n\tcase jancy_lexer_en_regexp:\n\t\tsetCurrentBlockState (BLOCK_STATE_REGEXP);\n\t\tbreak;\n\n\tcase jancy_lexer_en_lit_ml:\n\t\tsetCurrentBlockState (BLOCK_STATE_LIT_ML);\n\t\tbreak;\n\t}\n}\n\n\/\/.............................................................................\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"4cfd7bbf5df41e822541241441b384dc8166ef62","subject":"noexectime jobs must ignore the lasttime as well as the exectime.","message":"noexectime jobs must ignore the lasttime as well as the exectime.\n","repos":"niklata\/ncron,niklata\/ncron","old_file":"crontab.rl","new_file":"crontab.rl","new_contents":"\/* crontab.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n#include \"nk\/malloc.h\"\n#include \"nk\/privilege.h\"\n\n#include \"ncron.h\"\n#include \"crontab.h\"\n#include \"sched.h\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\n\nstruct ParseCfgState\n{\n char v_str[1024];\n\n cronentry_t *stack;\n cronentry_t *deadstack;\n cronentry_t *ce;\n\n char *execfile;\n\n char *jobid_st;\n char *time_st;\n char *intv_st;\n char *intv2_st;\n char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int noextime;\n int cmdret;\n\n bool intv2_exist;\n};\n\nstatic void nullify_item(cronentry_t *item)\n{\n if (!item)\n return;\n item->id = 0;\n item->command = NULL;\n item->args = NULL;\n item->chroot = NULL;\n item->numruns = 0;\n item->maxruns = 0;\n item->journal = 0;\n item->user = 0;\n item->group = 0;\n item->month = NULL;\n item->day = NULL;\n item->weekday = NULL;\n item->hour = NULL;\n item->minute = NULL;\n item->interval = 0;\n item->exectime = 0;\n item->lasttime = 0;\n item->limits = NULL;\n item->next = NULL;\n}\n\nstatic void nullify_limits(limit_t *l)\n{\n if (!l)\n return;\n l->cpu = NULL;\n l->fsize = NULL;\n l->data = NULL;\n l->stack = NULL;\n l->core = NULL;\n l->rss = NULL;\n l->nproc = NULL;\n l->nofile = NULL;\n l->memlock = NULL;\n l->as = NULL;\n}\n\nstruct hstm {\n char *st;\n int cs;\n int id;\n time_t exectime;\n time_t lasttime;\n unsigned int numruns;\n bool got_exectime:1;\n bool got_lasttime:1;\n bool got_numruns:1;\n};\n\n%%{\n machine history_m;\n access hstm->;\n\n action St { hstm->st = p; }\n action LastTimeEn {\n hstm->lasttime = atoi(hstm->st);\n hstm->got_lasttime = 1;\n }\n action NumRunsEn {\n hstm->numruns = atoi(hstm->st);\n hstm->got_numruns = 1;\n }\n action ExecTimeEn {\n hstm->exectime = atoi(hstm->st);\n hstm->got_exectime = 1;\n }\n action IdEn { hstm->id = atoi(hstm->st); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+ '\\n';\n}%%\n\n%% write data;\n\nstatic int do_get_history(struct hstm *hstm, char *buf, size_t blen)\n{\n char *p = buf;\n const char *pe = buf + blen;\n\n %% write init;\n %% write exec;\n\n if (hstm->cs >= history_m_first_final)\n return 1;\n if (hstm->cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic void get_history(cronentry_t *item, char *path, int ignore_exectime)\n{\n struct hstm hstm = {0};\n time_t exectm = 0;\n time_t lasttm = 0;\n\n assert(item);\n\n FILE *f = fopen(path, \"r\");\n if (!f) {\n log_line(\"failed to open history file \\\"%s\\\" for read\", path);\n if (!ignore_exectime)\n item->exectime = (time_t)0; \/* gracefully fail *\/\n return;\n }\n\n size_t linenum = 0;\n char buf[MAXLINE];\n while (fgets(buf, sizeof buf, f)) {\n ++linenum;\n size_t buflen = strlen(buf);\n if (buflen <= 0)\n continue;\n memset(&hstm, 0, sizeof hstm);\n int r = do_get_history(&hstm, buf, buflen);\n if (r < 0) {\n if (r == -2)\n log_error(\"%s: Incomplete configuration at line %zu; ignoring\",\n __func__, linenum);\n else\n log_error(\"%s: Malformed configuration at line %zu; ignoring.\",\n __func__, linenum);\n continue;\n }\n if (hstm.id == item->id) {\n if (hstm.got_lasttime)\n lasttm = hstm.lasttime;\n if (hstm.got_numruns) {\n item->numruns = hstm.numruns;\n log_line(\"[%d]->numruns = %u\", item->id, item->numruns);\n }\n if (hstm.got_exectime)\n exectm = hstm.exectime;\n break;\n }\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n if (!ignore_exectime) {\n item->lasttime = lasttm > 0 ? lasttm : 0;\n log_line(\"[%d]->lasttime = %u\", item->id, item->lasttime);\n item->exectime = exectm > 0 ? exectm : 0;\n log_line(\"[%d]->exectime = %u\", item->id, item->exectime);\n }\n}\n\nstatic void setlim(struct ParseCfgState *ncs, int type)\n{\n struct rlimit **p = NULL;\n if (!ncs->ce->limits) {\n ncs->ce->limits = xmalloc(sizeof(limit_t));\n nullify_limits(ncs->ce->limits);\n }\n switch (type) {\n case RLIMIT_CPU: *p = ncs->ce->limits->cpu; break;\n case RLIMIT_FSIZE: *p = ncs->ce->limits->fsize; break;\n case RLIMIT_DATA: *p = ncs->ce->limits->data; break;\n case RLIMIT_STACK: *p = ncs->ce->limits->stack; break;\n case RLIMIT_CORE: *p = ncs->ce->limits->core; break;\n case RLIMIT_RSS: *p = ncs->ce->limits->rss; break;\n case RLIMIT_NPROC: *p = ncs->ce->limits->nproc; break;\n case RLIMIT_NOFILE: *p = ncs->ce->limits->nofile; break;\n case RLIMIT_MEMLOCK: *p = ncs->ce->limits->memlock; break;\n#ifndef BSD\n case RLIMIT_AS: *p = ncs->ce->limits->as; break;\n#endif \/* BSD *\/\n default: return;\n }\n if (!p)\n suicide(\"%s: unexpected NULL, corruption?\", __func__);\n if (!*p)\n *p = xmalloc(sizeof(struct rlimit));\n if (ncs->v_int == 0) (*p)->rlim_cur = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int;\n\n if (ncs->v_int2 == 0) (*p)->rlim_max = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int2;\n}\n\nstatic void addipairlist(struct ParseCfgState *ncs,\n ipair_node_t **list, int wildcard, int min, int max)\n{\n ipair_node_t *l;\n int low, high = wildcard;\n\n low = ncs->v_int;\n if (ncs->intv2_exist)\n high = ncs->v_int2;\n\n if (high == wildcard)\n high = low;\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (*list == NULL) {\n *list = xmalloc(sizeof(ipair_node_t));\n l = *list;\n } else {\n l = *list;\n while (l->next)\n l = l->next;\n\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n }\n\n \/* discontinuous range, split into two continuous rules... *\/\n if (low > high) {\n l->node.l = low;\n l->node.h = max;\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n l->node.l = min;\n l->node.h = high;\n l->next = NULL;\n } else {\n \/* handle continuous ranges normally *\/\n l->node.l = low;\n l->node.h = high;\n l->next = NULL;\n }\n}\n\nstatic void setgroupv(struct ParseCfgState *ncs)\n{\n if (nk_gidbyname(ncs->v_str, &ncs->ce->group))\n suicide(\"%s: nonexistent group specified at line %zu\", ncs->linenum);\n}\n\nstatic void setuserv(struct ParseCfgState *ncs)\n{\n if (nk_uidgidbyname(ncs->v_str, &ncs->ce->user, &ncs->ce->group))\n suicide(\"%s: nonexistent user specified at line %zu\", ncs->linenum);\n}\n\nstatic void parse_assign_str(char **dest, char *src, size_t srclen,\n size_t linenum)\n{\n if (srclen > INT_MAX)\n suicide(\"%s: srclen would overflow int at line %zu\",\n __func__, linenum);\n free(*dest);\n *dest = xmalloc(srclen+1);\n ssize_t l = snprintf(*dest, srclen+1, \"%.*s\", (int)srclen, src);\n if (l < 0 || (size_t)l >= srclen+1)\n suicide(\"%s: snprintf failed l=%u srclen+1=%u at line %zu\",\n __func__, l, srclen+1, linenum);\n}\n\nstruct pckm {\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n size_t cmdlen = p - pckm.st;\n parse_assign_str(&ncs->ce->command, pckm.st, cmdlen, ncs->linenum);\n \/\/ Unescape \"\\\\\" and \"\\ \".\n int prevsl = 0;\n size_t i = 0;\n while (ncs->ce->command[i]) {\n if (prevsl && (ncs->ce->command[i] == '\\\\'\n || ncs->ce->command[i] == ' ')) {\n memmove(ncs->ce->command + i - 1,\n ncs->ce->command + i, cmdlen--);\n continue;\n }\n if (ncs->ce->command[i] == '\\\\')\n prevsl = 1;\n ++i;\n }\n }\n action ArgEn {\n parse_assign_str(&ncs->ce->args, pckm.st, p - pckm.st, ncs->linenum);\n }\n\n sptab = [ \\t];\n cmdstr = ([^\\0 \\t] | '\\\\\\\\' | '\\\\ ')+;\n cmd = sptab* (cmdstr > St % CmdEn);\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args?;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(struct ParseCfgState *ncs)\n{\n char *p = ncs->v_str;\n const char *pe = ncs->v_str + ncs->v_strlen;\n const char *eof = pe;\n\n struct pckm pckm = {0};\n\n if (ncs->cmdret != 0) {\n ncs->cmdret = -3;\n suicide(\"Duplicate 'command' value at line %zu\", ncs->linenum);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs->cmdret = -1;\n suicide(\"Malformed 'command' value at line %zu\", ncs->linenum);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs->cmdret = 1;\n else {\n ncs->cmdret = -2;\n suicide(\"Incomplete 'command' value at line %zu\", ncs->linenum);\n }\n}\n\nstatic void create_ce(struct ParseCfgState *ncs)\n{\n assert(!ncs->ce);\n ncs->ce = xmalloc(sizeof(cronentry_t));\n nullify_item(ncs->ce);\n ncs->cmdret = 0;\n ncs->noextime = 0;\n}\n\n#ifdef CONFIG_RL_DEBUG\nstatic void debug_print_ce(struct ParseCfgState *ncs)\n{\n printf(\"\\nfinish_ce:\\n\");\n printf(\"id: %u\\n\", ncs->ce->id);\n printf(\"command: %s\\n\", ncs->ce->command);\n printf(\"args: %s\\n\", ncs->ce->args);\n printf(\"chroot: %s\\n\", ncs->ce->chroot);\n printf(\"numruns: %u\\n\", ncs->ce->numruns);\n printf(\"maxruns: %u\\n\", ncs->ce->maxruns);\n printf(\"journal: %d\\n\", ncs->ce->journal);\n printf(\"user: %u\\n\", ncs->ce->user);\n printf(\"group: %u\\n\", ncs->ce->group);\n if (ncs->ce->month)\n printf(\"month: [%d,%d]\\n\", ncs->ce->month->node.l, ncs->ce->month->node.h);\n if (ncs->ce->day)\n printf(\"day: [%d,%d]\\n\", ncs->ce->day->node.l, ncs->ce->day->node.h);\n if (ncs->ce->weekday)\n printf(\"weekday: [%d,%d]\\n\", ncs->ce->weekday->node.l, ncs->ce->weekday->node.h);\n if (ncs->ce->hour)\n printf(\"hour: [%d,%d]\\n\", ncs->ce->hour->node.l, ncs->ce->hour->node.h);\n if (ncs->ce->minute)\n printf(\"minute: [%d,%d]\\n\", ncs->ce->minute->node.l, ncs->ce->minute->node.h);\n printf(\"interval: %u\\n\", ncs->ce->interval);\n printf(\"exectime: %u\\n\", ncs->ce->exectime);\n printf(\"lasttime: %u\\n\", ncs->ce->lasttime);\n}\nstatic void debug_print_ce_ignore(struct ParseCfgState *ncs)\n{\n (void)ncs;\n printf(\"===> IGNORE\\n\");\n}\nstatic void debug_print_ce_add(struct ParseCfgState *ncs)\n{\n (void)ncs;\n printf(\"===> ADD\\n\");\n}\n#else\nstatic void debug_print_ce(struct ParseCfgState *ncs) {(void)ncs;}\nstatic void debug_print_ce_ignore(struct ParseCfgState *ncs) {(void)ncs;}\nstatic void debug_print_ce_add(struct ParseCfgState *ncs) {(void)ncs;}\n#endif\n\nstatic void finish_ce(struct ParseCfgState *ncs)\n{\n if (!ncs->ce)\n return;\n\n debug_print_ce(ncs);\n\n if (ncs->ce->id <= 0\n || (ncs->ce->interval <= 0 && ncs->ce->exectime <= 0)\n || !ncs->ce->command || ncs->cmdret < 1) {\n debug_print_ce_ignore(ncs);\n free_cronentry(&ncs->ce);\n ncs->ce = NULL;\n return;\n }\n debug_print_ce_add(ncs);\n\n \/* we have a job to insert *\/\n if (ncs->ce->exectime != 0) { \/* runat task *\/\n get_history(ncs->ce, ncs->execfile, 1);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n } else { \/* interval task *\/\n get_history(ncs->ce, ncs->execfile, ncs->noextime && !cfg_reload);\n set_initial_exectime(ncs->ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n && ncs->ce->exectime != 0)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n }\n ncs->ce = NULL;\n}\n\n%%{\n machine ncrontab;\n access ncs->;\n\n spc = [ \\t];\n eqsep = spc* '=' spc*;\n cmdterm = [\\0\\n];\n\n action TUnitSt { ncs->time_st = p; ncs->v_time = 0; }\n action TSecEn { ncs->v_time += atoi(ncs->time_st); }\n action TMinEn { ncs->v_time += 60 * atoi(ncs->time_st); }\n action THrEn { ncs->v_time += 3600 * atoi(ncs->time_st); }\n action TDayEn { ncs->v_time += 86400 * atoi(ncs->time_st); }\n action TWeekEn { ncs->v_time += 604800 * atoi(ncs->time_st); }\n\n action IntValSt {\n ncs->intv_st = p;\n ncs->v_int = ncs->v_int2 = 0;\n ncs->intv2_exist = false;\n }\n action IntValEn { ncs->v_int = atoi(ncs->intv_st); }\n action IntVal2St { ncs->intv2_st = p; }\n action IntVal2En {\n ncs->v_int2 = atoi(ncs->intv2_st);\n ncs->intv2_exist = true;\n }\n\n action StrValSt { ncs->strv_st = p; ncs->v_strlen = 0; }\n action StrValEn {\n ncs->v_strlen = p - ncs->strv_st;\n if (ncs->v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs->v_str, sizeof ncs->v_str,\n \"%.*s\", (int)ncs->v_strlen, ncs->strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs->v_str)\n suicide(\"error parsing line %u in crontab; too long?\",\n ncs->linenum);\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn) cmdterm;\n timeval = t_any (spc* t_any)* cmdterm;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))? cmdterm;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn) cmdterm;\n\n action JournalEn { ncs->ce->journal = 1; }\n action NoExecTimeEn { ncs->noextime = 1; }\n\n journal = 'journal'i cmdterm % JournalEn;\n noexectime = 'noexectime'i cmdterm % NoExecTimeEn;\n\n action RunAtEn {\n ncs->ce->exectime = ncs->v_int;\n ncs->ce->maxruns = 1;\n ncs->ce->journal = 1;\n }\n action MaxRunsEn {\n if (ncs->ce->exectime == 0)\n ncs->ce->maxruns = ncs->v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n\n action IntervalEn { ncs->ce->interval = ncs->v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addipairlist(ncs, &ncs->ce->month, 0, 1, 12); }\n action DayEn { addipairlist(ncs, &ncs->ce->day, 0, 1, 31); }\n action WeekdayEn { addipairlist(ncs, &ncs->ce->weekday, 0, 1, 7); }\n action HourEn { addipairlist(ncs, &ncs->ce->hour, 24, 0, 23); }\n action MinuteEn { addipairlist(ncs, &ncs->ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn {\n parse_assign_str(&ncs->ce->chroot, ncs->v_str, ncs->v_strlen,\n ncs->linenum);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n maxruns | runat | noexectime | journal;\n\n action JobIdSt { ncs->jobid_st = p; }\n action JobIdEn { ncs->ce->id = atoi(ncs->jobid_st); }\n action CreateCe { finish_ce(ncs); create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) cmdterm % JobIdEn;\n\n emptyline = '\\n';\n\n main := jobid | cmds | emptyline;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(struct ParseCfgState *ncs, char *data, size_t len)\n{\n char *p = data;\n const char *pe = data + len;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs->cs == ncrontab_error)\n return -1;\n if (ncs->cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(char *path, char *execfile, cronentry_t **stk,\n cronentry_t **deadstk)\n{\n char buf[MAXLINE];\n struct ParseCfgState ncs;\n memset(&ncs, 0, sizeof ncs);\n ncs.execfile = execfile;\n ncs.stack = *stk;\n ncs.deadstack = *deadstk;\n\n FILE *f = fopen(path, \"r\");\n if (!f)\n suicide(\"%s: fopen(%s) failed: %s\", __func__, path, strerror(errno));\n\n while (++ncs.linenum, fgets(buf, sizeof buf, f)) {\n int r = do_parse_config(&ncs, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_parse_config(%s) failed at line %u\",\n __func__, path, ncs.linenum);\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n *stk = ncs.stack;\n *deadstk = ncs.deadstack;\n if (ncs.ce)\n free_cronentry(&ncs.ce); \/\/ Free partially built unused item.\n cfg_reload = 1;\n}\n\n","old_contents":"\/* crontab.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n#include \"nk\/malloc.h\"\n#include \"nk\/privilege.h\"\n\n#include \"ncron.h\"\n#include \"crontab.h\"\n#include \"sched.h\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\n\nstruct ParseCfgState\n{\n char v_str[1024];\n\n cronentry_t *stack;\n cronentry_t *deadstack;\n cronentry_t *ce;\n\n char *execfile;\n\n char *jobid_st;\n char *time_st;\n char *intv_st;\n char *intv2_st;\n char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int noextime;\n int cmdret;\n\n bool intv2_exist;\n};\n\nstatic void nullify_item(cronentry_t *item)\n{\n if (!item)\n return;\n item->id = 0;\n item->command = NULL;\n item->args = NULL;\n item->chroot = NULL;\n item->numruns = 0;\n item->maxruns = 0;\n item->journal = 0;\n item->user = 0;\n item->group = 0;\n item->month = NULL;\n item->day = NULL;\n item->weekday = NULL;\n item->hour = NULL;\n item->minute = NULL;\n item->interval = 0;\n item->exectime = 0;\n item->lasttime = 0;\n item->limits = NULL;\n item->next = NULL;\n}\n\nstatic void nullify_limits(limit_t *l)\n{\n if (!l)\n return;\n l->cpu = NULL;\n l->fsize = NULL;\n l->data = NULL;\n l->stack = NULL;\n l->core = NULL;\n l->rss = NULL;\n l->nproc = NULL;\n l->nofile = NULL;\n l->memlock = NULL;\n l->as = NULL;\n}\n\nstruct hstm {\n char *st;\n int cs;\n int id;\n time_t exectime;\n time_t lasttime;\n unsigned int numruns;\n bool got_exectime:1;\n bool got_lasttime:1;\n bool got_numruns:1;\n};\n\n%%{\n machine history_m;\n access hstm->;\n\n action St { hstm->st = p; }\n action LastTimeEn {\n hstm->lasttime = atoi(hstm->st);\n hstm->got_lasttime = 1;\n }\n action NumRunsEn {\n hstm->numruns = atoi(hstm->st);\n hstm->got_numruns = 1;\n }\n action ExecTimeEn {\n hstm->exectime = atoi(hstm->st);\n hstm->got_exectime = 1;\n }\n action IdEn { hstm->id = atoi(hstm->st); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+ '\\n';\n}%%\n\n%% write data;\n\nstatic int do_get_history(struct hstm *hstm, char *buf, size_t blen)\n{\n char *p = buf;\n const char *pe = buf + blen;\n\n %% write init;\n %% write exec;\n\n if (hstm->cs >= history_m_first_final)\n return 1;\n if (hstm->cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic void get_history(cronentry_t *item, char *path, int ignore_exectime)\n{\n struct hstm hstm = {0};\n time_t exectm = 0;\n\n assert(item);\n\n FILE *f = fopen(path, \"r\");\n if (!f) {\n log_line(\"failed to open history file \\\"%s\\\" for read\", path);\n if (!ignore_exectime)\n item->exectime = (time_t)0; \/* gracefully fail *\/\n return;\n }\n\n size_t linenum = 0;\n char buf[MAXLINE];\n while (fgets(buf, sizeof buf, f)) {\n ++linenum;\n size_t buflen = strlen(buf);\n if (buflen <= 0)\n continue;\n memset(&hstm, 0, sizeof hstm);\n int r = do_get_history(&hstm, buf, buflen);\n if (r < 0) {\n if (r == -2)\n log_error(\"%s: Incomplete configuration at line %zu; ignoring\",\n __func__, linenum);\n else\n log_error(\"%s: Malformed configuration at line %zu; ignoring.\",\n __func__, linenum);\n continue;\n }\n if (hstm.id == item->id) {\n if (hstm.got_lasttime) {\n item->lasttime = hstm.lasttime;\n log_line(\"[%d]->lasttime = %u\", item->id, item->lasttime);\n }\n if (hstm.got_numruns) {\n item->numruns = hstm.numruns;\n log_line(\"[%d]->numruns = %u\", item->id, item->numruns);\n }\n if (hstm.got_exectime)\n exectm = hstm.exectime;\n break;\n }\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n if (!ignore_exectime) {\n item->exectime = exectm > 0 ? exectm : 0;\n log_line(\"[%d]->exectime = %u\", item->id, item->exectime);\n }\n}\n\nstatic void setlim(struct ParseCfgState *ncs, int type)\n{\n struct rlimit **p = NULL;\n if (!ncs->ce->limits) {\n ncs->ce->limits = xmalloc(sizeof(limit_t));\n nullify_limits(ncs->ce->limits);\n }\n switch (type) {\n case RLIMIT_CPU: *p = ncs->ce->limits->cpu; break;\n case RLIMIT_FSIZE: *p = ncs->ce->limits->fsize; break;\n case RLIMIT_DATA: *p = ncs->ce->limits->data; break;\n case RLIMIT_STACK: *p = ncs->ce->limits->stack; break;\n case RLIMIT_CORE: *p = ncs->ce->limits->core; break;\n case RLIMIT_RSS: *p = ncs->ce->limits->rss; break;\n case RLIMIT_NPROC: *p = ncs->ce->limits->nproc; break;\n case RLIMIT_NOFILE: *p = ncs->ce->limits->nofile; break;\n case RLIMIT_MEMLOCK: *p = ncs->ce->limits->memlock; break;\n#ifndef BSD\n case RLIMIT_AS: *p = ncs->ce->limits->as; break;\n#endif \/* BSD *\/\n default: return;\n }\n if (!p)\n suicide(\"%s: unexpected NULL, corruption?\", __func__);\n if (!*p)\n *p = xmalloc(sizeof(struct rlimit));\n if (ncs->v_int == 0) (*p)->rlim_cur = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int;\n\n if (ncs->v_int2 == 0) (*p)->rlim_max = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int2;\n}\n\nstatic void addipairlist(struct ParseCfgState *ncs,\n ipair_node_t **list, int wildcard, int min, int max)\n{\n ipair_node_t *l;\n int low, high = wildcard;\n\n low = ncs->v_int;\n if (ncs->intv2_exist)\n high = ncs->v_int2;\n\n if (high == wildcard)\n high = low;\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (*list == NULL) {\n *list = xmalloc(sizeof(ipair_node_t));\n l = *list;\n } else {\n l = *list;\n while (l->next)\n l = l->next;\n\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n }\n\n \/* discontinuous range, split into two continuous rules... *\/\n if (low > high) {\n l->node.l = low;\n l->node.h = max;\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n l->node.l = min;\n l->node.h = high;\n l->next = NULL;\n } else {\n \/* handle continuous ranges normally *\/\n l->node.l = low;\n l->node.h = high;\n l->next = NULL;\n }\n}\n\nstatic void setgroupv(struct ParseCfgState *ncs)\n{\n if (nk_gidbyname(ncs->v_str, &ncs->ce->group))\n suicide(\"%s: nonexistent group specified at line %zu\", ncs->linenum);\n}\n\nstatic void setuserv(struct ParseCfgState *ncs)\n{\n if (nk_uidgidbyname(ncs->v_str, &ncs->ce->user, &ncs->ce->group))\n suicide(\"%s: nonexistent user specified at line %zu\", ncs->linenum);\n}\n\nstatic void parse_assign_str(char **dest, char *src, size_t srclen,\n size_t linenum)\n{\n if (srclen > INT_MAX)\n suicide(\"%s: srclen would overflow int at line %zu\",\n __func__, linenum);\n free(*dest);\n *dest = xmalloc(srclen+1);\n ssize_t l = snprintf(*dest, srclen+1, \"%.*s\", (int)srclen, src);\n if (l < 0 || (size_t)l >= srclen+1)\n suicide(\"%s: snprintf failed l=%u srclen+1=%u at line %zu\",\n __func__, l, srclen+1, linenum);\n}\n\nstruct pckm {\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n size_t cmdlen = p - pckm.st;\n parse_assign_str(&ncs->ce->command, pckm.st, cmdlen, ncs->linenum);\n \/\/ Unescape \"\\\\\" and \"\\ \".\n int prevsl = 0;\n size_t i = 0;\n while (ncs->ce->command[i]) {\n if (prevsl && (ncs->ce->command[i] == '\\\\'\n || ncs->ce->command[i] == ' ')) {\n memmove(ncs->ce->command + i - 1,\n ncs->ce->command + i, cmdlen--);\n continue;\n }\n if (ncs->ce->command[i] == '\\\\')\n prevsl = 1;\n ++i;\n }\n }\n action ArgEn {\n parse_assign_str(&ncs->ce->args, pckm.st, p - pckm.st, ncs->linenum);\n }\n\n sptab = [ \\t];\n cmdstr = ([^\\0 \\t] | '\\\\\\\\' | '\\\\ ')+;\n cmd = sptab* (cmdstr > St % CmdEn);\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args?;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(struct ParseCfgState *ncs)\n{\n char *p = ncs->v_str;\n const char *pe = ncs->v_str + ncs->v_strlen;\n const char *eof = pe;\n\n struct pckm pckm = {0};\n\n if (ncs->cmdret != 0) {\n ncs->cmdret = -3;\n suicide(\"Duplicate 'command' value at line %zu\", ncs->linenum);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs->cmdret = -1;\n suicide(\"Malformed 'command' value at line %zu\", ncs->linenum);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs->cmdret = 1;\n else {\n ncs->cmdret = -2;\n suicide(\"Incomplete 'command' value at line %zu\", ncs->linenum);\n }\n}\n\nstatic void create_ce(struct ParseCfgState *ncs)\n{\n assert(!ncs->ce);\n ncs->ce = xmalloc(sizeof(cronentry_t));\n nullify_item(ncs->ce);\n ncs->cmdret = 0;\n ncs->noextime = 0;\n}\n\n#ifdef CONFIG_RL_DEBUG\nstatic void debug_print_ce(struct ParseCfgState *ncs)\n{\n printf(\"\\nfinish_ce:\\n\");\n printf(\"id: %u\\n\", ncs->ce->id);\n printf(\"command: %s\\n\", ncs->ce->command);\n printf(\"args: %s\\n\", ncs->ce->args);\n printf(\"chroot: %s\\n\", ncs->ce->chroot);\n printf(\"numruns: %u\\n\", ncs->ce->numruns);\n printf(\"maxruns: %u\\n\", ncs->ce->maxruns);\n printf(\"journal: %d\\n\", ncs->ce->journal);\n printf(\"user: %u\\n\", ncs->ce->user);\n printf(\"group: %u\\n\", ncs->ce->group);\n if (ncs->ce->month)\n printf(\"month: [%d,%d]\\n\", ncs->ce->month->node.l, ncs->ce->month->node.h);\n if (ncs->ce->day)\n printf(\"day: [%d,%d]\\n\", ncs->ce->day->node.l, ncs->ce->day->node.h);\n if (ncs->ce->weekday)\n printf(\"weekday: [%d,%d]\\n\", ncs->ce->weekday->node.l, ncs->ce->weekday->node.h);\n if (ncs->ce->hour)\n printf(\"hour: [%d,%d]\\n\", ncs->ce->hour->node.l, ncs->ce->hour->node.h);\n if (ncs->ce->minute)\n printf(\"minute: [%d,%d]\\n\", ncs->ce->minute->node.l, ncs->ce->minute->node.h);\n printf(\"interval: %u\\n\", ncs->ce->interval);\n printf(\"exectime: %u\\n\", ncs->ce->exectime);\n printf(\"lasttime: %u\\n\", ncs->ce->lasttime);\n}\nstatic void debug_print_ce_ignore(struct ParseCfgState *ncs)\n{\n (void)ncs;\n printf(\"===> IGNORE\\n\");\n}\nstatic void debug_print_ce_add(struct ParseCfgState *ncs)\n{\n (void)ncs;\n printf(\"===> ADD\\n\");\n}\n#else\nstatic void debug_print_ce(struct ParseCfgState *ncs) {(void)ncs;}\nstatic void debug_print_ce_ignore(struct ParseCfgState *ncs) {(void)ncs;}\nstatic void debug_print_ce_add(struct ParseCfgState *ncs) {(void)ncs;}\n#endif\n\nstatic void finish_ce(struct ParseCfgState *ncs)\n{\n if (!ncs->ce)\n return;\n\n debug_print_ce(ncs);\n\n if (ncs->ce->id <= 0\n || (ncs->ce->interval <= 0 && ncs->ce->exectime <= 0)\n || !ncs->ce->command || ncs->cmdret < 1) {\n debug_print_ce_ignore(ncs);\n free_cronentry(&ncs->ce);\n ncs->ce = NULL;\n return;\n }\n debug_print_ce_add(ncs);\n\n \/* we have a job to insert *\/\n if (ncs->ce->exectime != 0) { \/* runat task *\/\n get_history(ncs->ce, ncs->execfile, 1);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n } else { \/* interval task *\/\n get_history(ncs->ce, ncs->execfile, ncs->noextime && !cfg_reload);\n set_initial_exectime(ncs->ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n && ncs->ce->exectime != 0)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n }\n ncs->ce = NULL;\n}\n\n%%{\n machine ncrontab;\n access ncs->;\n\n spc = [ \\t];\n eqsep = spc* '=' spc*;\n cmdterm = [\\0\\n];\n\n action TUnitSt { ncs->time_st = p; ncs->v_time = 0; }\n action TSecEn { ncs->v_time += atoi(ncs->time_st); }\n action TMinEn { ncs->v_time += 60 * atoi(ncs->time_st); }\n action THrEn { ncs->v_time += 3600 * atoi(ncs->time_st); }\n action TDayEn { ncs->v_time += 86400 * atoi(ncs->time_st); }\n action TWeekEn { ncs->v_time += 604800 * atoi(ncs->time_st); }\n\n action IntValSt {\n ncs->intv_st = p;\n ncs->v_int = ncs->v_int2 = 0;\n ncs->intv2_exist = false;\n }\n action IntValEn { ncs->v_int = atoi(ncs->intv_st); }\n action IntVal2St { ncs->intv2_st = p; }\n action IntVal2En {\n ncs->v_int2 = atoi(ncs->intv2_st);\n ncs->intv2_exist = true;\n }\n\n action StrValSt { ncs->strv_st = p; ncs->v_strlen = 0; }\n action StrValEn {\n ncs->v_strlen = p - ncs->strv_st;\n if (ncs->v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs->v_str, sizeof ncs->v_str,\n \"%.*s\", (int)ncs->v_strlen, ncs->strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs->v_str)\n suicide(\"error parsing line %u in crontab; too long?\",\n ncs->linenum);\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn) cmdterm;\n timeval = t_any (spc* t_any)* cmdterm;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))? cmdterm;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn) cmdterm;\n\n action JournalEn { ncs->ce->journal = 1; }\n action NoExecTimeEn { ncs->noextime = 1; }\n\n journal = 'journal'i cmdterm % JournalEn;\n noexectime = 'noexectime'i cmdterm % NoExecTimeEn;\n\n action RunAtEn {\n ncs->ce->exectime = ncs->v_int;\n ncs->ce->maxruns = 1;\n ncs->ce->journal = 1;\n }\n action MaxRunsEn {\n if (ncs->ce->exectime == 0)\n ncs->ce->maxruns = ncs->v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n\n action IntervalEn { ncs->ce->interval = ncs->v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addipairlist(ncs, &ncs->ce->month, 0, 1, 12); }\n action DayEn { addipairlist(ncs, &ncs->ce->day, 0, 1, 31); }\n action WeekdayEn { addipairlist(ncs, &ncs->ce->weekday, 0, 1, 7); }\n action HourEn { addipairlist(ncs, &ncs->ce->hour, 24, 0, 23); }\n action MinuteEn { addipairlist(ncs, &ncs->ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn {\n parse_assign_str(&ncs->ce->chroot, ncs->v_str, ncs->v_strlen,\n ncs->linenum);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n maxruns | runat | noexectime | journal;\n\n action JobIdSt { ncs->jobid_st = p; }\n action JobIdEn { ncs->ce->id = atoi(ncs->jobid_st); }\n action CreateCe { finish_ce(ncs); create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) cmdterm % JobIdEn;\n\n emptyline = '\\n';\n\n main := jobid | cmds | emptyline;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(struct ParseCfgState *ncs, char *data, size_t len)\n{\n char *p = data;\n const char *pe = data + len;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs->cs == ncrontab_error)\n return -1;\n if (ncs->cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(char *path, char *execfile, cronentry_t **stk,\n cronentry_t **deadstk)\n{\n char buf[MAXLINE];\n struct ParseCfgState ncs;\n memset(&ncs, 0, sizeof ncs);\n ncs.execfile = execfile;\n ncs.stack = *stk;\n ncs.deadstack = *deadstk;\n\n FILE *f = fopen(path, \"r\");\n if (!f)\n suicide(\"%s: fopen(%s) failed: %s\", __func__, path, strerror(errno));\n\n while (++ncs.linenum, fgets(buf, sizeof buf, f)) {\n int r = do_parse_config(&ncs, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_parse_config(%s) failed at line %u\",\n __func__, path, ncs.linenum);\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n *stk = ncs.stack;\n *deadstk = ncs.deadstack;\n if (ncs.ce)\n free_cronentry(&ncs.ce); \/\/ Free partially built unused item.\n cfg_reload = 1;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"1c34a2c161e5993e6130f42d647949f9c720778c","subject":"Improved regular expression handling and added an escape for \u00ab","message":"Improved regular expression handling and added an escape for \u00ab\n","repos":"fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil","old_file":"Source\/Tranquil\/lex.rl","new_file":"Source\/Tranquil\/lex.rl","new_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n NSError *syntaxError;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")* \":\";\n\n regexCont = (ualnum | ascii) - '\/' - '\\\\';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n \"\\\\\" lGuillmt => { [strBuf appendString:@\"\u00ab\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n \"\\\\\/\" => { [strBuf appendString:@\"\\\\\/\"]; };\n \"\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n regexCont => { [strBuf appendString:NSStr(0, 0)]; };\n \"\/\" [im]* term => { [strBuf appendString:@\"\/\"]; _EmitToken(REGEXNL, strBuf); fret; };\n \"\/\" [im]* => { [strBuf appendString:@\"\/\"]; _EmitToken(REGEX, strBuf); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else {\n strBuf = [NSMutableString stringWithString:@\"\/\"];\n fcall regex;\n }\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"do\" term? => { EmitToken(DO); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n \".\" => { EmitToken(PERIOD); };\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new], nil\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n _EmitToken(0, @\"EOF\");\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = parserState.syntaxError;\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","old_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n NSError *syntaxError;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")* \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"do\" term? => { EmitToken(DO); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n \".\" => { EmitToken(PERIOD); };\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new], nil\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = parserState.syntaxError;\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"b3fc99ff2f62a0d1f1f2956e793f663c7f5630f3","subject":"This works","message":"This works\n","repos":"pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = [a-zA-Z][a-zA-Z_]+; \n string = [\"][^\"]*[\"];\n boolean = '.';\n id_kw = 'ID'|'Number';\n\n action call_pairs { fcall pairs ; }\n\n pairs := |*\n 'ID=' identifier => {\n emit(:identifier, data, token_array, ts, te) \n };\n *|;\n\n # parser\n main := '<' @call_pairs ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data.pack(\"c*\")[ts...te] }\nend\n\ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n \n %% write init;\n %% write exec;\n\n p token_array\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n# run_lexer(\"value = -2.00\")\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s.sub(\/^##(FORMAT|INFO)=\/,'')) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\n # key := (\n \n # integer => { \n # emit(:integer_literal, data, token_array, ts, te) \n # };\n \n # float => { \n # emit(:float_literal, data, token_array, ts, te) \n # };\n \n # assignment => { \n # emit(:assignment_operator, data, token_array, ts, te) \n # };\n \n # boolean => { \n # emit(:boolean, data, token_array, ts, te) \n # };\n \n # identifier => { \n # emit(:identifier, data, token_array, ts, te) \n # };\n\n # string => { \n # emit(:string, data, token_array, ts, te) \n # };\n \n # space|',';\n \n # );\n\n","old_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = [a-zA-Z][a-zA-Z_]+; \n string = [\"][^\"]*[\"];\n boolean = '.';\n id_kw = 'ID';\n\n action call_pairs { fcall pairs ; }\n\n # keyword id pair parser\n # pairs := ( id_kw ); \n pairs := |*\n id_kw => {\n emit(:identifier, data, token_array, ts, te) \n };\n *|;\n\n # parser\n main := '<' @ call_pairs ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data.pack(\"c*\")[ts...te] }\nend\n\ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n \n %% write init;\n %% write exec;\n\n p token_array\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n# run_lexer(\"value = -2.00\")\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s.sub(\/^##(FORMAT|INFO)=\/,'')) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\n # key := (\n \n # integer => { \n # emit(:integer_literal, data, token_array, ts, te) \n # };\n \n # float => { \n # emit(:float_literal, data, token_array, ts, te) \n # };\n \n # assignment => { \n # emit(:assignment_operator, data, token_array, ts, te) \n # };\n \n # boolean => { \n # emit(:boolean, data, token_array, ts, te) \n # };\n \n # identifier => { \n # emit(:identifier, data, token_array, ts, te) \n # };\n\n # string => { \n # emit(:string, data, token_array, ts, te) \n # };\n \n # space|',';\n \n # );\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"0a32a86eb8e54324e78cdfd1ac217dba3f100e5f","subject":"Precedence of strings","message":"Precedence of strings","repos":"medcat\/liquidscript,medcat\/liquidscript","old_file":"lib\/liquidscript\/scanner\/lexer.rl","new_file":"lib\/liquidscript\/scanner\/lexer.rl","new_contents":"%%{\n\n machine lexer;\n\n variable data @data;\n variable p @p;\n variable pe @pe;\n variable eof @eof;\n access @;\n \n action mark {\n @start = @p\n }\n\n number_integer = '-'? [0-9][1-9]*;\n number_frac = '.' [0-9]+;\n number_e = ('e' | 'E') ('+' | '-' | '');\n number_exp = number_e [0-9]+;\n number = number_integer number_frac? number_exp?;\n\n string_double = '\"' ( \n any -- '\"' | \n '\\\\\"' \n )* '\"';\n identifier = [A-Za-z_$][A-Za-z0-9_$]*;\n string_single = \"'\" [A-Za-z0-9_$\\-]+;\n keywords = 'undefined' | 'null' | 'true' | 'false';\n unops = '!' | '++' | '--' | '~' | 'new' | 'return' |\n 'typeof';\n binops = '+' | '-' | '*' | '\/' | '&' | '|' | '^' | '<<' | '>>' |\n '>>>' | '==' | '!=' | '===' | '!==' | '>' | '>=' | '<' | '<=' |\n '&&' | '||' | 'instanceof' | 'or' | 'and';\n \n istring_part = ( any -- '\"' | '\\\\\"' );\n istring_start = '\"' ( istring_part* ) '#{';\n istring_mid = '}' ( istring_part* ) '#{';\n istring_end = '}' ( istring_part* ) '\"';\n \n main := |*\n number => { emit :number };\n string_single => { emit :sstring };\n istring_start => { emit :istart };\n istring_mid => { emit :imid };\n istring_end => { emit :iend };\n string_double => { emit :dstring };\n 'class' => { emit :class };\n 'module' => { emit :module };\n 'if' => { emit :if };\n 'unless' => { emit :unless };\n 'elsif' => { emit :elsif };\n 'else' => { emit :else };\n unops => { emit :unop };\n binops => { emit :binop };\n keywords => { emit :keyword };\n identifier => { emit :identifier };\n '->' => { emit :arrow };\n '=' => { emit :equal };\n '{' => { emit :lbrack };\n '(' => { emit :lparen };\n '[' => { emit :lbrace };\n '}' => { emit :rbrack };\n ')' => { emit :rparen };\n ']' => { emit :rbrace };\n ':' => { emit :colon };\n '.' => { emit :prop };\n ',' => { emit :comma };\n '\\n' => { line.call };\n space => { };\n any => { error };\n *|;\n}%%\n\nmodule Liquidscript\n class Scanner\n\n # A lexer, built from ragel.\n #\n # @private\n class Lexer\n\n attr_reader :tokens\n\n def initialize\n %% write data;\n # %% # fix\n @tokens = []\n clean!\n end\n\n def clean!\n @p = nil\n @pe = nil\n @te = nil\n @ts = nil\n @act = nil\n @eof = nil\n @top = nil\n @line = { :start => 0, :num => 0 }\n @data = nil\n @stack = nil\n @start = nil\n end\n\n def emit(type)\n @tokens << if @start\n Token.new(type, @data[@start..(@p - 1)],\n @line[:num], @p - @line[:start])\n else\n Token.new(type, nil, @line[:num], @p - @line[:start])\n end\n \n @start = nil\n end\n\n def error\n raise SyntaxError, \"Unexpected #{@data[@start..(@p-1)].pack('c*')}\"\n end\n\n def perform(data)\n @data = data.unpack(\"c*\") if data.is_a? String\n @eof = data.length\n\n @tokens = []\n\n line = proc do\n @line[:start] = @ts\n @line[:num] += 1\n emit :newline\n end\n\n %% write init;\n %% write exec;\n\n clean!\n\n @tokens\n end\n end\n end\nend\n","old_contents":"%%{\n\n machine lexer;\n\n variable data @data;\n variable p @p;\n variable pe @pe;\n variable eof @eof;\n access @;\n \n action mark {\n @start = @p\n }\n\n number_integer = '-'? [0-9][1-9]*;\n number_frac = '.' [0-9]+;\n number_e = ('e' | 'E') ('+' | '-' | '');\n number_exp = number_e [0-9]+;\n number = number_integer number_frac? number_exp?;\n\n string_double = '\"' ( \n any -- '\"' | \n '\\\\\"' \n )* '\"';\n identifier = [A-Za-z_$][A-Za-z0-9_$]*;\n string_single = \"'\" [A-Za-z0-9_$\\-]+;\n keywords = 'undefined' | 'null' | 'true' | 'false';\n unops = '!' | '++' | '--' | '~' | 'new' | 'return' |\n 'typeof';\n binops = '+' | '-' | '*' | '\/' | '&' | '|' | '^' | '<<' | '>>' |\n '>>>' | '==' | '!=' | '===' | '!==' | '>' | '>=' | '<' | '<=' |\n '&&' | '||' | 'instanceof' | 'or' | 'and';\n \n istring_part = ( any -- '\"' | '\\\\\"' );\n istring_start = '\"' ( istring_part* ) '#{';\n istring_mid = '}' ( istring_part* ) '#{';\n istring_end = '}' ( istring_part* ) '\"';\n \n main := |*\n number => { emit :number };\n string_double => { emit :dstring };\n string_single => { emit :sstring };\n istring_start => { emit :istart };\n istring_mid => { emit :imid };\n istring_end => { emit :iend };\n 'class' => { emit :class };\n 'module' => { emit :module };\n 'if' => { emit :if };\n 'unless' => { emit :unless };\n 'elsif' => { emit :elsif };\n 'else' => { emit :else };\n unops => { emit :unop };\n binops => { emit :binop };\n keywords => { emit :keyword };\n identifier => { emit :identifier };\n '->' => { emit :arrow };\n '=' => { emit :equal };\n '{' => { emit :lbrack };\n '(' => { emit :lparen };\n '[' => { emit :lbrace };\n '}' => { emit :rbrack };\n ')' => { emit :rparen };\n ']' => { emit :rbrace };\n ':' => { emit :colon };\n '.' => { emit :prop };\n ',' => { emit :comma };\n '\\n' => { line.call };\n space => { };\n any => { error };\n *|;\n}%%\n\nmodule Liquidscript\n class Scanner\n\n # A lexer, built from ragel.\n #\n # @private\n class Lexer\n\n attr_reader :tokens\n\n def initialize\n %% write data;\n # %% # fix\n @tokens = []\n clean!\n end\n\n def clean!\n @p = nil\n @pe = nil\n @te = nil\n @ts = nil\n @act = nil\n @eof = nil\n @top = nil\n @line = { :start => 0, :num => 0 }\n @data = nil\n @stack = nil\n @start = nil\n end\n\n def emit(type)\n @tokens << if @start\n Token.new(type, @data[@start..(@p - 1)],\n @line[:num], @p - @line[:start])\n else\n Token.new(type, nil, @line[:num], @p - @line[:start])\n end\n \n @start = nil\n end\n\n def error\n raise SyntaxError, \"Unexpected #{@data[@start..(@p-1)].pack('c*')}\"\n end\n\n def perform(data)\n @data = data.unpack(\"c*\") if data.is_a? String\n @eof = data.length\n\n @tokens = []\n\n line = proc do\n @line[:start] = @ts\n @line[:num] += 1\n emit :newline\n end\n\n %% write init;\n %% write exec;\n\n clean!\n\n @tokens\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"3625d6765ff87c0213d0360c8c6f206bd345a860","subject":"Fix compiler warnings.","message":"Fix compiler warnings.","repos":"github\/redcloth,mmorga\/redcloth,amrocco\/redcloth,mmorga\/redcloth,dmitry\/redcloth,amrocco\/redcloth,github\/redcloth,purcell\/redcloth,dmitry\/redcloth,purcell\/redcloth","old_file":"ragel\/redcloth_scan.c.rl","new_file":"ragel\/redcloth_scan.c.rl","new_contents":"\/*\n * redcloth_scan.c.rl\n *\n * Copyright (C) 2009 Jason Garber\n *\/\n#define redcloth_scan_c\n\n#include \n#include \"redcloth.h\"\n\nVALUE mRedCloth, super_ParseError, super_RedCloth, super_HTML, super_LATEX;\nVALUE SYM_escape_preformatted, SYM_escape_attributes;\n\n%%{\n\n machine redcloth_scan;\n include redcloth_common \"redcloth_common.c.rl\";\n\n action extend { extend = rb_hash_aref(regs, ID2SYM(rb_intern(\"type\"))); }\n\n include redcloth_scan \"redcloth_scan.rl\";\n\n}%%\n\n%% write data nofinal;\n\nVALUE\nredcloth_transform(self, p, pe, refs)\n VALUE self;\n char *p, *pe;\n VALUE refs;\n{\n char *orig_p = p, *orig_pe = pe;\n int cs, act, nest = 0;\n char *ts = NULL, *te = NULL, *reg = NULL, *bck = NULL, *attr_reg = NULL, *eof = NULL;\n VALUE html = STR_NEW2(\"\");\n VALUE table = STR_NEW2(\"\");\n VALUE block = STR_NEW2(\"\");\n VALUE regs, attr_regs; CLEAR_REGS()\n \n \n VALUE list_layout = Qnil;\n const char *list_type = NULL;\n VALUE list_index = rb_ary_new();\n VALUE plain_block; SET_PLAIN_BLOCK(\"p\");\n VALUE extend = Qnil;\n char listm[10] = \"\";\n VALUE refs_found = rb_hash_new();\n \n %% write init;\n\n %% write exec;\n\n if (RSTRING_LEN(block) > 0)\n {\n ADD_BLOCK();\n }\n\n if ( NIL_P(refs) && rb_funcall(refs_found, rb_intern(\"empty?\"), 0) == Qfalse ) {\n return redcloth_transform(self, orig_p, orig_pe, refs_found);\n } else {\n rb_funcall(self, rb_intern(\"after_transform\"), 1, html);\n return html;\n }\n}\n\nVALUE\nredcloth_transform2(self, str)\n VALUE self, str;\n{\n StringValue(str);\n rb_funcall(self, rb_intern(\"before_transform\"), 1, str);\n return redcloth_transform(self, RSTRING_PTR(str), RSTRING_PTR(str) + RSTRING_LEN(str) + 1, Qnil);\n}\n\n\/*\n * Converts special characters into HTML entities.\n *\/\nstatic VALUE\nredcloth_html_esc(int argc, VALUE* argv, VALUE self) \/\/(self, str, level)\n{\n VALUE str, level;\n \n rb_scan_args(argc, argv, \"11\", &str, &level);\n \n VALUE new_str = STR_NEW2(\"\");\n if (str == Qnil)\n return new_str;\n \n StringValue(str);\n \n if (RSTRING_LEN(str) == 0)\n return new_str;\n \n char *ts = RSTRING_PTR(str), *te = RSTRING_PTR(str) + RSTRING_LEN(str);\n char *t = ts, *t2 = ts;\n const char *ch = NULL;\n if (te <= ts) return Qnil;\n\n while (t2 < te) {\n ch = NULL;\n \n \/\/ normal + pre\n switch (*t2)\n {\n case '&': ch = \"amp\"; break;\n case '>': ch = \"gt\"; break;\n case '<': ch = \"lt\"; break;\n }\n \n \/\/ normal (non-pre)\n if (level != SYM_escape_preformatted) {\n switch (*t2)\n {\n case '\\n': ch = \"br\"; break;\n case '\"' : ch = \"quot\"; break;\n case '\\'': \n ch = (level == SYM_escape_attributes) ? \"apos\" : \"squot\";\n break;\n }\n }\n \n if (ch != NULL)\n {\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n rb_str_concat(new_str, rb_funcall(self, rb_intern(ch), 1, rb_hash_new()));\n t = t2 + 1;\n }\n\n t2++;\n }\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n \n return new_str;\n}\n\n\/*\n * Converts special characters into LaTeX entities.\n *\/\nstatic VALUE\nredcloth_latex_esc(VALUE self, VALUE str)\n{ \n VALUE new_str = STR_NEW2(\"\");\n \n if (str == Qnil)\n return new_str;\n \n StringValue(str);\n \n if (RSTRING_LEN(str) == 0)\n return new_str;\n \n char *ts = RSTRING_PTR(str), *te = RSTRING_PTR(str) + RSTRING_LEN(str);\n char *t = ts, *t2 = ts;\n const char *ch = NULL;\n if (te <= ts) return Qnil;\n\n while (t2 < te) {\n ch = NULL;\n \n switch (*t2) \n { \n case '{': ch = \"#123\"; break;\n case '}': ch = \"#125\"; break;\n case '\\\\': ch = \"#92\"; break;\n case '#': ch = \"#35\"; break;\n case '$': ch = \"#36\"; break;\n case '%': ch = \"#37\"; break;\n case '&': ch = \"amp\"; break;\n case '_': ch = \"#95\"; break;\n case '^': ch = \"circ\"; break;\n case '~': ch = \"tilde\"; break;\n case '<': ch = \"lt\"; break;\n case '>': ch = \"gt\"; break;\n case '\\n': ch = \"#10\"; break;\n }\n\n if (ch != NULL)\n {\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n VALUE opts = rb_hash_new();\n rb_hash_aset(opts, ID2SYM(rb_intern(\"text\")), STR_NEW2(ch));\n rb_str_concat(new_str, rb_funcall(self, rb_intern(\"entity\"), 1, opts));\n t = t2 + 1;\n }\n\n t2++;\n }\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n \n return new_str;\n}\n\n\/*\n * Transforms a Textile document with +formatter+\n *\/\nstatic VALUE\nredcloth_to(self, formatter)\n VALUE self, formatter;\n{\n rb_funcall(self, rb_intern(\"delete!\"), 1, STR_NEW2(\"\\r\"));\n VALUE working_copy = rb_obj_clone(self);\n rb_extend_object(working_copy, formatter);\n \n if (rb_funcall(working_copy, rb_intern(\"lite_mode\"), 0) == Qtrue) {\n return redcloth_inline2(working_copy, self, rb_hash_new());\n } else {\n return redcloth_transform2(working_copy, self);\n }\n}\n\nvoid Init_redcloth_scan()\n{\n mRedCloth = rb_define_module(\"RedCloth\");\n rb_define_const( mRedCloth, \"EXTENSION_LANGUAGE\", rb_str_new2(\"C\") );\n \/* A Textile document that can be converted to other formats. See\n the README for Textile syntax. *\/\n super_RedCloth = rb_define_class_under(mRedCloth, \"TextileDoc\", rb_cString);\n rb_define_method(super_RedCloth, \"to\", redcloth_to, 1);\n super_ParseError = rb_define_class_under(super_RedCloth, \"ParseError\", rb_eException);\n \/* Escaping *\/\n rb_define_method(super_RedCloth, \"html_esc\", redcloth_html_esc, -1);\n rb_define_method(super_RedCloth, \"latex_esc\", redcloth_latex_esc, 1);\n SYM_escape_preformatted = ID2SYM(rb_intern(\"html_escape_preformatted\"));\n SYM_escape_attributes = ID2SYM(rb_intern(\"html_escape_attributes\"));\n}\n","old_contents":"\/*\n * redcloth_scan.c.rl\n *\n * Copyright (C) 2009 Jason Garber\n *\/\n#define redcloth_scan_c\n\n#include \n#include \"redcloth.h\"\n\nVALUE mRedCloth, super_ParseError, super_RedCloth, super_HTML, super_LATEX;\nint SYM_escape_preformatted, SYM_escape_attributes;\n\n%%{\n\n machine redcloth_scan;\n include redcloth_common \"redcloth_common.c.rl\";\n\n action extend { extend = rb_hash_aref(regs, ID2SYM(rb_intern(\"type\"))); }\n\n include redcloth_scan \"redcloth_scan.rl\";\n\n}%%\n\n%% write data nofinal;\n\nVALUE\nredcloth_transform(self, p, pe, refs)\n VALUE self;\n char *p, *pe;\n VALUE refs;\n{\n char *orig_p = p, *orig_pe = pe;\n int cs, act, nest = 0;\n char *ts = NULL, *te = NULL, *reg = NULL, *bck = NULL, *attr_reg = NULL, *eof = NULL;\n VALUE html = STR_NEW2(\"\");\n VALUE table = STR_NEW2(\"\");\n VALUE block = STR_NEW2(\"\");\n VALUE regs, attr_regs; CLEAR_REGS()\n \n \n VALUE list_layout = Qnil;\n char *list_type = NULL;\n VALUE list_index = rb_ary_new();\n VALUE plain_block; SET_PLAIN_BLOCK(\"p\");\n VALUE extend = Qnil;\n char listm[10] = \"\";\n VALUE refs_found = rb_hash_new();\n \n %% write init;\n\n %% write exec;\n\n if (RSTRING_LEN(block) > 0)\n {\n ADD_BLOCK();\n }\n\n if ( NIL_P(refs) && rb_funcall(refs_found, rb_intern(\"empty?\"), 0) == Qfalse ) {\n return redcloth_transform(self, orig_p, orig_pe, refs_found);\n } else {\n rb_funcall(self, rb_intern(\"after_transform\"), 1, html);\n return html;\n }\n}\n\nVALUE\nredcloth_transform2(self, str)\n VALUE self, str;\n{\n StringValue(str);\n rb_funcall(self, rb_intern(\"before_transform\"), 1, str);\n return redcloth_transform(self, RSTRING_PTR(str), RSTRING_PTR(str) + RSTRING_LEN(str) + 1, Qnil);\n}\n\n\/*\n * Converts special characters into HTML entities.\n *\/\nstatic VALUE\nredcloth_html_esc(int argc, VALUE* argv, VALUE self) \/\/(self, str, level)\n{\n VALUE str, level;\n \n rb_scan_args(argc, argv, \"11\", &str, &level);\n \n VALUE new_str = STR_NEW2(\"\");\n if (str == Qnil)\n return new_str;\n \n StringValue(str);\n \n if (RSTRING_LEN(str) == 0)\n return new_str;\n \n char *ts = RSTRING_PTR(str), *te = RSTRING_PTR(str) + RSTRING_LEN(str);\n char *t = ts, *t2 = ts, *ch = NULL;\n if (te <= ts) return Qnil;\n\n while (t2 < te) {\n ch = NULL;\n \n \/\/ normal + pre\n switch (*t2)\n {\n case '&': ch = \"amp\"; break;\n case '>': ch = \"gt\"; break;\n case '<': ch = \"lt\"; break;\n }\n \n \/\/ normal (non-pre)\n if (level != SYM_escape_preformatted) {\n switch (*t2)\n {\n case '\\n': ch = \"br\"; break;\n case '\"' : ch = \"quot\"; break;\n case '\\'': \n ch = (level == SYM_escape_attributes) ? \"apos\" : \"squot\";\n break;\n }\n }\n \n if (ch != NULL)\n {\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n rb_str_concat(new_str, rb_funcall(self, rb_intern(ch), 1, rb_hash_new()));\n t = t2 + 1;\n }\n\n t2++;\n }\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n \n return new_str;\n}\n\n\/*\n * Converts special characters into LaTeX entities.\n *\/\nstatic VALUE\nredcloth_latex_esc(VALUE self, VALUE str)\n{ \n VALUE new_str = STR_NEW2(\"\");\n \n if (str == Qnil)\n return new_str;\n \n StringValue(str);\n \n if (RSTRING_LEN(str) == 0)\n return new_str;\n \n char *ts = RSTRING_PTR(str), *te = RSTRING_PTR(str) + RSTRING_LEN(str);\n char *t = ts, *t2 = ts, *ch = NULL;\n if (te <= ts) return Qnil;\n\n while (t2 < te) {\n ch = NULL;\n \n switch (*t2) \n { \n case '{': ch = \"#123\"; break;\n case '}': ch = \"#125\"; break;\n case '\\\\': ch = \"#92\"; break;\n case '#': ch = \"#35\"; break;\n case '$': ch = \"#36\"; break;\n case '%': ch = \"#37\"; break;\n case '&': ch = \"amp\"; break;\n case '_': ch = \"#95\"; break;\n case '^': ch = \"circ\"; break;\n case '~': ch = \"tilde\"; break;\n case '<': ch = \"lt\"; break;\n case '>': ch = \"gt\"; break;\n case '\\n': ch = \"#10\"; break;\n }\n\n if (ch != NULL)\n {\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n VALUE opts = rb_hash_new();\n rb_hash_aset(opts, ID2SYM(rb_intern(\"text\")), STR_NEW2(ch));\n rb_str_concat(new_str, rb_funcall(self, rb_intern(\"entity\"), 1, opts));\n t = t2 + 1;\n }\n\n t2++;\n }\n if (t2 > t)\n rb_str_cat(new_str, t, t2-t);\n \n return new_str;\n}\n\n\/*\n * Transforms a Textile document with +formatter+\n *\/\nstatic VALUE\nredcloth_to(self, formatter)\n VALUE self, formatter;\n{\n rb_funcall(self, rb_intern(\"delete!\"), 1, STR_NEW2(\"\\r\"));\n VALUE working_copy = rb_obj_clone(self);\n rb_extend_object(working_copy, formatter);\n \n if (rb_funcall(working_copy, rb_intern(\"lite_mode\"), 0) == Qtrue) {\n return redcloth_inline2(working_copy, self, rb_hash_new());\n } else {\n return redcloth_transform2(working_copy, self);\n }\n}\n\nvoid Init_redcloth_scan()\n{\n mRedCloth = rb_define_module(\"RedCloth\");\n rb_define_const( mRedCloth, \"EXTENSION_LANGUAGE\", rb_str_new2(\"C\") );\n \/* A Textile document that can be converted to other formats. See\n the README for Textile syntax. *\/\n super_RedCloth = rb_define_class_under(mRedCloth, \"TextileDoc\", rb_cString);\n rb_define_method(super_RedCloth, \"to\", redcloth_to, 1);\n super_ParseError = rb_define_class_under(super_RedCloth, \"ParseError\", rb_eException);\n \/* Escaping *\/\n rb_define_method(super_RedCloth, \"html_esc\", redcloth_html_esc, -1);\n rb_define_method(super_RedCloth, \"latex_esc\", redcloth_latex_esc, 1);\n SYM_escape_preformatted = ID2SYM(rb_intern(\"html_escape_preformatted\"));\n SYM_escape_attributes = ID2SYM(rb_intern(\"html_escape_attributes\"));\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"dbbafe267bac2bce3095557a9f67856d219348e8","subject":"Ragel works","message":"Ragel works\n","repos":"pjotrp\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,gusevfe\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = [a-zA-Z][a-zA-Z_]+; \n string = [\"][^\"]*[\"];\n boolean = '.';\n key_word = ( ('ID'|'Number'|'Type'|'Description') %{ puts \"**keyword\" } );\n value = ( (integer|float|boolean|identifier|string) %{ puts \"***value\" } );\n\n key_value = ( key_word '=' value ) ;\n \n main := ( ('<'|',') key_value )*;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data.pack(\"c*\")[ts...te] }\nend\n\ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n \n %% write init;\n %% write exec;\n\n p token_array\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n# run_lexer(\"value = -2.00\")\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s.sub(\/^##(FORMAT|INFO)=\/,'')) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\n # key := (\n \n # integer => { \n # emit(:integer_literal, data, token_array, ts, te) \n # };\n \n # float => { \n # emit(:float_literal, data, token_array, ts, te) \n # };\n \n # assignment => { \n # emit(:assignment_operator, data, token_array, ts, te) \n # };\n \n # boolean => { \n # emit(:boolean, data, token_array, ts, te) \n # };\n \n # identifier => { \n # emit(:identifier, data, token_array, ts, te) \n # };\n\n # string => { \n # emit(:string, data, token_array, ts, te) \n # };\n \n # space|',';\n \n # );\n\n","old_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = [a-zA-Z][a-zA-Z_]+; \n string = [\"][^\"]*[\"];\n boolean = '.';\n id_kw = 'ID'|'Number';\n\n action call_key { fcall key ; }\n action call_value {}\n\n n := ( identifier );\n\n key := |*\n 'ID'|'Number' => {\n emit(:identifier, data, token_array, ts, te) \n };\n *|;\n\n # parser\n main := ( ('<'|',') @call_key '=' @call_value )+ ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data.pack(\"c*\")[ts...te] }\nend\n\ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n \n %% write init;\n %% write exec;\n\n p token_array\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n# run_lexer(\"value = -2.00\")\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s.sub(\/^##(FORMAT|INFO)=\/,'')) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\n # key := (\n \n # integer => { \n # emit(:integer_literal, data, token_array, ts, te) \n # };\n \n # float => { \n # emit(:float_literal, data, token_array, ts, te) \n # };\n \n # assignment => { \n # emit(:assignment_operator, data, token_array, ts, te) \n # };\n \n # boolean => { \n # emit(:boolean, data, token_array, ts, te) \n # };\n \n # identifier => { \n # emit(:identifier, data, token_array, ts, te) \n # };\n\n # string => { \n # emit(:string, data, token_array, ts, te) \n # };\n \n # space|',';\n \n # );\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"478bb4d6cc95e9d0ecc0791e28f564b26c1da5be","subject":"In the port from flex to ragel, the Name separator :: in Ragel code was lost. Added it back.","message":"In the port from flex to ragel, the Name separator :: in Ragel code was lost.\nAdded it back.\n","repos":"timoc\/ragel,timoc\/ragel,timoc\/ragel,timoc\/ragel","old_file":"ragel\/rlscan.rl","new_file":"ragel\/rlscan.rl","new_contents":"\/*\n * Copyright 2006-2007 Adrian Thurston \n *\/\n\n\/* This file is part of Ragel.\n *\n * Ragel is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Ragel is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Ragel; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"ragel.h\"\n#include \"rlparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nextern char *Parser_lelNames[];\n\n\/* This is used for tracking the current stack of include file\/machine pairs. It is\n * is used to detect and recursive include structure. *\/\nstruct IncludeStackItem\n{\n\tIncludeStackItem( char *fileName, char *sectionName )\n\t\t: fileName(fileName), sectionName(sectionName) {}\n\n\tchar *fileName;\n\tchar *sectionName;\n};\n\ntypedef Vector IncludeStack;\n\nenum InlineBlockType\n{\n\tCurlyDelimited,\n\tSemiTerminated\n};\n\nstruct Scanner\n{\n\tScanner( char *fileName, istream &input, ostream &output,\n\t\t\tParser *inclToParser, char *inclSectionTarg,\n\t\t\tint includeDepth )\n\t: \n\t\tfileName(fileName), input(input), output(output),\n\t\tinclToParser(inclToParser),\n\t\tinclSectionTarg(inclSectionTarg),\n\t\tincludeDepth(includeDepth),\n\t\tline(1), column(1), lastnl(0), \n\t\tparser(0), ignoreSection(false), \n\t\tparserExistsError(false),\n\t\twhitespaceOn(true),\n\t\tlastToken(0)\n\t\t{}\n\n\tbool recursiveInclude( char *inclFileName, char *inclSectionName );\n\n\tchar *prepareFileName( char *fileName, int len )\n\t{\n\t\tbool caseInsensitive;\n\t\tToken tokenFnStr, tokenRes;\n\t\ttokenFnStr.data = fileName;\n\t\ttokenFnStr.length = len;\n\t\ttokenFnStr.prepareLitString( tokenRes, caseInsensitive );\n\t\treturn tokenRes.data;\n\t}\n\n\tvoid init();\n\tvoid token( int type, char *start, char *end );\n\tvoid token( int type, char c );\n\tvoid token( int type );\n\tvoid updateCol();\n\tvoid startSection();\n\tvoid endSection();\n\tvoid do_scan();\n\tbool active();\n\tostream &scan_error();\n\n\tchar *fileName;\n\tistream &input;\n\tostream &output;\n\tParser *inclToParser;\n\tchar *inclSectionTarg;\n\tint includeDepth;\n\n\tint cs;\n\tint line;\n\tchar *word, *lit;\n\tint word_len, lit_len;\n\tInputLoc sectionLoc;\n\tchar *tokstart, *tokend;\n\tint column;\n\tchar *lastnl;\n\n\t\/* Set by machine statements, these persist from section to section\n\t * allowing for unnamed sections. *\/\n\tParser *parser;\n\tbool ignoreSection;\n\tIncludeStack includeStack;\n\n\t\/* This is set if ragel has already emitted an error stating that\n\t * no section name has been seen and thus no parser exists. *\/\n\tbool parserExistsError;\n\n\t\/* This is for inline code. By default it is on. It goes off for\n\t * statements and values in inline blocks which are parsed. *\/\n\tbool whitespaceOn;\n\n\t\/* Keeps a record of the previous token sent to the section parser. *\/\n\tint lastToken;\n};\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid Scanner::init( )\n{\n\t%% write init;\n}\n\nbool Scanner::active()\n{\n\tif ( ignoreSection )\n\t\treturn false;\n\n\tif ( parser == 0 && ! parserExistsError ) {\n\t\tscan_error() << \"there is no previous specification name\" << endl;\n\t\tparserExistsError = true;\n\t}\n\n\tif ( parser == 0 )\n\t\treturn false;\n\n\treturn true;\n}\n\nostream &Scanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 &&\n\t\t\t\tstrcmp( si->sectionName, inclSectionName ) == 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\t\n}\n\nvoid Scanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = tokstart;\n\t\/\/cerr << \"adding \" << tokend - from << \" to column\" << endl;\n\tcolumn += tokend - from;\n\tlastnl = 0;\n}\n\nvoid Scanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid Scanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\n%%{\n\tmachine section_parse;\n\n\t# This relies on the the kelbt implementation and the order\n\t# that tokens are declared.\n\tKW_Machine = 128;\n\tKW_Include = 129;\n\tKW_Write = 130;\n\tTK_Word = 131;\n\tTK_Literal = 132;\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_word { word = tokdata; word_len = toklen; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_machine\n\t{\n\t\t\/* Assign a name to the machine. *\/\n\t\tchar *machine = word;\n\n\t\tif ( inclSectionTarg == 0 ) {\n\t\t\tignoreSection = false;\n\n\t\t\tParserDictEl *pdEl = parserDict.find( machine );\n\t\t\tif ( pdEl == 0 ) {\n\t\t\t\tpdEl = new ParserDictEl( machine );\n\t\t\t\tpdEl->value = new Parser( fileName, machine, sectionLoc );\n\t\t\t\tpdEl->value->init();\n\t\t\t\tparserDict.insert( pdEl );\n\t\t\t}\n\n\t\t\tparser = pdEl->value;\n\t\t}\n\t\telse if ( strcmp( inclSectionTarg, machine ) == 0 ) {\n\t\t\t\/* found include target *\/\n\t\t\tignoreSection = false;\n\t\t\tparser = inclToParser;\n\t\t}\n\t\telse {\n\t\t\t\/* ignoring section *\/\n\t\t\tignoreSection = true;\n\t\t\tparser = 0;\n\t\t}\n\t}\n\n\tmachine_stmt =\n\t\t( KW_Machine TK_Word @store_word ';' ) @handle_machine\n\t\t<>err mach_err <>eof mach_err;\n\n\taction handle_include\n\t{\n\t\tif ( active() ) {\n\t\t\tchar *inclSectionName = word;\n\t\t\tchar *inclFileName = 0;\n\n\t\t\t\/* Implement defaults for the input file and section name. *\/\n\t\t\tif ( inclSectionName == 0 )\n\t\t\t\tinclSectionName = parser->sectionName;\n\n\t\t\tif ( lit != 0 ) \n\t\t\t\tinclFileName = prepareFileName( lit, lit_len );\n\t\t\telse\n\t\t\t\tinclFileName = fileName;\n\n\t\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t\t * name then check if what we are including is already in the stack. *\/\n\t\t\tincludeStack.append( IncludeStackItem( fileName, parser->sectionName ) );\n\n\t\t\tif ( recursiveInclude( inclFileName, inclSectionName ) )\n\t\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\t\t\telse {\n\t\t\t\t\/* Open the input file for reading. *\/\n\t\t\t\tifstream *inFile = new ifstream( inclFileName );\n\t\t\t\tif ( ! inFile->is_open() ) {\n\t\t\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\t\t\tinclFileName << \" for reading\" << endl;\n\t\t\t\t}\n\n\t\t\t\tScanner scanner( inclFileName, *inFile, output, parser,\n\t\t\t\t\t\tinclSectionName, includeDepth+1 );\n\t\t\t\tscanner.init();\n\t\t\t\tscanner.do_scan( );\n\t\t\t\tdelete inFile;\n\t\t\t}\n\n\t\t\t\/* Remove the last element (len-1) *\/\n\t\t\tincludeStack.remove( -1 );\n\t\t}\n\t}\n\n\tinclude_names = (\n\t\tTK_Word @store_word ( TK_Literal @store_lit )? |\n\t\tTK_Literal @store_lit\n\t) >clear_words;\n\n\tinclude_stmt =\n\t\t( KW_Include include_names ';' ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction write_command\n\t{\n\t\tif ( active() && machineSpec == 0 && machineName == 0 ) {\n\t\t\toutput << \"sectionName << \"\\\"\"\n\t\t\t\t\t\" line=\\\"\" << line << \"\\\"\"\n\t\t\t\t\t\" col=\\\"\" << column << \"\\\"\"\n\t\t\t\t\t\">\";\n\t\t}\n\t}\n\n\taction write_arg\n\t{\n\t\tif ( active() && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"\" << tokdata << \"<\/arg>\";\n\t}\n\n\taction write_close\n\t{\n\t\tif ( active() && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/write>\\n\";\n\t}\n\n\twrite_stmt =\n\t\t( KW_Write @write_command \n\t\t( TK_Word @write_arg )+ ';' @write_close )\n\t\t<>err write_err <>eof write_err;\n\n\taction handle_token\n\t{\n\t\t\/* Send the token off to the parser. *\/\n\t\tif ( active() ) {\n\t\t\tInputLoc loc;\n\n\t\t\t#if 0\n\t\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\t\tcerr << \" \" << toklen;\n\t\t\tif ( tokdata != 0 )\n\t\t\t\tcerr << \" \" << tokdata;\n\t\t\tcerr << endl;\n\t\t\t#endif\n\n\t\t\tloc.fileName = fileName;\n\t\t\tloc.line = line;\n\t\t\tloc.col = column;\n\n\t\t\tparser->token( loc, type, tokdata, toklen );\n\t\t}\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;\n\n\tmain := ( \n\t\tmachine_stmt |\n\t\tinclude_stmt |\n\t\twrite_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid Scanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n\n\t\/* Record the last token for use in controlling the scan of subsequent\n\t * tokens. *\/\n\tlastToken = type;\n}\n\nvoid Scanner::startSection( )\n{\n\tparserExistsError = false;\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/host>\\n\";\n\t}\n\n\tsectionLoc.fileName = fileName;\n\tsectionLoc.line = line;\n\tsectionLoc.col = 0;\n}\n\nvoid Scanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t%%{\n\t\tmachine section_parse;\n\t\twrite eof;\n\t}%%\n\n\t\/* Close off the section with the parser. *\/\n\tif ( active() ) {\n\t\tInputLoc loc;\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = 0;\n\n\t\tparser->token( loc, TK_EndSection, 0, 0 );\n\t}\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 ) {\n\t\t\t\/* The end section may include a newline on the end, so\n\t\t\t * we use the last line, which will count the newline. *\/\n\t\t\toutput << \"\";\n\t\t}\n\t}\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\tc_comment = \n\t\t'\/*' ( any | NL )* :>> '*\/';\n\n\tcpp_comment =\n\t\t'\/\/' [^\\n]* NL;\n\n\tc_cpp_comment = c_comment | cpp_comment;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\t# An inline block of code. This is specified as a scanned, but is sent to\n\t# the parser as one long block. The inline_block pointer is used to handle\n\t# the preservation of the data.\n\tinline_code := |*\n\t\t# Inline expression keywords.\n\t\t\"fpc\" => { token( KW_PChar ); };\n\t\t\"fc\" => { token( KW_Char ); };\n\t\t\"fcurs\" => { token( KW_CurState ); };\n\t\t\"ftargs\" => { token( KW_TargState ); };\n\t\t\"fentry\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Entry );\n\t\t};\n\n\t\t# Inline statement keywords.\n\t\t\"fhold\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Hold );\n\t\t};\n\t\t\"fexec\" => { token( KW_Exec, 0, 0 ); };\n\t\t\"fgoto\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Goto );\n\t\t};\n\t\t\"fnext\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Next );\n\t\t};\n\t\t\"fcall\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Call );\n\t\t};\n\t\t\"fret\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Ret );\n\t\t};\n\t\t\"fbreak\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Break );\n\t\t};\n\n\t\tident => { token( TK_Word, tokstart, tokend ); };\n\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t( s_literal | d_literal ) \n\t\t\t=> { token( IL_Literal, tokstart, tokend ); };\n\n\t\twhitespace+ => { \n\t\t\tif ( whitespaceOn ) \n\t\t\t\ttoken( IL_WhiteSpace, tokstart, tokend );\n\t\t};\n\t\tc_cpp_comment => { token( IL_Comment, tokstart, tokend ); };\n\n\t\t\"::\" => { token( TK_NameSep, tokstart, tokend ); };\n\n\t\t# Some symbols need to go to the parser as with their cardinal value as\n\t\t# the token type (as opposed to being sent as anonymous symbols)\n\t\t# because they are part of the sequences which we interpret. The * ) ;\n\t\t# symbols cause whitespace parsing to come back on. This gets turned\n\t\t# off by some keywords.\n\n\t\t\";\" => {\n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t\tif ( inlineBlockType == SemiTerminated )\n\t\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t[*)] => { \n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t};\n\n\t\t[,(] => { token( *tokstart, tokstart, tokend ); };\n\n\t\t'{' => { \n\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\tcurly_count += 1; \n\t\t};\n\n\t\t'}' => { \n\t\t\tif ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {\n\t\t\t\t\/* Inline code block ends. *\/\n\t\t\t\ttoken( '}' );\n\t\t\t\tfgoto parser_def;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/* Either a semi terminated inline block or only the closing\n\t\t\t\t * brace of some inner scope, not the block's closing brace. *\/\n\t\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\t}\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated code block\" << endl;\n\t\t};\n\n\t\t# Send every other character as a symbol.\n\t\tany => { token( IL_Symbol, tokstart, tokend ); };\n\t*|;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( RE_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( RE_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( RE_Char, tokstart, tokend ); };\n\n\t*|;\n\n\tre_literal := |*\n\t\t# Escape sequences in regular expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Terminate an OR expression.\n\t\t'\/' [i]? => { \n\t\t\ttoken( RE_Slash, tokstart, tokend ); \n\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t# Special characters.\n\t\t'.' => { token( RE_Dot ); };\n\t\t'*' => { token( RE_Star ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated regular expression\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\\/] => { token( RE_Char, tokstart, tokend ); };\n\t*|;\n\n\t# We need a separate token space here to avoid the ragel keywords.\n\twrite_statement := |*\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\t\t[ \\t\\n]+ => { updateCol(); };\n\t\t';' => { token( ';' ); fgoto parser_def; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated write statement\" << endl;\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tparser_def := |*\n\t\t'machine' => { token( KW_Machine ); };\n\t\t'include' => { token( KW_Include ); };\n\t\t'write' => { \n\t\t\ttoken( KW_Write );\n\t\t\tfgoto write_statement;\n\t\t};\n\t\t'action' => { token( KW_Action ); };\n\t\t'alphtype' => { token( KW_AlphType ); };\n\n\t\t# FIXME: Enable this post 5.17.\n\t\t# 'range' => { token( KW_Range ); };\n\n\t\t'getkey' => { \n\t\t\ttoken( KW_GetKey );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'access' => { \n\t\t\ttoken( KW_Access );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'variable' => { \n\t\t\ttoken( KW_Variable );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'when' => { token( KW_When ); };\n\t\t'eof' => { token( KW_Eof ); };\n\t\t'err' => { token( KW_Err ); };\n\t\t'lerr' => { token( KW_Lerr ); };\n\t\t'to' => { token( KW_To ); };\n\t\t'from' => { token( KW_From ); };\n\t\t'export' => { token( KW_Export ); };\n\t\t'entry' => { token( KW_Entry ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, tokstart, tokend ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( RE_Slash ); fgoto re_literal; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t':=' => { token( TK_ColonEquals ); };\n\n\t\t# To State Actions.\n\t\t\">~\" => { token( TK_StartToState ); };\n\t\t\"$~\" => { token( TK_AllToState ); };\n\t\t\"%~\" => { token( TK_FinalToState ); };\n\t\t\"<~\" => { token( TK_NotStartToState ); };\n\t\t\"@~\" => { token( TK_NotFinalToState ); };\n\t\t\"<>~\" => { token( TK_MiddleToState ); };\n\n\t\t# From State actions\n\t\t\">*\" => { token( TK_StartFromState ); };\n\t\t\"$*\" => { token( TK_AllFromState ); };\n\t\t\"%*\" => { token( TK_FinalFromState ); };\n\t\t\"<*\" => { token( TK_NotStartFromState ); };\n\t\t\"@*\" => { token( TK_NotFinalFromState ); };\n\t\t\"<>*\" => { token( TK_MiddleFromState ); };\n\n\t\t# EOF Actions.\n\t\t\">\/\" => { token( TK_StartEOF ); };\n\t\t\"$\/\" => { token( TK_AllEOF ); };\n\t\t\"%\/\" => { token( TK_FinalEOF ); };\n\t\t\"<\/\" => { token( TK_NotStartEOF ); };\n\t\t\"@\/\" => { token( TK_NotFinalEOF ); };\n\t\t\"<>\/\" => { token( TK_MiddleEOF ); };\n\n\t\t# Global Error actions.\n\t\t\">!\" => { token( TK_StartGblError ); };\n\t\t\"$!\" => { token( TK_AllGblError ); };\n\t\t\"%!\" => { token( TK_FinalGblError ); };\n\t\t\" { token( TK_NotStartGblError ); };\n\t\t\"@!\" => { token( TK_NotFinalGblError ); };\n\t\t\"<>!\" => { token( TK_MiddleGblError ); };\n\n\t\t# Local error actions.\n\t\t\">^\" => { token( TK_StartLocalError ); };\n\t\t\"$^\" => { token( TK_AllLocalError ); };\n\t\t\"%^\" => { token( TK_FinalLocalError ); };\n\t\t\"<^\" => { token( TK_NotStartLocalError ); };\n\t\t\"@^\" => { token( TK_NotFinalLocalError ); };\n\t\t\"<>^\" => { token( TK_MiddleLocalError ); };\n\n\t\t# Middle.\n\t\t\"<>\" => { token( TK_Middle ); };\n\n\t\t# Conditions. \n\t\t'>?' => { token( TK_StartCond ); };\n\t\t'$?' => { token( TK_AllCond ); };\n\t\t'%?' => { token( TK_LeavingCond ); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\t\t'->' => { token( TK_Arrow ); };\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\n\t\t\":>\" => { token( TK_ColonGt ); };\n\t\t\":>>\" => { token( TK_ColonGtGt ); };\n\t\t\"<:\" => { token( TK_LtColon ); };\n\n\t\t# Opening of longest match.\n\t\t\"|*\" => { token( TK_BarStar ); };\n\n\t\t# Separater for name references.\n\t\t\"::\" => { token( TK_NameSep, tokstart, tokend ); };\n\n\t\t'}%%' => { \n\t\t\tupdateCol();\n\t\t\tendSection();\n\t\t\tfgoto main;\n\t\t};\n\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => {\n\t\t\tupdateCol();\n\t\t\tif ( singleLineSpec ) {\n\t\t\t\tendSection();\n\t\t\t\tfgoto main;\n\t\t\t}\n\t\t};\n\n\t\t'{' => { \n\t\t\tif ( lastToken == KW_Export || lastToken == KW_Entry )\n\t\t\t\ttoken( '{' );\n\t\t\telse {\n\t\t\t\ttoken( '{' );\n\t\t\t\tcurly_count = 1; \n\t\t\t\tinlineBlockType = CurlyDelimited;\n\t\t\t\tfgoto inline_code;\n\t\t\t}\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated ragel section\" << endl;\n\t\t};\n\n\t\tany => { token( *tokstart ); } ;\n\t*|;\n\n\taction pass {\n\t\tupdateCol();\n\n\t\t\/* If no errors and we are at the bottom of the include stack (the\n\t\t * source file listed on the command line) then write out the data. *\/\n\t\tif ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )\n\t\t\txmlEscapeHost( output, tokstart, tokend-tokstart );\n\t}\n\n\t# Outside code scanner. These tokens get passed through.\n\tmain := |*\n\t\tident => pass;\n\t\tnumber => pass;\n\t\tc_cpp_comment => pass;\n\t\ts_literal | d_literal => pass;\n\t\t'%%{' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = false;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\t'%%' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = true;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\twhitespace+ => pass;\n\t\tEOF;\n\t\tany => pass;\n\t*|;\n\n}%%\n\n%% write data;\n\nvoid Scanner::do_scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[1];\n\tint curly_count = 0;\n\tbool execute = true;\n\tbool singleLineSpec = false;\n\tInlineBlockType inlineBlockType;\n\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart = newbuf + ( tokstart - buf );\n\t\t\ttokend = newbuf + ( tokend - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"scanner error\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = tokstart;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart -= shiftback;\n\t\t\ttokend -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\n\tdelete[] buf;\n}\n\nvoid scan( char *fileName, istream &input, ostream &output )\n{\n\tScanner scanner( fileName, input, output, 0, 0, 0 );\n\tscanner.init();\n\tscanner.do_scan();\n\n\tInputLoc eofLoc;\n\teofLoc.fileName = fileName;\n\teofLoc.col = 1;\n\teofLoc.line = scanner.line;\n}\n","old_contents":"\/*\n * Copyright 2006-2007 Adrian Thurston \n *\/\n\n\/* This file is part of Ragel.\n *\n * Ragel is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Ragel is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Ragel; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"ragel.h\"\n#include \"rlparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nextern char *Parser_lelNames[];\n\n\/* This is used for tracking the current stack of include file\/machine pairs. It is\n * is used to detect and recursive include structure. *\/\nstruct IncludeStackItem\n{\n\tIncludeStackItem( char *fileName, char *sectionName )\n\t\t: fileName(fileName), sectionName(sectionName) {}\n\n\tchar *fileName;\n\tchar *sectionName;\n};\n\ntypedef Vector IncludeStack;\n\nenum InlineBlockType\n{\n\tCurlyDelimited,\n\tSemiTerminated\n};\n\nstruct Scanner\n{\n\tScanner( char *fileName, istream &input, ostream &output,\n\t\t\tParser *inclToParser, char *inclSectionTarg,\n\t\t\tint includeDepth )\n\t: \n\t\tfileName(fileName), input(input), output(output),\n\t\tinclToParser(inclToParser),\n\t\tinclSectionTarg(inclSectionTarg),\n\t\tincludeDepth(includeDepth),\n\t\tline(1), column(1), lastnl(0), \n\t\tparser(0), ignoreSection(false), \n\t\tparserExistsError(false),\n\t\twhitespaceOn(true),\n\t\tlastToken(0)\n\t\t{}\n\n\tbool recursiveInclude( char *inclFileName, char *inclSectionName );\n\n\tchar *prepareFileName( char *fileName, int len )\n\t{\n\t\tbool caseInsensitive;\n\t\tToken tokenFnStr, tokenRes;\n\t\ttokenFnStr.data = fileName;\n\t\ttokenFnStr.length = len;\n\t\ttokenFnStr.prepareLitString( tokenRes, caseInsensitive );\n\t\treturn tokenRes.data;\n\t}\n\n\tvoid init();\n\tvoid token( int type, char *start, char *end );\n\tvoid token( int type, char c );\n\tvoid token( int type );\n\tvoid updateCol();\n\tvoid startSection();\n\tvoid endSection();\n\tvoid do_scan();\n\tbool active();\n\tostream &scan_error();\n\n\tchar *fileName;\n\tistream &input;\n\tostream &output;\n\tParser *inclToParser;\n\tchar *inclSectionTarg;\n\tint includeDepth;\n\n\tint cs;\n\tint line;\n\tchar *word, *lit;\n\tint word_len, lit_len;\n\tInputLoc sectionLoc;\n\tchar *tokstart, *tokend;\n\tint column;\n\tchar *lastnl;\n\n\t\/* Set by machine statements, these persist from section to section\n\t * allowing for unnamed sections. *\/\n\tParser *parser;\n\tbool ignoreSection;\n\tIncludeStack includeStack;\n\n\t\/* This is set if ragel has already emitted an error stating that\n\t * no section name has been seen and thus no parser exists. *\/\n\tbool parserExistsError;\n\n\t\/* This is for inline code. By default it is on. It goes off for\n\t * statements and values in inline blocks which are parsed. *\/\n\tbool whitespaceOn;\n\n\t\/* Keeps a record of the previous token sent to the section parser. *\/\n\tint lastToken;\n};\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid Scanner::init( )\n{\n\t%% write init;\n}\n\nbool Scanner::active()\n{\n\tif ( ignoreSection )\n\t\treturn false;\n\n\tif ( parser == 0 && ! parserExistsError ) {\n\t\tscan_error() << \"there is no previous specification name\" << endl;\n\t\tparserExistsError = true;\n\t}\n\n\tif ( parser == 0 )\n\t\treturn false;\n\n\treturn true;\n}\n\nostream &Scanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 &&\n\t\t\t\tstrcmp( si->sectionName, inclSectionName ) == 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\t\n}\n\nvoid Scanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = tokstart;\n\t\/\/cerr << \"adding \" << tokend - from << \" to column\" << endl;\n\tcolumn += tokend - from;\n\tlastnl = 0;\n}\n\nvoid Scanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid Scanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\n%%{\n\tmachine section_parse;\n\n\t# This relies on the the kelbt implementation and the order\n\t# that tokens are declared.\n\tKW_Machine = 128;\n\tKW_Include = 129;\n\tKW_Write = 130;\n\tTK_Word = 131;\n\tTK_Literal = 132;\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_word { word = tokdata; word_len = toklen; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_machine\n\t{\n\t\t\/* Assign a name to the machine. *\/\n\t\tchar *machine = word;\n\n\t\tif ( inclSectionTarg == 0 ) {\n\t\t\tignoreSection = false;\n\n\t\t\tParserDictEl *pdEl = parserDict.find( machine );\n\t\t\tif ( pdEl == 0 ) {\n\t\t\t\tpdEl = new ParserDictEl( machine );\n\t\t\t\tpdEl->value = new Parser( fileName, machine, sectionLoc );\n\t\t\t\tpdEl->value->init();\n\t\t\t\tparserDict.insert( pdEl );\n\t\t\t}\n\n\t\t\tparser = pdEl->value;\n\t\t}\n\t\telse if ( strcmp( inclSectionTarg, machine ) == 0 ) {\n\t\t\t\/* found include target *\/\n\t\t\tignoreSection = false;\n\t\t\tparser = inclToParser;\n\t\t}\n\t\telse {\n\t\t\t\/* ignoring section *\/\n\t\t\tignoreSection = true;\n\t\t\tparser = 0;\n\t\t}\n\t}\n\n\tmachine_stmt =\n\t\t( KW_Machine TK_Word @store_word ';' ) @handle_machine\n\t\t<>err mach_err <>eof mach_err;\n\n\taction handle_include\n\t{\n\t\tif ( active() ) {\n\t\t\tchar *inclSectionName = word;\n\t\t\tchar *inclFileName = 0;\n\n\t\t\t\/* Implement defaults for the input file and section name. *\/\n\t\t\tif ( inclSectionName == 0 )\n\t\t\t\tinclSectionName = parser->sectionName;\n\n\t\t\tif ( lit != 0 ) \n\t\t\t\tinclFileName = prepareFileName( lit, lit_len );\n\t\t\telse\n\t\t\t\tinclFileName = fileName;\n\n\t\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t\t * name then check if what we are including is already in the stack. *\/\n\t\t\tincludeStack.append( IncludeStackItem( fileName, parser->sectionName ) );\n\n\t\t\tif ( recursiveInclude( inclFileName, inclSectionName ) )\n\t\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\t\t\telse {\n\t\t\t\t\/* Open the input file for reading. *\/\n\t\t\t\tifstream *inFile = new ifstream( inclFileName );\n\t\t\t\tif ( ! inFile->is_open() ) {\n\t\t\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\t\t\tinclFileName << \" for reading\" << endl;\n\t\t\t\t}\n\n\t\t\t\tScanner scanner( inclFileName, *inFile, output, parser,\n\t\t\t\t\t\tinclSectionName, includeDepth+1 );\n\t\t\t\tscanner.init();\n\t\t\t\tscanner.do_scan( );\n\t\t\t\tdelete inFile;\n\t\t\t}\n\n\t\t\t\/* Remove the last element (len-1) *\/\n\t\t\tincludeStack.remove( -1 );\n\t\t}\n\t}\n\n\tinclude_names = (\n\t\tTK_Word @store_word ( TK_Literal @store_lit )? |\n\t\tTK_Literal @store_lit\n\t) >clear_words;\n\n\tinclude_stmt =\n\t\t( KW_Include include_names ';' ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction write_command\n\t{\n\t\tif ( active() && machineSpec == 0 && machineName == 0 ) {\n\t\t\toutput << \"sectionName << \"\\\"\"\n\t\t\t\t\t\" line=\\\"\" << line << \"\\\"\"\n\t\t\t\t\t\" col=\\\"\" << column << \"\\\"\"\n\t\t\t\t\t\">\";\n\t\t}\n\t}\n\n\taction write_arg\n\t{\n\t\tif ( active() && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"\" << tokdata << \"<\/arg>\";\n\t}\n\n\taction write_close\n\t{\n\t\tif ( active() && machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/write>\\n\";\n\t}\n\n\twrite_stmt =\n\t\t( KW_Write @write_command \n\t\t( TK_Word @write_arg )+ ';' @write_close )\n\t\t<>err write_err <>eof write_err;\n\n\taction handle_token\n\t{\n\t\t\/* Send the token off to the parser. *\/\n\t\tif ( active() ) {\n\t\t\tInputLoc loc;\n\n\t\t\t#if 0\n\t\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\t\tcerr << \" \" << toklen;\n\t\t\tif ( tokdata != 0 )\n\t\t\t\tcerr << \" \" << tokdata;\n\t\t\tcerr << endl;\n\t\t\t#endif\n\n\t\t\tloc.fileName = fileName;\n\t\t\tloc.line = line;\n\t\t\tloc.col = column;\n\n\t\t\tparser->token( loc, type, tokdata, toklen );\n\t\t}\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;\n\n\tmain := ( \n\t\tmachine_stmt |\n\t\tinclude_stmt |\n\t\twrite_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid Scanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n\n\t\/* Record the last token for use in controlling the scan of subsequent\n\t * tokens. *\/\n\tlastToken = type;\n}\n\nvoid Scanner::startSection( )\n{\n\tparserExistsError = false;\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 )\n\t\t\toutput << \"<\/host>\\n\";\n\t}\n\n\tsectionLoc.fileName = fileName;\n\tsectionLoc.line = line;\n\tsectionLoc.col = 0;\n}\n\nvoid Scanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t%%{\n\t\tmachine section_parse;\n\t\twrite eof;\n\t}%%\n\n\t\/* Close off the section with the parser. *\/\n\tif ( active() ) {\n\t\tInputLoc loc;\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = 0;\n\n\t\tparser->token( loc, TK_EndSection, 0, 0 );\n\t}\n\n\tif ( includeDepth == 0 ) {\n\t\tif ( machineSpec == 0 && machineName == 0 ) {\n\t\t\t\/* The end section may include a newline on the end, so\n\t\t\t * we use the last line, which will count the newline. *\/\n\t\t\toutput << \"\";\n\t\t}\n\t}\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\tc_comment = \n\t\t'\/*' ( any | NL )* :>> '*\/';\n\n\tcpp_comment =\n\t\t'\/\/' [^\\n]* NL;\n\n\tc_cpp_comment = c_comment | cpp_comment;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\t# An inline block of code. This is specified as a scanned, but is sent to\n\t# the parser as one long block. The inline_block pointer is used to handle\n\t# the preservation of the data.\n\tinline_code := |*\n\t\t# Inline expression keywords.\n\t\t\"fpc\" => { token( KW_PChar ); };\n\t\t\"fc\" => { token( KW_Char ); };\n\t\t\"fcurs\" => { token( KW_CurState ); };\n\t\t\"ftargs\" => { token( KW_TargState ); };\n\t\t\"fentry\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Entry );\n\t\t};\n\n\t\t# Inline statement keywords.\n\t\t\"fhold\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Hold );\n\t\t};\n\t\t\"fexec\" => { token( KW_Exec, 0, 0 ); };\n\t\t\"fgoto\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Goto );\n\t\t};\n\t\t\"fnext\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Next );\n\t\t};\n\t\t\"fcall\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Call );\n\t\t};\n\t\t\"fret\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Ret );\n\t\t};\n\t\t\"fbreak\" => { \n\t\t\twhitespaceOn = false; \n\t\t\ttoken( KW_Break );\n\t\t};\n\n\t\tident => { token( TK_Word, tokstart, tokend ); };\n\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t( s_literal | d_literal ) \n\t\t\t=> { token( IL_Literal, tokstart, tokend ); };\n\n\t\twhitespace+ => { \n\t\t\tif ( whitespaceOn ) \n\t\t\t\ttoken( IL_WhiteSpace, tokstart, tokend );\n\t\t};\n\t\tc_cpp_comment => { token( IL_Comment, tokstart, tokend ); };\n\n\t\t\"::\" => { token( TK_NameSep, tokstart, tokend ); };\n\n\t\t# Some symbols need to go to the parser as with their cardinal value as\n\t\t# the token type (as opposed to being sent as anonymous symbols)\n\t\t# because they are part of the sequences which we interpret. The * ) ;\n\t\t# symbols cause whitespace parsing to come back on. This gets turned\n\t\t# off by some keywords.\n\n\t\t\";\" => {\n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t\tif ( inlineBlockType == SemiTerminated )\n\t\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t[*)] => { \n\t\t\twhitespaceOn = true;\n\t\t\ttoken( *tokstart, tokstart, tokend );\n\t\t};\n\n\t\t[,(] => { token( *tokstart, tokstart, tokend ); };\n\n\t\t'{' => { \n\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\tcurly_count += 1; \n\t\t};\n\n\t\t'}' => { \n\t\t\tif ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {\n\t\t\t\t\/* Inline code block ends. *\/\n\t\t\t\ttoken( '}' );\n\t\t\t\tfgoto parser_def;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/* Either a semi terminated inline block or only the closing\n\t\t\t\t * brace of some inner scope, not the block's closing brace. *\/\n\t\t\t\ttoken( IL_Symbol, tokstart, tokend );\n\t\t\t}\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated code block\" << endl;\n\t\t};\n\n\t\t# Send every other character as a symbol.\n\t\tany => { token( IL_Symbol, tokstart, tokend ); };\n\t*|;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( RE_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( RE_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( RE_Char, tokstart, tokend ); };\n\n\t*|;\n\n\tre_literal := |*\n\t\t# Escape sequences in regular expressions.\n\t\t'\\\\0' => { token( RE_Char, '\\0' ); };\n\t\t'\\\\a' => { token( RE_Char, '\\a' ); };\n\t\t'\\\\b' => { token( RE_Char, '\\b' ); };\n\t\t'\\\\t' => { token( RE_Char, '\\t' ); };\n\t\t'\\\\n' => { token( RE_Char, '\\n' ); };\n\t\t'\\\\v' => { token( RE_Char, '\\v' ); };\n\t\t'\\\\f' => { token( RE_Char, '\\f' ); };\n\t\t'\\\\r' => { token( RE_Char, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( RE_Char, tokstart+1, tokend ); };\n\n\t\t# Terminate an OR expression.\n\t\t'\/' [i]? => { \n\t\t\ttoken( RE_Slash, tokstart, tokend ); \n\t\t\tfgoto parser_def;\n\t\t};\n\n\t\t# Special characters.\n\t\t'.' => { token( RE_Dot ); };\n\t\t'*' => { token( RE_Star ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated regular expression\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\\/] => { token( RE_Char, tokstart, tokend ); };\n\t*|;\n\n\t# We need a separate token space here to avoid the ragel keywords.\n\twrite_statement := |*\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\t\t[ \\t\\n]+ => { updateCol(); };\n\t\t';' => { token( ';' ); fgoto parser_def; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated write statement\" << endl;\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tparser_def := |*\n\t\t'machine' => { token( KW_Machine ); };\n\t\t'include' => { token( KW_Include ); };\n\t\t'write' => { \n\t\t\ttoken( KW_Write );\n\t\t\tfgoto write_statement;\n\t\t};\n\t\t'action' => { token( KW_Action ); };\n\t\t'alphtype' => { token( KW_AlphType ); };\n\n\t\t# FIXME: Enable this post 5.17.\n\t\t# 'range' => { token( KW_Range ); };\n\n\t\t'getkey' => { \n\t\t\ttoken( KW_GetKey );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'access' => { \n\t\t\ttoken( KW_Access );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'variable' => { \n\t\t\ttoken( KW_Variable );\n\t\t\tinlineBlockType = SemiTerminated;\n\t\t\tfgoto inline_code;\n\t\t};\n\t\t'when' => { token( KW_When ); };\n\t\t'eof' => { token( KW_Eof ); };\n\t\t'err' => { token( KW_Err ); };\n\t\t'lerr' => { token( KW_Lerr ); };\n\t\t'to' => { token( KW_To ); };\n\t\t'from' => { token( KW_From ); };\n\t\t'export' => { token( KW_Export ); };\n\t\t'entry' => { token( KW_Entry ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, tokstart, tokend ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, tokstart, tokend ); };\n\t\thex_number => { token( TK_Hex, tokstart, tokend ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, tokstart, tokend ); };\n\n\t\t'[' => { token( RE_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( RE_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( RE_Slash ); fgoto re_literal; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t':=' => { token( TK_ColonEquals ); };\n\n\t\t# To State Actions.\n\t\t\">~\" => { token( TK_StartToState ); };\n\t\t\"$~\" => { token( TK_AllToState ); };\n\t\t\"%~\" => { token( TK_FinalToState ); };\n\t\t\"<~\" => { token( TK_NotStartToState ); };\n\t\t\"@~\" => { token( TK_NotFinalToState ); };\n\t\t\"<>~\" => { token( TK_MiddleToState ); };\n\n\t\t# From State actions\n\t\t\">*\" => { token( TK_StartFromState ); };\n\t\t\"$*\" => { token( TK_AllFromState ); };\n\t\t\"%*\" => { token( TK_FinalFromState ); };\n\t\t\"<*\" => { token( TK_NotStartFromState ); };\n\t\t\"@*\" => { token( TK_NotFinalFromState ); };\n\t\t\"<>*\" => { token( TK_MiddleFromState ); };\n\n\t\t# EOF Actions.\n\t\t\">\/\" => { token( TK_StartEOF ); };\n\t\t\"$\/\" => { token( TK_AllEOF ); };\n\t\t\"%\/\" => { token( TK_FinalEOF ); };\n\t\t\"<\/\" => { token( TK_NotStartEOF ); };\n\t\t\"@\/\" => { token( TK_NotFinalEOF ); };\n\t\t\"<>\/\" => { token( TK_MiddleEOF ); };\n\n\t\t# Global Error actions.\n\t\t\">!\" => { token( TK_StartGblError ); };\n\t\t\"$!\" => { token( TK_AllGblError ); };\n\t\t\"%!\" => { token( TK_FinalGblError ); };\n\t\t\" { token( TK_NotStartGblError ); };\n\t\t\"@!\" => { token( TK_NotFinalGblError ); };\n\t\t\"<>!\" => { token( TK_MiddleGblError ); };\n\n\t\t# Local error actions.\n\t\t\">^\" => { token( TK_StartLocalError ); };\n\t\t\"$^\" => { token( TK_AllLocalError ); };\n\t\t\"%^\" => { token( TK_FinalLocalError ); };\n\t\t\"<^\" => { token( TK_NotStartLocalError ); };\n\t\t\"@^\" => { token( TK_NotFinalLocalError ); };\n\t\t\"<>^\" => { token( TK_MiddleLocalError ); };\n\n\t\t# Middle.\n\t\t\"<>\" => { token( TK_Middle ); };\n\n\t\t# Conditions. \n\t\t'>?' => { token( TK_StartCond ); };\n\t\t'$?' => { token( TK_AllCond ); };\n\t\t'%?' => { token( TK_LeavingCond ); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\t\t'->' => { token( TK_Arrow ); };\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\n\t\t\":>\" => { token( TK_ColonGt ); };\n\t\t\":>>\" => { token( TK_ColonGtGt ); };\n\t\t\"<:\" => { token( TK_LtColon ); };\n\n\t\t# Opening of longest match.\n\t\t\"|*\" => { token( TK_BarStar ); };\n\n\t\t'}%%' => { \n\t\t\tupdateCol();\n\t\t\tendSection();\n\t\t\tfgoto main;\n\t\t};\n\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => {\n\t\t\tupdateCol();\n\t\t\tif ( singleLineSpec ) {\n\t\t\t\tendSection();\n\t\t\t\tfgoto main;\n\t\t\t}\n\t\t};\n\n\t\t'{' => { \n\t\t\tif ( lastToken == KW_Export || lastToken == KW_Entry )\n\t\t\t\ttoken( '{' );\n\t\t\telse {\n\t\t\t\ttoken( '{' );\n\t\t\t\tcurly_count = 1; \n\t\t\t\tinlineBlockType = CurlyDelimited;\n\t\t\t\tfgoto inline_code;\n\t\t\t}\n\t\t};\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated ragel section\" << endl;\n\t\t};\n\n\t\tany => { token( *tokstart ); } ;\n\t*|;\n\n\taction pass {\n\t\tupdateCol();\n\n\t\t\/* If no errors and we are at the bottom of the include stack (the\n\t\t * source file listed on the command line) then write out the data. *\/\n\t\tif ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )\n\t\t\txmlEscapeHost( output, tokstart, tokend-tokstart );\n\t}\n\n\t# Outside code scanner. These tokens get passed through.\n\tmain := |*\n\t\tident => pass;\n\t\tnumber => pass;\n\t\tc_cpp_comment => pass;\n\t\ts_literal | d_literal => pass;\n\t\t'%%{' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = false;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\t'%%' => { \n\t\t\tupdateCol();\n\t\t\tsingleLineSpec = true;\n\t\t\tstartSection();\n\t\t\tfgoto parser_def;\n\t\t};\n\t\twhitespace+ => pass;\n\t\tEOF;\n\t\tany => pass;\n\t*|;\n\n}%%\n\n%% write data;\n\nvoid Scanner::do_scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[1];\n\tint curly_count = 0;\n\tbool execute = true;\n\tbool singleLineSpec = false;\n\tInlineBlockType inlineBlockType;\n\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart = newbuf + ( tokstart - buf );\n\t\t\ttokend = newbuf + ( tokend - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"scanner error\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = tokstart;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( tokstart != 0 )\n\t\t\t\ttokstart -= shiftback;\n\t\t\ttokend -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\n\tdelete[] buf;\n}\n\nvoid scan( char *fileName, istream &input, ostream &output )\n{\n\tScanner scanner( fileName, input, output, 0, 0, 0 );\n\tscanner.init();\n\tscanner.do_scan();\n\n\tInputLoc eofLoc;\n\teofLoc.fileName = fileName;\n\teofLoc.col = 1;\n\teofLoc.line = scanner.line;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"b6db3250a503cc44baae7da151d0faa7881df8d2","subject":"Unbreak sctp stream parsing, now sctp works with mplayer-nemesi","message":"Unbreak sctp stream parsing, now sctp works with mplayer-nemesi\n","repos":"winlinvip\/feng,winlinvip\/feng,lscube\/feng,lscube\/feng,winlinvip\/feng,lscube\/feng","old_file":"src\/network\/ragel_transport.rl","new_file":"src\/network\/ragel_transport.rl","new_contents":"\/* -*- c -*- *\/\n\n#include \n\n#include \"network\/rtsp.h\"\n#include \"network\/rtp.h\"\n#include \"network\/ragel_parsers.h\"\n\n%% machine ragel_transport_header;\n\ngboolean ragel_parse_transport_header(RTSP_Client *rtsp,\n RTP_transport *rtp_t,\n const char *header) {\n struct ParsedTransport transport;\n int cs;\n const char *p = header, *pe = p + strlen(p) +1;\n uint32_t portval; uint16_t chanval;\n\n %%{\n action start_port {\n portval = 0;\n }\n\n action count_port {\n portval = (portval*10) + (fc - '0');\n }\n\n action check_port {\n if ( portval > G_MAXUINT16 )\n portval = G_MAXUINT16;\n }\n\n action start_channel {\n chanval = 0;\n }\n\n action count_channel {\n chanval = (chanval*10) + (fc - '0');\n }\n\n action check_channel {\n if ( chanval > G_MAXUINT8 )\n chanval = G_MAXUINT8;\n }\n\n Port = digit{,5} >start_port @count_port %check_port;\n Channel = digit{,3} >start_channel @count_channel %check_channel;\n\n Unicast = \";unicast\" %{transport.mode = TransportUnicast;};\n Multicast = \";multicast\" %{transport.mode = TransportMulticast;};\n\n TransportParamName = ( alnum | '_' )+;\n TransportParamValue = (print - ('=' | ';' ))+;\n\n TransportParam = \";\" . TransportParamName . ( '=' . TransportParamValue )?;\n\n ClientPort = \";client_port=\" .\n Port%{transport.parameters.UDP.Unicast.port_rtp = portval;} .\n ( \"-\" . Port%{transport.parameters.UDP.Unicast.port_rtcp = portval;} );\n\n UnicastUDPParams = Unicast . ( ClientPort | TransportParam )+;\n MulticastUDPParams = Multicast . TransportParam+;\n\n UDPParams = ( UnicastUDPParams | MulticastUDPParams );\n\n Interleaved = \";interleaved=\" .\n Channel%{transport.parameters.TCP.ich_rtp = chanval;} .\n ( \"-\" . Channel%{transport.parameters.TCP.ich_rtcp = chanval;} );\n\n TCPParams = ( Interleaved | TransportParam)+;\n\n Streams = \";streams=\" .\n Channel%{transport.parameters.SCTP.ch_rtp = chanval;} .\n ( \"-\" . Channel%{transport.parameters.SCTP.ch_rtcp = chanval;} );\n\n SCTPParams = ( Streams | TransportParam)+;\n\n TransportUDP = (\"\/UDP\")? %{transport.protocol = TransportUDP; }\n . UDPParams;\n TransportTCP = \"\/TCP\" %{transport.protocol = TransportTCP; }\n . TCPParams;\n TransportSCTP = \"\/SCTP\" %{transport.protocol = TransportSCTP; }\n . SCTPParams;\n\n action check_transport {\n \/* If the transport is valid, our work is done *\/\n if ( check_parsed_transport(rtsp, rtp_t, &transport) )\n return true;\n }\n\n TransportSpec = \"RTP\/AVP\" . ( TransportUDP|TransportTCP|TransportSCTP )\n > { memset(&transport, 0, sizeof(transport)); }\n % check_transport;\n\n main := TransportSpec . ( ',' . TransportSpec )* . 0;\n\n write data;\n write init;\n write exec;\n }%%\n\n return false;\n}\n","old_contents":"\/* -*- c -*- *\/\n\n#include \n\n#include \"network\/rtsp.h\"\n#include \"network\/rtp.h\"\n#include \"network\/ragel_parsers.h\"\n\n%% machine ragel_transport_header;\n\ngboolean ragel_parse_transport_header(RTSP_Client *rtsp,\n RTP_transport *rtp_t,\n const char *header) {\n struct ParsedTransport transport;\n int cs;\n const char *p = header, *pe = p + strlen(p) +1;\n uint32_t portval; uint16_t chanval;\n\n %%{\n action start_port {\n portval = 0;\n }\n\n action count_port {\n portval = (portval*10) + (fc - '0');\n }\n\n action check_port {\n if ( portval > G_MAXUINT16 )\n portval = G_MAXUINT16;\n }\n\n action start_channel {\n chanval = 0;\n }\n\n action count_channel {\n chanval = (chanval*10) + (fc - '0');\n }\n\n action check_channel {\n if ( chanval > G_MAXUINT8 )\n chanval = G_MAXUINT8;\n }\n\n Port = digit{,5} >start_port @count_port %check_port;\n Channel = digit{,3} >start_channel @count_channel %check_channel;\n\n Unicast = \";unicast\" %{transport.mode = TransportUnicast;};\n Multicast = \";multicast\" %{transport.mode = TransportMulticast;};\n\n TransportParamName = ( alnum | '_' )+;\n TransportParamValue = (print - ('=' | ';' ))+;\n\n TransportParam = \";\" . TransportParamName . ( '=' . TransportParamValue )?;\n\n ClientPort = \";client_port=\" .\n Port%{transport.parameters.UDP.Unicast.port_rtp = portval;} .\n ( \"-\" . Port%{transport.parameters.UDP.Unicast.port_rtcp = portval;} );\n\n UnicastUDPParams = Unicast . ( ClientPort | TransportParam )+;\n MulticastUDPParams = Multicast . TransportParam+;\n\n UDPParams = ( UnicastUDPParams | MulticastUDPParams );\n\n Interleaved = \";interleaved=\" .\n Channel%{transport.parameters.TCP.ich_rtp = chanval;} .\n ( \"-\" . Channel%{transport.parameters.TCP.ich_rtcp = chanval;} );\n\n TCPParams = ( Interleaved | TransportParam)+;\n\n Streams = \";streams\" .\n Channel%{transport.parameters.SCTP.ch_rtp = chanval;} .\n ( \"-\" . Channel%{transport.parameters.SCTP.ch_rtcp = chanval;} );\n\n SCTPParams = TransportParam+;\n\n TransportUDP = (\"\/UDP\")? %{transport.protocol = TransportUDP; }\n . UDPParams;\n TransportTCP = \"\/TCP\" %{transport.protocol = TransportTCP; }\n . TCPParams;\n TransportSCTP = \"\/SCTP\" %{transport.protocol = TransportSCTP; }\n . SCTPParams;\n\n action check_transport {\n \/* If the transport is valid, our work is done *\/\n if ( check_parsed_transport(rtsp, rtp_t, &transport) )\n return true;\n }\n\n TransportSpec = \"RTP\/AVP\" . ( TransportUDP|TransportTCP|TransportSCTP )\n > { memset(&transport, 0, sizeof(transport)); }\n % check_transport;\n\n main := TransportSpec . ( ',' . TransportSpec )* . 0;\n\n write data;\n write init;\n write exec;\n }%%\n\n return false;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"edab3a4052ae6a2c47ace80e2c0e759bf7290c04","subject":"updated expected output in rlscan test since adding more input","message":"updated expected output in rlscan test since adding more input\n","repos":"timoc\/ragel,timoc\/ragel,timoc\/ragel,timoc\/ragel","old_file":"test\/rlscan.rl","new_file":"test\/rlscan.rl","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"34df7cef46fd04175ff7c69f142b505a02b8d7a4","subject":"remove some debugging code","message":"remove some debugging code\n","repos":"jneen\/tnetstrings-ruby,jneen\/tnetstrings-ruby","old_file":"ext\/tnetstrings.c.rl","new_file":"ext\/tnetstrings.c.rl","new_contents":"#include \n#include \n#include \n#include \n#include \"tnetstrings.h\"\n\nstatic VALUE eTnetsParserError;\n\n%%{\n machine tnetstrings;\n access parser->;\n\n action mark_ends {\n \/\/ this marks the start of the payload -\n \/\/ move ahead 2 for the colon and the type spec.\n parser->payload = p + 2;\n\n \/\/ this is a bit hacky, but I think it's the only way to do it.\n \/\/ only now do we know where the end is, since we've parsed the payload_size.\n \/\/ This will cause EOF actions to be triggered at the end of the payload.\n \/\/ TODO: eventually, have an option to read this from a stream,\n \/\/ which is arguably the whole point.\n eof = pe = parser->payload + parser->payload_size;\n\n if (pe - str > size) {\n TNETS_ERROR(\"Oops I almost accidentally the buffer.\");\n }\n }\n\n action collect_payload_size {\n parser->payload_size *= 10;\n parser->payload_size += CTOI(fc);\n }\n\n # -*- boolean (!) -*- #\n action wrap_true { parser->result = TNETS_WRAP_TRUE; }\n action wrap_false { parser->result = TNETS_WRAP_FALSE; }\n\n # -*- null (~) -*- #\n action wrap_null { parser->result = Qnil; }\n\n # -*- number (#) -*- #\n action neg {\n parser->seen_neg = 1;\n }\n\n action collect_num {\n parser->num_builder *= 10;\n parser->num_builder += CTOI(fc);\n }\n\n action wrap_num {\n if (parser->seen_neg) parser->num_builder *= -1;\n parser->result = TNETS_WRAP_NUM(parser->num_builder);\n }\n\n # -*- string (,) -*- #\n action wrap_str {\n parser->result = TNETS_WRAP_STR(p+1, parser->payload_size);\n }\n\n action wrap_dict_key {\n parser->result = TNETS_WRAP_DICT_KEY(p+1, parser->payload_size);\n }\n\n action parse_dict {\n TNETS_T dict = TNETS_NEW_DICT;\n TNETS_T key;\n tnets_parser* sub_parser = tnets_parser_new();\n char* sub_data = parser->payload;\n int sub_size = parser->payload_size;\n\n \/\/ TODO: seriously DRY this up, if only with #defines\n while(sub_size > 0) {\n \/\/ XXX HACK. Ask the ragel guys for a better way to do this.\n \/\/ This sets the \"current state\" to the entry point for the\n \/\/ dict_key machine, which only accepts strings.\n sub_parser->cs = tnetstrings_en_dict_key;\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n key = sub_parser->result;\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n tnets_parser_clear(sub_parser);\n\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n TNETS_DICT_ADD(dict, key, sub_parser->result);\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n tnets_parser_clear(sub_parser);\n }\n\n free(sub_parser);\n\n parser->result = dict;\n }\n\n action parse_arr {\n TNETS_T arr = TNETS_NEW_ARR;\n tnets_parser* sub_parser = tnets_parser_new();\n char* sub_data = parser->payload;\n int sub_size = parser->payload_size;\n while (sub_size > 0) {\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n TNETS_ARR_PUSH(arr, sub_parser->result);\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n \/\/ reset current state and such\n tnets_parser_clear(sub_parser);\n }\n free(sub_parser);\n\n parser->result = arr;\n }\n\n action error {\n TNETS_ERROR(\"parse error\"); \/\/ TODO: more helpful messages\n }\n\n # kind of a hack, but represents the end of the chunk.\n end = (any @error)?;\n\n # parses the size spec at the start of the payload\n tnets_size = digit+ $collect_payload_size;\n colon = ':' @mark_ends;\n\n # primitives\n tnets_num = '#' (('-' @neg)? (digit+ $collect_num)) %\/wrap_num <: end;\n tnets_str = ',' @wrap_str;\n tnets_dict_key = ',' @wrap_dict_key;\n # NB: any string that is not \"true\" will return \"false\".\n tnets_bool = '!' ('true' %\/wrap_true | !'true' %\/wrap_false);\n tnets_null = ('~' %\/wrap_null) end;\n\n # recursive structures\n tnets_dict = '}' @parse_dict;\n tnets_arr = ']' @parse_arr;\n\n main := (\n tnets_size colon (\n tnets_dict |\n tnets_arr |\n tnets_num |\n tnets_str |\n tnets_bool |\n tnets_null\n )\n ) @err(error);\n\n dict_key := (tnets_size colon tnets_dict_key) @err(error);\n}%%\n\n%% write data;\n\nint tnets_parser_init(tnets_parser *parser) {\n %% write init;\n}\n\nint tnets_parser_clear(tnets_parser *parser) {\n tnets_parser_init(parser);\n parser->num_builder = 0;\n parser->seen_neg = 0;\n parser->result = TNETS_WRAP_NULL;\n parser->payload = NULL;\n parser->payload_size = 0;\n}\n\nint tnets_parser_chunk(tnets_parser *parser, char *str, int size) {\n char *p = str;\n \/\/ pe gets re-set once we've parsed the length.\n \/\/ set to 10 characters here because that's the maximum\n \/\/ length of the length spec. Also add one for the colon.\n char *pe = p + ( (size < 11) ? size : 11 );\n char *eof = pe;\n\n %% write exec;\n\n return 0;\n}\n\ntnets_parser *tnets_parser_new(void) {\n tnets_parser *parser = calloc(sizeof(tnets_parser), 1);\n tnets_parser_init(parser);\n return parser;\n}\n\ntnets_parser *parse_str(char *str, int size) {\n tnets_parser *parser = tnets_parser_new();\n tnets_parser_chunk(parser, str, size);\n return parser;\n}\n\nVALUE rb_parse_tnets(VALUE self, VALUE rbstr) {\n char *tnets = RSTRING_PTR(rbstr);\n int len = RSTRING_LEN(rbstr);\n\n tnets_parser *parser = parse_str(RSTRING_PTR(rbstr), len);\n\n VALUE result = parser->result;\n free(parser);\n\n return result;\n}\n\nvoid Init_tnetstrings() {\n VALUE mTnetstrings = rb_define_module(\"TNETS\");\n\n rb_define_method(mTnetstrings, \"c_parse\", rb_parse_tnets, 1);\n eTnetsParserError = rb_define_class_under(mTnetstrings, \"ParserError\", rb_eIOError);\n}\n","old_contents":"#include \n#include \n#include \n#include \n#include \"tnetstrings.h\"\n\nstatic VALUE eTnetsParserError;\n\n%%{\n machine tnetstrings;\n access parser->;\n\n action mark_ends {\n \/\/ this marks the start of the payload -\n \/\/ move ahead 2 for the colon and the type spec.\n parser->payload = p + 2;\n\n \/\/ this is a bit hacky, but I think it's the only way to do it.\n \/\/ only now do we know where the end is, since we've parsed the payload_size.\n \/\/ This will cause EOF actions to be triggered at the end of the payload.\n \/\/ TODO: eventually, have an option to read this from a stream,\n \/\/ which is arguably the whole point.\n eof = pe = parser->payload + parser->payload_size;\n\n if (pe - str > size) {\n TNETS_ERROR(\"Oops I almost accidentally the buffer.\");\n }\n }\n\n action collect_payload_size {\n parser->payload_size *= 10;\n parser->payload_size += CTOI(fc);\n }\n\n # -*- boolean (!) -*- #\n action wrap_true { parser->result = TNETS_WRAP_TRUE; }\n action wrap_false { parser->result = TNETS_WRAP_FALSE; }\n\n # -*- null (~) -*- #\n action wrap_null { parser->result = Qnil; }\n\n # -*- number (#) -*- #\n action neg {\n parser->seen_neg = 1;\n }\n\n action collect_num {\n parser->num_builder *= 10;\n parser->num_builder += CTOI(fc);\n }\n\n action wrap_num {\n if (parser->seen_neg) parser->num_builder *= -1;\n parser->result = TNETS_WRAP_NUM(parser->num_builder);\n }\n\n # -*- string (,) -*- #\n action wrap_str {\n parser->result = TNETS_WRAP_STR(p+1, parser->payload_size);\n }\n\n action wrap_dict_key {\n parser->result = TNETS_WRAP_DICT_KEY(p+1, parser->payload_size);\n }\n\n action parse_dict {\n TNETS_T dict = TNETS_NEW_DICT;\n TNETS_T key;\n tnets_parser* sub_parser = tnets_parser_new();\n char* sub_data = parser->payload;\n int sub_size = parser->payload_size;\n\n \/\/ TODO: seriously DRY this up, if only with #defines\n while(sub_size > 0) {\n \/\/ XXX HACK. Ask the ragel guys for a better way to do this.\n \/\/ This sets the \"current state\" to the entry point for the\n \/\/ dict_key machine, which only accepts strings.\n sub_parser->cs = tnetstrings_en_dict_key;\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n key = sub_parser->result;\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n tnets_parser_clear(sub_parser);\n\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n TNETS_DICT_ADD(dict, key, sub_parser->result);\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n tnets_parser_clear(sub_parser);\n }\n\n free(sub_parser);\n\n parser->result = dict;\n }\n\n action parse_arr {\n TNETS_T arr = TNETS_NEW_ARR;\n tnets_parser* sub_parser = tnets_parser_new();\n char* sub_data = parser->payload;\n int sub_size = parser->payload_size;\n while (sub_size > 0) {\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n TNETS_ARR_PUSH(arr, sub_parser->result);\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n \/\/ reset current state and such\n tnets_parser_clear(sub_parser);\n }\n free(sub_parser);\n\n parser->result = arr;\n }\n\n action error {\n printf(\"error!\\n\");\n printf(\"p: [%s]\\n\", p);\n printf(\"pe: [%s]\\n\", pe);\n printf(\"str: [%s]\\n\", str);\n TNETS_ERROR(\"parse error\"); \/\/ TODO: more helpful messages\n }\n\n # kind of a hack, but represents the end of the chunk.\n end = (any @error)?;\n\n # parses the size spec at the start of the payload\n tnets_size = digit+ $collect_payload_size;\n colon = ':' @mark_ends;\n\n # primitives\n tnets_num = '#' (('-' @neg)? (digit+ $collect_num)) %\/wrap_num <: end;\n tnets_str = ',' @wrap_str;\n tnets_dict_key = ',' @wrap_dict_key;\n # NB: any string that is not \"true\" will return \"false\".\n tnets_bool = '!' ('true' %\/wrap_true | !'true' %\/wrap_false);\n tnets_null = ('~' %\/wrap_null) end;\n\n # recursive structures\n tnets_dict = '}' @parse_dict;\n tnets_arr = ']' @parse_arr;\n\n main := (\n tnets_size colon (\n tnets_dict |\n tnets_arr |\n tnets_num |\n tnets_str |\n tnets_bool |\n tnets_null\n )\n ) @err(error);\n\n dict_key := (tnets_size colon tnets_dict_key) @err(error);\n}%%\n\n%% write data;\n\nint tnets_parser_init(tnets_parser *parser) {\n %% write init;\n}\n\nint tnets_parser_clear(tnets_parser *parser) {\n tnets_parser_init(parser);\n parser->num_builder = 0;\n parser->seen_neg = 0;\n parser->result = TNETS_WRAP_NULL;\n parser->payload = NULL;\n parser->payload_size = 0;\n}\n\nint tnets_parser_chunk(tnets_parser *parser, char *str, int size) {\n char *p = str;\n \/\/ pe gets re-set once we've parsed the length.\n \/\/ set to 10 characters here because that's the maximum\n \/\/ length of the length spec. Also add one for the colon.\n char *pe = p + ( (size < 11) ? size : 11 );\n char *eof = pe;\n\n %% write exec;\n\n return 0;\n}\n\ntnets_parser *tnets_parser_new(void) {\n tnets_parser *parser = calloc(sizeof(tnets_parser), 1);\n tnets_parser_init(parser);\n return parser;\n}\n\ntnets_parser *parse_str(char *str, int size) {\n tnets_parser *parser = tnets_parser_new();\n tnets_parser_chunk(parser, str, size);\n return parser;\n}\n\nVALUE rb_parse_tnets(VALUE self, VALUE rbstr) {\n char *tnets = RSTRING_PTR(rbstr);\n int len = RSTRING_LEN(rbstr);\n\n tnets_parser *parser = parse_str(RSTRING_PTR(rbstr), len);\n\n VALUE result = parser->result;\n free(parser);\n\n return result;\n}\n\nvoid Init_tnetstrings() {\n VALUE mTnetstrings = rb_define_module(\"TNETS\");\n\n rb_define_method(mTnetstrings, \"c_parse\", rb_parse_tnets, 1);\n eTnetsParserError = rb_define_class_under(mTnetstrings, \"ParserError\", rb_eIOError);\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"3ef87c1f26654a43ee7fa8cb771505bc3006df7b","subject":"ifchd: Make the command parser much more strict. It now has a concept of argument types and command types.","message":"ifchd: Make the command parser much more strict. It now has a concept of\nargument types and command types.\n","repos":"niklata\/ndhc","old_file":"ifchd\/ifchd-parse.rl","new_file":"ifchd\/ifchd-parse.rl","new_contents":"\/* ifchd-parse.rl - interface change daemon parser\n *\n * Copyright (c) 2004-2013 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"ifchd-defines.h\"\n#include \"log.h\"\n#include \"ifch_proto.h\"\n#include \"strl.h\"\n#include \"linux.h\"\n\n%%{\n machine ifchd_parser;\n\n action Reset { cl->state = STATE_NOTHING; }\n action ArgSt { arg_start = p; }\n action ArgEn {\n arg_len = p - arg_start;\n if (arg_len > sizeof tb - 1) {\n log_line(\"command argument would overflow\");\n return -1;\n }\n memcpy(tb, arg_start, arg_len);\n tb[arg_len] = 0;\n }\n\n action Dispatch {\n switch (cl->state) {\n case STATE_INTERFACE: perform_interface(cl, tb, arg_len); break;\n case STATE_IP: perform_ip(cl, tb, arg_len); break;\n case STATE_SUBNET: perform_subnet(cl, tb, arg_len); break;\n case STATE_TIMEZONE: perform_timezone(cl, tb, arg_len); break;\n case STATE_ROUTER: perform_router(cl, tb, arg_len); break;\n case STATE_DNS: perform_dns(cl, tb, arg_len); break;\n case STATE_LPRSVR: perform_lprsvr(cl, tb, arg_len); break;\n case STATE_HOSTNAME: perform_hostname(cl, tb, arg_len); break;\n case STATE_DOMAIN: perform_domain(cl, tb, arg_len); break;\n case STATE_IPTTL: perform_ipttl(cl, tb, arg_len); break;\n case STATE_MTU: perform_mtu(cl, tb, arg_len); break;\n case STATE_BROADCAST: perform_broadcast(cl, tb, arg_len); break;\n case STATE_NTPSVR: perform_ntpsrv(cl, tb, arg_len); break;\n case STATE_WINS: perform_wins(cl, tb, arg_len); break;\n default:\n log_line(\"error: invalid state in dispatch_work\");\n return -1;\n }\n }\n\n terminator = ';' > Dispatch;\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip_arg = (v4addr > ArgSt % ArgEn) terminator;\n iplist_arg = (((v4addr ',')* v4addr) > ArgSt % ArgEn) terminator;\n str_arg = ([^;\\0]+ > ArgSt % ArgEn) terminator;\n s32_arg = (extend{4} > ArgSt % ArgEn) terminator;\n u16_arg = (extend{2} > ArgSt % ArgEn) terminator;\n u8_arg = (extend{1} > ArgSt % ArgEn) terminator;\n\n cmd_ip = ('ip:' % { cl->state = STATE_IP; }\n |'snet:' % { cl->state = STATE_SUBNET; }\n |'routr:' % { cl->state = STATE_ROUTER; }\n |'bcast:' % { cl->state = STATE_BROADCAST; }\n ) ip_arg;\n cmd_iplist = ('dns:' % { cl->state = STATE_DNS; }\n |'lpr:' % { cl->state = STATE_LPRSVR; }\n |'ntp:' % { cl->state = STATE_NTPSVR; }\n |'wins:' % { cl->state = STATE_WINS; }\n ) iplist_arg;\n cmd_str = ('iface:' % { cl->state = STATE_INTERFACE; }\n |'host:' % { cl->state = STATE_HOSTNAME; }\n |'dom:' % { cl->state = STATE_DOMAIN; }\n ) str_arg;\n cmd_s32 = ('tzone:' % { cl->state = STATE_TIMEZONE; }) s32_arg;\n cmd_u16 = ('mtu:' % { cl->state = STATE_MTU; }) u16_arg;\n cmd_u8 = ('ipttl:' % { cl->state = STATE_IPTTL; }) u8_arg;\n\n command = (cmd_ip|cmd_iplist|cmd_str|cmd_s32|cmd_u16|cmd_u8);\n main := (command > Reset)+;\n}%%\n\n%% write data;\n\n\/*\n * Returns -1 on fatal error; that leads to peer connection being closed.\n *\/\nint execute_buffer(struct ifchd_client *cl, char *newbuf)\n{\n char buf[MAX_BUF * 2];\n char tb[MAX_BUF];\n\n if (strnkcpy(buf, cl->ibuf, sizeof buf))\n goto buftooshort;\n if (strnkcat(buf, newbuf, sizeof buf)) {\nbuftooshort:\n log_line(\"error: input is too long for buffer\");\n return -1;\n }\n\n size_t init_siz = strlen(buf);\n const char *p = buf;\n const char *pe = p + init_siz;\n const char *arg_start;\n size_t arg_len;\n unsigned int cs = 0;\n\n %% write init;\n %% write exec;\n\n size_t bytes_left = pe - p;\n if (bytes_left > 0) {\n size_t taken = init_siz - bytes_left;\n strnkcpy(cl->ibuf, buf + taken, MAX_BUF);\n }\n\n if (cs < ifchd_parser_first_final) {\n log_line(\"error: received invalid commands\");\n return -1;\n }\n log_line(\"Commands received and successfully executed.\");\n return 0;\n}\n\n","old_contents":"\/* ifchd-parse.rl - interface change daemon parser\n *\n * Copyright (c) 2004-2013 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"ifchd-defines.h\"\n#include \"log.h\"\n#include \"ifch_proto.h\"\n#include \"strl.h\"\n#include \"linux.h\"\n\n%%{\n machine ifchd_parser;\n\n action Reset { cl->state = STATE_NOTHING; }\n action ArgSt { arg_start = p; }\n action ArgEn {\n arg_len = p - arg_start;\n if (arg_len > sizeof tb - 1) {\n log_line(\"command argument would overflow\");\n return -1;\n }\n memcpy(tb, arg_start, arg_len);\n tb[arg_len] = 0;\n }\n\n action Dispatch {\n switch (cl->state) {\n case STATE_INTERFACE: perform_interface(cl, tb, arg_len); break;\n case STATE_IP: perform_ip(cl, tb, arg_len); break;\n case STATE_SUBNET: perform_subnet(cl, tb, arg_len); break;\n case STATE_TIMEZONE: perform_timezone(cl, tb, arg_len); break;\n case STATE_ROUTER: perform_router(cl, tb, arg_len); break;\n case STATE_DNS: perform_dns(cl, tb, arg_len); break;\n case STATE_LPRSVR: perform_lprsvr(cl, tb, arg_len); break;\n case STATE_HOSTNAME: perform_hostname(cl, tb, arg_len); break;\n case STATE_DOMAIN: perform_domain(cl, tb, arg_len); break;\n case STATE_IPTTL: perform_ipttl(cl, tb, arg_len); break;\n case STATE_MTU: perform_mtu(cl, tb, arg_len); break;\n case STATE_BROADCAST: perform_broadcast(cl, tb, arg_len); break;\n case STATE_NTPSVR: perform_ntpsrv(cl, tb, arg_len); break;\n case STATE_WINS: perform_wins(cl, tb, arg_len); break;\n default:\n log_line(\"error: invalid state in dispatch_work\");\n return -1;\n }\n }\n\n interface = 'iface';\n ip = 'ip';\n subnet = 'snet';\n dns = 'dns';\n lprsvr = 'lpr';\n ntpsvr = 'ntp';\n wins = 'wins';\n router = 'routr';\n broadcast = 'bcast';\n timezone = 'tzone';\n hostname = 'host';\n domain = 'dom';\n ipttl = 'ipttl';\n mtu = 'mtu';\n\n cmdname = (interface % { cl->state = STATE_INTERFACE; }\n |ip % { cl->state = STATE_IP; }\n |subnet % { cl->state = STATE_SUBNET; }\n |dns % { cl->state = STATE_DNS; }\n |lprsvr % { cl->state = STATE_LPRSVR; }\n |ntpsvr % { cl->state = STATE_NTPSVR; }\n |wins % { cl->state = STATE_WINS; }\n |router % { cl->state = STATE_ROUTER; }\n |broadcast % { cl->state = STATE_BROADCAST; }\n |timezone % { cl->state = STATE_TIMEZONE; }\n |hostname % { cl->state = STATE_HOSTNAME; }\n |domain % { cl->state = STATE_DOMAIN; }\n |ipttl % { cl->state = STATE_IPTTL; }\n |mtu % { cl->state = STATE_MTU; }\n );\n\n command = cmdname ':' ([^;\\0]+ > ArgSt % ArgEn) (';' > Dispatch);\n main := (command > Reset)+;\n}%%\n\n%% write data;\n\n\/*\n * Returns -1 on fatal error; that leads to peer connection being closed.\n *\/\nint execute_buffer(struct ifchd_client *cl, char *newbuf)\n{\n char buf[MAX_BUF * 2];\n char tb[MAX_BUF];\n\n if (strnkcpy(buf, cl->ibuf, sizeof buf))\n goto buftooshort;\n if (strnkcat(buf, newbuf, sizeof buf)) {\nbuftooshort:\n log_line(\"error: input is too long for buffer\");\n return -1;\n }\n\n size_t init_siz = strlen(buf);\n const char *p = buf;\n const char *pe = p + init_siz;\n const char *arg_start;\n size_t arg_len;\n unsigned int cs = 0;\n\n %% write init;\n %% write exec;\n\n size_t bytes_left = pe - p;\n if (bytes_left > 0) {\n size_t taken = init_siz - bytes_left;\n strnkcpy(cl->ibuf, buf + taken, MAX_BUF);\n }\n\n if (cs < ifchd_parser_first_final) {\n log_line(\"error: received invalid commands\");\n return -1;\n }\n log_line(\"Commands received and successfully executed.\");\n return 0;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"d2f2ee4715a686fa7222812883062b4746e4ee09","subject":"Fix memory leak in JSONPath lexer","message":"Fix memory leak in JSONPath lexer\n","repos":"xguerin\/ace,xguerin\/ace,xguerin\/ace,xguerin\/ace","old_file":"libace\/tree\/Lexer.rl","new_file":"libace\/tree\/Lexer.rl","new_contents":"\/**\n * Copyright (c) 2016 Xavier R. Guerin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this\n * software and associated documentation files (the \"Software\"), to deal in the Software\n * without restriction, including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons\n * to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or\n * substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NEVER(__arg__) __arg__\n#include \"Parser.c\"\n\nnamespace {\n\nToken *\ngetIndex(const char * const beg, const char * const end) {\n size_t result = 0;\n std::istringstream(std::string(beg).substr(0, end-beg)) >> result;\n return new IndexToken { result };\n}\n\nToken *\ngetMember(const char * const beg, const char * const end) {\n return new MemberToken { std::string(beg).substr(0, end-beg) };\n}\n\n} \/\/ namespace\n\n%%{\n\nmachine JSONPath;\n\naction groot_tok {\n Parse(lparser, GROOT, 0, nullptr);\n}\n\naction lroot_tok {\n Parse(lparser, LROOT, 0, nullptr);\n}\n\naction dot_tok {\n Parse(lparser, DOT, 0, nullptr);\n}\n\naction openc_tok {\n Parse(lparser, OPENC, 0, nullptr);\n}\n\naction closec_tok {\n Parse(lparser, CLOSEC, 0, nullptr);\n}\n\naction slice_tok {\n Parse(lparser, SLICE, 0, nullptr);\n}\n\naction wildcard_tok {\n Parse(lparser, WILDCARD, 0, nullptr);\n}\n\naction index_tok { \n Parse(lparser, INDEX, getIndex(ts, te), nullptr);\n}\n\naction comma_tok { \n Parse(lparser, COMMA, 0, nullptr);\n}\n\naction member_tok { \n Parse(lparser, MEMBER, getMember(ts, te), nullptr);\n}\n\ngroot = '$';\nlroot = '@';\ndot = '.';\nopenc = '[';\nclosec = ']';\nslice = ':';\nwildcard = '*';\nindex = [0-9]+;\ncomma = ',';\nmember = [a-zA-Z_\\-][a-zA-Z0-9_\\-]*;\n\nmain := |*\n groot => groot_tok;\n lroot => lroot_tok;\n dot => dot_tok;\n openc => openc_tok;\n closec => closec_tok;\n slice => slice_tok;\n wildcard => wildcard_tok;\n index => index_tok;\n comma => comma_tok;\n member => member_tok;\n*|;\n\n}%%\n\n%% write data;\n\nnamespace ace {\nnamespace tree {\nnamespace path {\n\nScan::Scan()\n : cs(0)\n , act(0)\n , ts(0)\n , te(0)\n , lparser(0) {\n lparser = ParseAlloc(malloc);\n %% write init;\n}\n\nScan::~Scan() {\n ParseFree(lparser, free);\n}\n\nPath\nScan::parse(std::string const & str) {\n const char* p = str.c_str();\n const char* pe = str.c_str() + str.length();\n const char* eof = pe;\n %% write exec;\n ace::tree::Path * path = nullptr;\n Parse(lparser, 0, 0, &path);\n if (path == nullptr) throw std::invalid_argument(str);\n ace::tree::Path result(*path);\n delete path;\n return result;\n}\n\n} \/\/ namespace path\n} \/\/ namespace tree\n} \/\/ namespace ace\n\n","old_contents":"\/**\n * Copyright (c) 2016 Xavier R. Guerin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this\n * software and associated documentation files (the \"Software\"), to deal in the Software\n * without restriction, including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons\n * to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or\n * substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NEVER(__arg__) __arg__\n#include \"Parser.c\"\n\nnamespace {\n\nToken *\ngetIndex(const char * const beg, const char * const end) {\n size_t result = 0;\n std::istringstream(std::string(beg).substr(0, end-beg)) >> result;\n return new IndexToken { result };\n}\n\nToken *\ngetMember(const char * const beg, const char * const end) {\n return new MemberToken { std::string(beg).substr(0, end-beg) };\n}\n\n} \/\/ namespace\n\n%%{\n\nmachine JSONPath;\n\naction groot_tok {\n Parse(lparser, GROOT, 0, nullptr);\n}\n\naction lroot_tok {\n Parse(lparser, LROOT, 0, nullptr);\n}\n\naction dot_tok {\n Parse(lparser, DOT, 0, nullptr);\n}\n\naction openc_tok {\n Parse(lparser, OPENC, 0, nullptr);\n}\n\naction closec_tok {\n Parse(lparser, CLOSEC, 0, nullptr);\n}\n\naction slice_tok {\n Parse(lparser, SLICE, 0, nullptr);\n}\n\naction wildcard_tok {\n Parse(lparser, WILDCARD, 0, nullptr);\n}\n\naction index_tok { \n Parse(lparser, INDEX, getIndex(ts, te), nullptr);\n}\n\naction comma_tok { \n Parse(lparser, COMMA, 0, nullptr);\n}\n\naction member_tok { \n Parse(lparser, MEMBER, getMember(ts, te), nullptr);\n}\n\ngroot = '$';\nlroot = '@';\ndot = '.';\nopenc = '[';\nclosec = ']';\nslice = ':';\nwildcard = '*';\nindex = [0-9]+;\ncomma = ',';\nmember = [a-zA-Z_\\-][a-zA-Z0-9_\\-]*;\n\nmain := |*\n groot => groot_tok;\n lroot => lroot_tok;\n dot => dot_tok;\n openc => openc_tok;\n closec => closec_tok;\n slice => slice_tok;\n wildcard => wildcard_tok;\n index => index_tok;\n comma => comma_tok;\n member => member_tok;\n*|;\n\n}%%\n\n%% write data;\n\nnamespace ace {\nnamespace tree {\nnamespace path {\n\nScan::Scan()\n : cs(0)\n , act(0)\n , ts(0)\n , te(0)\n , lparser(0) {\n lparser = ParseAlloc(malloc);\n %% write init;\n}\n\nScan::~Scan() {\n ParseFree(lparser, free);\n}\n\nPath\nScan::parse(std::string const & str) {\n const char* p = str.c_str();\n const char* pe = str.c_str() + str.length();\n const char* eof = pe;\n %% write exec;\n ace::tree::Path * path = nullptr;\n Parse(lparser, 0, 0, &path);\n if (path == nullptr) throw std::invalid_argument(str);\n ace::tree::Path::Ref pref(path);\n return *path;\n}\n\n} \/\/ namespace path\n} \/\/ namespace tree\n} \/\/ namespace ace\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"062ce2d1472745d67a14d1ae2f35afeb736cdbbf","subject":"Use a custom function rather than boost::algorithm::replace_all.","message":"Use a custom function rather than boost::algorithm::replace_all.\n\nReduce dependencies and executable size.\n","repos":"niklata\/ncron,niklata\/ncron","old_file":"crontab.rl","new_file":"crontab.rl","new_contents":"\/* crontab.rl - configure file parser for ncron\n *\n * (c) 2003-2016 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \"nk\/privilege.h\"\n}\n\n#include \"ncron.hpp\"\n#include \"sched.hpp\"\n#include \"crontab.hpp\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\n#define MAX_LINE 2048\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\nextern int gflags_debug;\n\nstatic void get_history(std::unique_ptr &item);\n\nstruct ParseCfgState\n{\n ParseCfgState(const std::string &ef, std::vector &stk,\n std::vector &dstk) :\n stack(stk), deadstack(dstk), ce(nullptr), execfile(ef),\n jobid_st(nullptr), time_st(nullptr), intv_st(nullptr),\n intv2_st(nullptr), strv_st(nullptr), v_strlen(0), linenum(0), v_int(0),\n v_int2(0), cs(0), cmdret(0), intv2_exist(false), runat(false)\n {\n memset(v_str, 0, sizeof v_str);\n }\n char v_str[1024];\n\n std::vector &stack;\n std::vector &deadstack;\n std::unique_ptr ce;\n\n const std::string execfile;\n\n const char *jobid_st;\n const char *time_st;\n const char *intv_st;\n const char *intv2_st;\n const char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int cmdret;\n\n bool intv2_exist;\n bool runat;\n\n void create_ce()\n {\n assert(!ce);\n ce = std::make_unique();\n cmdret = 0;\n runat = false;\n }\n\n inline void debug_print_ce() const\n {\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"-=- finish_ce -=-\\n\");\n fmt::print(stderr, \"id: {}\\n\", ce->id);\n fmt::print(stderr, \"command: {}\\n\", ce->command);\n fmt::print(stderr, \"args: {}\\n\", ce->args);\n fmt::print(stderr, \"chroot: {}\\n\", ce->chroot);\n fmt::print(stderr, \"numruns: {}\\n\", ce->numruns);\n fmt::print(stderr, \"maxruns: {}\\n\", ce->maxruns);\n fmt::print(stderr, \"journal: {}\\n\", ce->journal);\n fmt::print(stderr, \"user: {}\\n\", ce->user);\n fmt::print(stderr, \"group: {}\\n\", ce->group);\n for (const auto &i: ce->month)\n fmt::print(stderr, \"month: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->day)\n fmt::print(stderr, \"day: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->weekday)\n fmt::print(stderr, \"weekday: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->hour)\n fmt::print(stderr, \"hour: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->minute)\n fmt::print(stderr, \"minute: [{},{}]\\n\", i.first, i.second);\n fmt::print(stderr, \"interval: {}\\n\", ce->interval);\n fmt::print(stderr, \"exectime: {}\\n\", ce->exectime);\n fmt::print(stderr, \"lasttime: {}\\n\", ce->lasttime);\n }\n\n inline void debug_print_ce_history() const\n {\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"[{}]->numruns = {}\\n\", ce->id, ce->numruns);\n fmt::print(stderr, \"[{}]->exectime = {}\\n\", ce->id, ce->exectime);\n fmt::print(stderr, \"[{}]->lasttime = {}\\n\", ce->id, ce->lasttime);\n }\n\n void finish_ce()\n {\n if (!ce)\n return;\n debug_print_ce();\n\n if (ce->id <= 0\n || (ce->interval <= 0 && ce->exectime <= 0)\n || ce->command.empty() || cmdret < 1) {\n if (gflags_debug)\n fmt::print(stderr, \"===> IGNORE\\n\");\n ce.reset();\n return;\n }\n if (gflags_debug)\n fmt::print(stderr, \"===> ADD\\n\");\n\n \/* we have a job to insert *\/\n if (runat) { \/* runat task *\/\n auto forced_exectime = ce->exectime;\n get_history(ce);\n ce->exectime = forced_exectime;\n debug_print_ce_history();\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (!ce->numruns)\n stack.emplace_back(std::move(ce));\n else\n deadstack.emplace_back(std::move(ce));\n } else { \/* interval task *\/\n get_history(ce);\n debug_print_ce_history();\n set_initial_exectime(*ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ce->maxruns == 0 || ce->numruns < ce->maxruns)\n && ce->exectime != 0)\n stack.emplace_back(std::move(ce));\n else\n deadstack.emplace_back(std::move(ce));\n }\n ce.reset();\n }\n\n void setgroupv()\n {\n if (nk_gidbyname(v_str, &ce->group)) {\n fmt::print(stderr, \"{}: nonexistent group specified at line {}\\n\",\n __func__, linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n\n void setuserv()\n {\n if (nk_uidgidbyname(v_str, &ce->user, &ce->group)) {\n fmt::print(stderr, \"{}: nonexistent user specified at line {}\\n\",\n __func__, linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n\n void setlim(int type)\n {\n struct rlimit rli;\n rli.rlim_cur = v_int == 0 ? RLIM_INFINITY : v_int;\n rli.rlim_max = v_int2 == 0 ? RLIM_INFINITY : v_int2;\n\n if (!ce->limits)\n ce->limits = std::make_unique();\n\n switch (type) {\n case RLIMIT_CPU: ce->limits->cpu = rli; break;\n case RLIMIT_FSIZE: ce->limits->fsize = rli; break;\n case RLIMIT_DATA: ce->limits->data = rli; break;\n case RLIMIT_STACK: ce->limits->stack = rli; break;\n case RLIMIT_CORE: ce->limits->core = rli; break;\n case RLIMIT_RSS: ce->limits->rss = rli; break;\n case RLIMIT_NPROC: ce->limits->nproc = rli; break;\n case RLIMIT_NOFILE: ce->limits->nofile = rli; break;\n case RLIMIT_MEMLOCK: ce->limits->memlock = rli; break;\n #ifndef BSD\n case RLIMIT_AS: ce->limits->as = rli; break;\n case RLIMIT_MSGQUEUE: ce->limits->msgqueue = rli; break;\n case RLIMIT_NICE: ce->limits->nice = rli; break;\n case RLIMIT_RTTIME: ce->limits->rttime = rli; break;\n case RLIMIT_RTPRIO: ce->limits->rtprio = rli; break;\n case RLIMIT_SIGPENDING: ce->limits->sigpending = rli; break;\n #endif \/* BSD *\/\n default: fmt::print(stderr, \"{}: Bad RLIMIT_type specified.\\n\", __func__);\n std::exit(EXIT_FAILURE);\n }\n }\n\n};\n\nstruct item_history {\n item_history() {}\n item_history(boost::optional e, boost::optional l,\n boost::optional n) :\n exectime(e), lasttime(l), numruns(n) {}\n boost::optional exectime;\n boost::optional lasttime;\n boost::optional numruns;\n};\n\nstruct hstm {\n hstm() : st(nullptr), cs(0), id(0) {}\n const char *st;\n int cs;\n unsigned int id;\n item_history h;\n};\n\n%%{\n machine history_m;\n access hst.;\n\n action St { hst.st = p; }\n action LastTimeEn { hst.h.lasttime = atoi(hst.st); }\n action NumRunsEn { hst.h.numruns = atoi(hst.st); }\n action ExecTimeEn { hst.h.exectime = atoi(hst.st); }\n action IdEn { hst.id = atoi(hst.st); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_parse_history(hstm &hst, const char *p, size_t plen)\n{\n const char *pe = p + plen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (hst.cs >= history_m_first_final)\n return 1;\n if (hst.cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic std::unordered_map history_map;\n\nstatic void parse_history(const std::string &path)\n{\n char buf[MAX_LINE];\n auto f = fopen(path.c_str(), \"r\");\n if (!f) {\n fmt::print(stderr, \"{}: failed to open history file \\\"{}\\\" for read: {}\\n\",\n __func__, path, strerror(errno));\n return;\n }\n size_t linenum = 0;\n while (!feof(f)) {\n auto fsv = fgets(buf, sizeof buf, f);\n auto llen = strlen(buf);\n if (buf[llen-1] == '\\n')\n buf[--llen] = 0;\n ++linenum;\n if (!fsv) {\n if (!feof(f))\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\", __func__, path);\n break;\n }\n if (llen == 0)\n continue;\n hstm h;\n auto r = do_parse_history(h, buf, llen);\n if (r < 0) {\n if (r == -2)\n fmt::print(stderr, \"{}: Incomplete configuration at line {}; ignoring\\n\",\n __func__, linenum);\n else\n fmt::print(stderr, \"{}: Malformed configuration at line {}; ignoring.\\n\",\n __func__, linenum);\n continue;\n }\n history_map.emplace(std::make_pair(\n h.id, item_history(h.h.exectime, h.h.lasttime, h.h.numruns)));\n }\n fclose(f);\n}\n\nstatic void get_history(std::unique_ptr &item)\n{\n assert(item);\n\n auto i = history_map.find(item->id);\n if (i == history_map.end())\n return;\n if (i->second.exectime) {\n auto exectm = *i->second.exectime;\n item->exectime = exectm > 0 ? exectm : 0;\n }\n if (i->second.lasttime) {\n auto lasttm = *i->second.lasttime;\n item->lasttime = lasttm > 0 ? lasttm : 0;\n }\n if (i->second.numruns) {\n item->numruns = *i->second.numruns;\n }\n}\n\nstatic void addcstlist(ParseCfgState &ncs, cronentry_t::cst_list &list,\n int wildcard, int min, int max)\n{\n int low = ncs.v_int;\n int high = wildcard;\n if (ncs.intv2_exist)\n high = ncs.v_int2;\n\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (low > high) {\n \/* discontinuous range, split into two continuous rules... *\/\n list.emplace_back(std::make_pair(low, max));\n list.emplace_back(std::make_pair(min, high));\n } else {\n \/* handle continuous ranges normally *\/\n list.emplace_back(std::make_pair(low, high));\n }\n}\n\nstatic inline void string_replace_all(std::string &s, const char *from,\n size_t fromlen, const char *to)\n{\n size_t pos{0};\n while ((pos = s.find(from, pos)) != std::string::npos) {\n s.replace(pos, fromlen, to);\n pos += fromlen;\n }\n}\n\nstruct pckm {\n pckm() : st(nullptr), cs(0) {}\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n ncs.ce->command = std::string(pckm.st, p - pckm.st);\n string_replace_all(ncs.ce->command, \"\\\\ \", 2, \" \");\n string_replace_all(ncs.ce->command, \"\\\\\\\\\", 2, \"\\\\\");\n }\n action ArgEn { ncs.ce->args = std::string(pckm.st, p - pckm.st); }\n\n sptab = [ \\t];\n cmdstr = ([^\\0 \\t] | '\\\\\\\\' | '\\\\ ')+;\n cmd = sptab* (cmdstr > St % CmdEn);\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args?;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(ParseCfgState &ncs)\n{\n char *p = ncs.v_str;\n const char *pe = ncs.v_str + ncs.v_strlen;\n const char *eof = pe;\n\n struct pckm pckm;\n\n if (ncs.cmdret != 0) {\n ncs.cmdret = -3;\n fmt::print(stderr, \"Duplicate 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs.cmdret = -1;\n fmt::print(stderr, \"Malformed 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs.cmdret = 1;\n else {\n ncs.cmdret = -2;\n fmt::print(stderr, \"Incomplete 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n}\n\n%%{\n machine ncrontab;\n access ncs.;\n\n spc = [ \\t];\n eqsep = spc* '=' spc*;\n\n action TUnitSt { ncs.time_st = p; ncs.v_time = 0; }\n action TSecEn { ncs.v_time += atoi(ncs.time_st); }\n action TMinEn { ncs.v_time += 60 * atoi(ncs.time_st); }\n action THrEn { ncs.v_time += 3600 * atoi(ncs.time_st); }\n action TDayEn { ncs.v_time += 86400 * atoi(ncs.time_st); }\n action TWeekEn { ncs.v_time += 604800 * atoi(ncs.time_st); }\n\n action IntValSt {\n ncs.intv_st = p;\n ncs.v_int = ncs.v_int2 = 0;\n ncs.intv2_exist = false;\n }\n action IntValEn { ncs.v_int = atoi(ncs.intv_st); }\n action IntVal2St { ncs.intv2_st = p; }\n action IntVal2En {\n ncs.v_int2 = atoi(ncs.intv2_st);\n ncs.intv2_exist = true;\n }\n\n action StrValSt { ncs.strv_st = p; ncs.v_strlen = 0; }\n action StrValEn {\n ncs.v_strlen = p - ncs.strv_st;\n if (ncs.v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs.v_str, sizeof ncs.v_str,\n \"%.*s\", (int)ncs.v_strlen, ncs.strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs.v_str) {\n fmt::print(stderr, \"error parsing line {} in crontab; too long?\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn);\n timeval = t_any (spc* t_any)*;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))?;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn);\n\n action JournalEn { ncs.ce->journal = true; }\n journal = 'journal'i % JournalEn;\n\n action RunAtEn {\n ncs.runat = true;\n ncs.ce->exectime = ncs.v_int;\n ncs.ce->maxruns = 1;\n ncs.ce->journal = true;\n }\n action MaxRunsEn {\n if (!ncs.runat)\n ncs.ce->maxruns = ncs.v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { ncs.setlim(RLIMIT_AS); }\n action LimMemlockEn { ncs.setlim(RLIMIT_MEMLOCK); }\n action LimNofileEn { ncs.setlim(RLIMIT_NOFILE); }\n action LimNprocEn { ncs.setlim(RLIMIT_NPROC); }\n action LimRssEn { ncs.setlim(RLIMIT_RSS); }\n action LimCoreEn { ncs.setlim(RLIMIT_CORE); }\n action LimStackEn { ncs.setlim(RLIMIT_STACK); }\n action LimDataEn { ncs.setlim(RLIMIT_DATA); }\n action LimFsizeEn { ncs.setlim(RLIMIT_FSIZE); }\n action LimCpuEn { ncs.setlim(RLIMIT_CPU); }\n action LimMsgQueueEn { ncs.setlim(RLIMIT_MSGQUEUE); }\n action LimNiceEn { ncs.setlim(RLIMIT_NICE); }\n action LimRtTimeEn { ncs.setlim(RLIMIT_RTTIME); }\n action LimRtPrioEn { ncs.setlim(RLIMIT_RTPRIO); }\n action LimSigPendingEn { ncs.setlim(RLIMIT_SIGPENDING); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n lim_msgqueue = 'l_msgqueue'i eqsep intrangeval % LimMsgQueueEn;\n lim_nice = 'l_nice'i eqsep intrangeval % LimNiceEn;\n lim_rttime = 'l_rttime'i eqsep intrangeval % LimRtTimeEn;\n lim_rtprio = 'l_rtprio'i eqsep intrangeval % LimRtPrioEn;\n lim_sigpending = 'l_sigpending'i eqsep intrangeval % LimSigPendingEn;\n\n action IntervalEn { ncs.ce->interval = ncs.v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addcstlist(ncs, ncs.ce->month, 0, 1, 12); }\n action DayEn { addcstlist(ncs, ncs.ce->day, 0, 1, 31); }\n action WeekdayEn { addcstlist(ncs, ncs.ce->weekday, 0, 1, 7); }\n action HourEn { addcstlist(ncs, ncs.ce->hour, 24, 0, 23); }\n action MinuteEn { addcstlist(ncs, ncs.ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { ncs.setgroupv(); }\n action UserEn { ncs.setuserv(); }\n action ChrootEn {\n ncs.ce->chroot = std::string(ncs.v_str, ncs.v_strlen);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n lim_msgqueue | lim_nice | lim_rttime | lim_rtprio | lim_sigpending |\n maxruns | runat | journal;\n\n action JobIdSt { ncs.jobid_st = p; }\n action JobIdEn { ncs.ce->id = atoi(ncs.jobid_st); }\n action CreateCe { ncs.finish_ce(); ncs.create_ce(); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) % JobIdEn;\n\n main := jobid | cmds;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(ParseCfgState &ncs, const char *p, size_t plen)\n{\n const char *pe = p + plen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs.cs == ncrontab_error)\n return -1;\n if (ncs.cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(const std::string &path, const std::string &execfile,\n std::vector &stk,\n std::vector &deadstk)\n{\n struct ParseCfgState ncs(execfile, stk, deadstk);\n parse_history(ncs.execfile);\n\n char buf[MAX_LINE];\n auto f = fopen(path.c_str(), \"r\");\n if (!f) {\n fmt::print(stderr, \"{}: failed to open file: '{}': {}\\n\",\n __func__, path, strerror(errno));\n std::exit(EXIT_FAILURE);\n }\n while (!feof(f)) {\n auto fsv = fgets(buf, sizeof buf, f);\n auto llen = strlen(buf);\n if (buf[llen-1] == '\\n')\n buf[--llen] = 0;\n ++ncs.linenum;\n if (!fsv) {\n if (!feof(f))\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\", __func__, path);\n break;\n }\n if (llen == 0)\n continue;\n auto r = do_parse_config(ncs, buf, llen);\n if (r < 0) {\n fmt::print(stderr, \"{}: do_parse_config({}) failed at line {}\\n\",\n __func__, path, ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n std::make_heap(stk.begin(), stk.end(), GtCronEntry);\n history_map.clear();\n cfg_reload = 1;\n fclose(f);\n}\n\n","old_contents":"\/* crontab.rl - configure file parser for ncron\n *\n * (c) 2003-2016 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \"nk\/privilege.h\"\n}\n\n#include \"ncron.hpp\"\n#include \"sched.hpp\"\n#include \"crontab.hpp\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\n#define MAX_LINE 2048\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\nextern int gflags_debug;\n\nstatic void get_history(std::unique_ptr &item);\n\nstruct ParseCfgState\n{\n ParseCfgState(const std::string &ef, std::vector &stk,\n std::vector &dstk) :\n stack(stk), deadstack(dstk), ce(nullptr), execfile(ef),\n jobid_st(nullptr), time_st(nullptr), intv_st(nullptr),\n intv2_st(nullptr), strv_st(nullptr), v_strlen(0), linenum(0), v_int(0),\n v_int2(0), cs(0), cmdret(0), intv2_exist(false), runat(false)\n {\n memset(v_str, 0, sizeof v_str);\n }\n char v_str[1024];\n\n std::vector &stack;\n std::vector &deadstack;\n std::unique_ptr ce;\n\n const std::string execfile;\n\n const char *jobid_st;\n const char *time_st;\n const char *intv_st;\n const char *intv2_st;\n const char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int cmdret;\n\n bool intv2_exist;\n bool runat;\n\n void create_ce()\n {\n assert(!ce);\n ce = std::make_unique();\n cmdret = 0;\n runat = false;\n }\n\n inline void debug_print_ce() const\n {\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"-=- finish_ce -=-\\n\");\n fmt::print(stderr, \"id: {}\\n\", ce->id);\n fmt::print(stderr, \"command: {}\\n\", ce->command);\n fmt::print(stderr, \"args: {}\\n\", ce->args);\n fmt::print(stderr, \"chroot: {}\\n\", ce->chroot);\n fmt::print(stderr, \"numruns: {}\\n\", ce->numruns);\n fmt::print(stderr, \"maxruns: {}\\n\", ce->maxruns);\n fmt::print(stderr, \"journal: {}\\n\", ce->journal);\n fmt::print(stderr, \"user: {}\\n\", ce->user);\n fmt::print(stderr, \"group: {}\\n\", ce->group);\n for (const auto &i: ce->month)\n fmt::print(stderr, \"month: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->day)\n fmt::print(stderr, \"day: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->weekday)\n fmt::print(stderr, \"weekday: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->hour)\n fmt::print(stderr, \"hour: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->minute)\n fmt::print(stderr, \"minute: [{},{}]\\n\", i.first, i.second);\n fmt::print(stderr, \"interval: {}\\n\", ce->interval);\n fmt::print(stderr, \"exectime: {}\\n\", ce->exectime);\n fmt::print(stderr, \"lasttime: {}\\n\", ce->lasttime);\n }\n\n inline void debug_print_ce_history() const\n {\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"[{}]->numruns = {}\\n\", ce->id, ce->numruns);\n fmt::print(stderr, \"[{}]->exectime = {}\\n\", ce->id, ce->exectime);\n fmt::print(stderr, \"[{}]->lasttime = {}\\n\", ce->id, ce->lasttime);\n }\n\n void finish_ce()\n {\n if (!ce)\n return;\n debug_print_ce();\n\n if (ce->id <= 0\n || (ce->interval <= 0 && ce->exectime <= 0)\n || ce->command.empty() || cmdret < 1) {\n if (gflags_debug)\n fmt::print(stderr, \"===> IGNORE\\n\");\n ce.reset();\n return;\n }\n if (gflags_debug)\n fmt::print(stderr, \"===> ADD\\n\");\n\n \/* we have a job to insert *\/\n if (runat) { \/* runat task *\/\n auto forced_exectime = ce->exectime;\n get_history(ce);\n ce->exectime = forced_exectime;\n debug_print_ce_history();\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (!ce->numruns)\n stack.emplace_back(std::move(ce));\n else\n deadstack.emplace_back(std::move(ce));\n } else { \/* interval task *\/\n get_history(ce);\n debug_print_ce_history();\n set_initial_exectime(*ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ce->maxruns == 0 || ce->numruns < ce->maxruns)\n && ce->exectime != 0)\n stack.emplace_back(std::move(ce));\n else\n deadstack.emplace_back(std::move(ce));\n }\n ce.reset();\n }\n\n void setgroupv()\n {\n if (nk_gidbyname(v_str, &ce->group)) {\n fmt::print(stderr, \"{}: nonexistent group specified at line {}\\n\",\n __func__, linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n\n void setuserv()\n {\n if (nk_uidgidbyname(v_str, &ce->user, &ce->group)) {\n fmt::print(stderr, \"{}: nonexistent user specified at line {}\\n\",\n __func__, linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n\n void setlim(int type)\n {\n struct rlimit rli;\n rli.rlim_cur = v_int == 0 ? RLIM_INFINITY : v_int;\n rli.rlim_max = v_int2 == 0 ? RLIM_INFINITY : v_int2;\n\n if (!ce->limits)\n ce->limits = std::make_unique();\n\n switch (type) {\n case RLIMIT_CPU: ce->limits->cpu = rli; break;\n case RLIMIT_FSIZE: ce->limits->fsize = rli; break;\n case RLIMIT_DATA: ce->limits->data = rli; break;\n case RLIMIT_STACK: ce->limits->stack = rli; break;\n case RLIMIT_CORE: ce->limits->core = rli; break;\n case RLIMIT_RSS: ce->limits->rss = rli; break;\n case RLIMIT_NPROC: ce->limits->nproc = rli; break;\n case RLIMIT_NOFILE: ce->limits->nofile = rli; break;\n case RLIMIT_MEMLOCK: ce->limits->memlock = rli; break;\n #ifndef BSD\n case RLIMIT_AS: ce->limits->as = rli; break;\n case RLIMIT_MSGQUEUE: ce->limits->msgqueue = rli; break;\n case RLIMIT_NICE: ce->limits->nice = rli; break;\n case RLIMIT_RTTIME: ce->limits->rttime = rli; break;\n case RLIMIT_RTPRIO: ce->limits->rtprio = rli; break;\n case RLIMIT_SIGPENDING: ce->limits->sigpending = rli; break;\n #endif \/* BSD *\/\n default: fmt::print(stderr, \"{}: Bad RLIMIT_type specified.\\n\", __func__);\n std::exit(EXIT_FAILURE);\n }\n }\n\n};\n\nstruct item_history {\n item_history() {}\n item_history(boost::optional e, boost::optional l,\n boost::optional n) :\n exectime(e), lasttime(l), numruns(n) {}\n boost::optional exectime;\n boost::optional lasttime;\n boost::optional numruns;\n};\n\nstruct hstm {\n hstm() : st(nullptr), cs(0), id(0) {}\n const char *st;\n int cs;\n unsigned int id;\n item_history h;\n};\n\n%%{\n machine history_m;\n access hst.;\n\n action St { hst.st = p; }\n action LastTimeEn { hst.h.lasttime = atoi(hst.st); }\n action NumRunsEn { hst.h.numruns = atoi(hst.st); }\n action ExecTimeEn { hst.h.exectime = atoi(hst.st); }\n action IdEn { hst.id = atoi(hst.st); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_parse_history(hstm &hst, const char *p, size_t plen)\n{\n const char *pe = p + plen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (hst.cs >= history_m_first_final)\n return 1;\n if (hst.cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic std::unordered_map history_map;\n\nstatic void parse_history(const std::string &path)\n{\n char buf[MAX_LINE];\n auto f = fopen(path.c_str(), \"r\");\n if (!f) {\n fmt::print(stderr, \"{}: failed to open history file \\\"{}\\\" for read: {}\\n\",\n __func__, path, strerror(errno));\n return;\n }\n size_t linenum = 0;\n while (!feof(f)) {\n auto fsv = fgets(buf, sizeof buf, f);\n auto llen = strlen(buf);\n if (buf[llen-1] == '\\n')\n buf[--llen] = 0;\n ++linenum;\n if (!fsv) {\n if (!feof(f))\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\", __func__, path);\n break;\n }\n if (llen == 0)\n continue;\n hstm h;\n auto r = do_parse_history(h, buf, llen);\n if (r < 0) {\n if (r == -2)\n fmt::print(stderr, \"{}: Incomplete configuration at line {}; ignoring\\n\",\n __func__, linenum);\n else\n fmt::print(stderr, \"{}: Malformed configuration at line {}; ignoring.\\n\",\n __func__, linenum);\n continue;\n }\n history_map.emplace(std::make_pair(\n h.id, item_history(h.h.exectime, h.h.lasttime, h.h.numruns)));\n }\n fclose(f);\n}\n\nstatic void get_history(std::unique_ptr &item)\n{\n assert(item);\n\n auto i = history_map.find(item->id);\n if (i == history_map.end())\n return;\n if (i->second.exectime) {\n auto exectm = *i->second.exectime;\n item->exectime = exectm > 0 ? exectm : 0;\n }\n if (i->second.lasttime) {\n auto lasttm = *i->second.lasttime;\n item->lasttime = lasttm > 0 ? lasttm : 0;\n }\n if (i->second.numruns) {\n item->numruns = *i->second.numruns;\n }\n}\n\nstatic void addcstlist(ParseCfgState &ncs, cronentry_t::cst_list &list,\n int wildcard, int min, int max)\n{\n int low = ncs.v_int;\n int high = wildcard;\n if (ncs.intv2_exist)\n high = ncs.v_int2;\n\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (low > high) {\n \/* discontinuous range, split into two continuous rules... *\/\n list.emplace_back(std::make_pair(low, max));\n list.emplace_back(std::make_pair(min, high));\n } else {\n \/* handle continuous ranges normally *\/\n list.emplace_back(std::make_pair(low, high));\n }\n}\n\nstruct pckm {\n pckm() : st(nullptr), cs(0) {}\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n ncs.ce->command = std::string(pckm.st, p - pckm.st);\n boost::algorithm::replace_all(ncs.ce->command, \"\\\\ \", \" \");\n boost::algorithm::replace_all(ncs.ce->command, \"\\\\\\\\\", \"\\\\\");\n }\n action ArgEn { ncs.ce->args = std::string(pckm.st, p - pckm.st); }\n\n sptab = [ \\t];\n cmdstr = ([^\\0 \\t] | '\\\\\\\\' | '\\\\ ')+;\n cmd = sptab* (cmdstr > St % CmdEn);\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args?;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(ParseCfgState &ncs)\n{\n char *p = ncs.v_str;\n const char *pe = ncs.v_str + ncs.v_strlen;\n const char *eof = pe;\n\n struct pckm pckm;\n\n if (ncs.cmdret != 0) {\n ncs.cmdret = -3;\n fmt::print(stderr, \"Duplicate 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs.cmdret = -1;\n fmt::print(stderr, \"Malformed 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs.cmdret = 1;\n else {\n ncs.cmdret = -2;\n fmt::print(stderr, \"Incomplete 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n}\n\n%%{\n machine ncrontab;\n access ncs.;\n\n spc = [ \\t];\n eqsep = spc* '=' spc*;\n\n action TUnitSt { ncs.time_st = p; ncs.v_time = 0; }\n action TSecEn { ncs.v_time += atoi(ncs.time_st); }\n action TMinEn { ncs.v_time += 60 * atoi(ncs.time_st); }\n action THrEn { ncs.v_time += 3600 * atoi(ncs.time_st); }\n action TDayEn { ncs.v_time += 86400 * atoi(ncs.time_st); }\n action TWeekEn { ncs.v_time += 604800 * atoi(ncs.time_st); }\n\n action IntValSt {\n ncs.intv_st = p;\n ncs.v_int = ncs.v_int2 = 0;\n ncs.intv2_exist = false;\n }\n action IntValEn { ncs.v_int = atoi(ncs.intv_st); }\n action IntVal2St { ncs.intv2_st = p; }\n action IntVal2En {\n ncs.v_int2 = atoi(ncs.intv2_st);\n ncs.intv2_exist = true;\n }\n\n action StrValSt { ncs.strv_st = p; ncs.v_strlen = 0; }\n action StrValEn {\n ncs.v_strlen = p - ncs.strv_st;\n if (ncs.v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs.v_str, sizeof ncs.v_str,\n \"%.*s\", (int)ncs.v_strlen, ncs.strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs.v_str) {\n fmt::print(stderr, \"error parsing line {} in crontab; too long?\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn);\n timeval = t_any (spc* t_any)*;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))?;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn);\n\n action JournalEn { ncs.ce->journal = true; }\n journal = 'journal'i % JournalEn;\n\n action RunAtEn {\n ncs.runat = true;\n ncs.ce->exectime = ncs.v_int;\n ncs.ce->maxruns = 1;\n ncs.ce->journal = true;\n }\n action MaxRunsEn {\n if (!ncs.runat)\n ncs.ce->maxruns = ncs.v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { ncs.setlim(RLIMIT_AS); }\n action LimMemlockEn { ncs.setlim(RLIMIT_MEMLOCK); }\n action LimNofileEn { ncs.setlim(RLIMIT_NOFILE); }\n action LimNprocEn { ncs.setlim(RLIMIT_NPROC); }\n action LimRssEn { ncs.setlim(RLIMIT_RSS); }\n action LimCoreEn { ncs.setlim(RLIMIT_CORE); }\n action LimStackEn { ncs.setlim(RLIMIT_STACK); }\n action LimDataEn { ncs.setlim(RLIMIT_DATA); }\n action LimFsizeEn { ncs.setlim(RLIMIT_FSIZE); }\n action LimCpuEn { ncs.setlim(RLIMIT_CPU); }\n action LimMsgQueueEn { ncs.setlim(RLIMIT_MSGQUEUE); }\n action LimNiceEn { ncs.setlim(RLIMIT_NICE); }\n action LimRtTimeEn { ncs.setlim(RLIMIT_RTTIME); }\n action LimRtPrioEn { ncs.setlim(RLIMIT_RTPRIO); }\n action LimSigPendingEn { ncs.setlim(RLIMIT_SIGPENDING); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n lim_msgqueue = 'l_msgqueue'i eqsep intrangeval % LimMsgQueueEn;\n lim_nice = 'l_nice'i eqsep intrangeval % LimNiceEn;\n lim_rttime = 'l_rttime'i eqsep intrangeval % LimRtTimeEn;\n lim_rtprio = 'l_rtprio'i eqsep intrangeval % LimRtPrioEn;\n lim_sigpending = 'l_sigpending'i eqsep intrangeval % LimSigPendingEn;\n\n action IntervalEn { ncs.ce->interval = ncs.v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addcstlist(ncs, ncs.ce->month, 0, 1, 12); }\n action DayEn { addcstlist(ncs, ncs.ce->day, 0, 1, 31); }\n action WeekdayEn { addcstlist(ncs, ncs.ce->weekday, 0, 1, 7); }\n action HourEn { addcstlist(ncs, ncs.ce->hour, 24, 0, 23); }\n action MinuteEn { addcstlist(ncs, ncs.ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { ncs.setgroupv(); }\n action UserEn { ncs.setuserv(); }\n action ChrootEn {\n ncs.ce->chroot = std::string(ncs.v_str, ncs.v_strlen);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n lim_msgqueue | lim_nice | lim_rttime | lim_rtprio | lim_sigpending |\n maxruns | runat | journal;\n\n action JobIdSt { ncs.jobid_st = p; }\n action JobIdEn { ncs.ce->id = atoi(ncs.jobid_st); }\n action CreateCe { ncs.finish_ce(); ncs.create_ce(); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) % JobIdEn;\n\n main := jobid | cmds;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(ParseCfgState &ncs, const char *p, size_t plen)\n{\n const char *pe = p + plen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs.cs == ncrontab_error)\n return -1;\n if (ncs.cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(const std::string &path, const std::string &execfile,\n std::vector &stk,\n std::vector &deadstk)\n{\n struct ParseCfgState ncs(execfile, stk, deadstk);\n parse_history(ncs.execfile);\n\n char buf[MAX_LINE];\n auto f = fopen(path.c_str(), \"r\");\n if (!f) {\n fmt::print(stderr, \"{}: failed to open file: '{}': {}\\n\",\n __func__, path, strerror(errno));\n std::exit(EXIT_FAILURE);\n }\n while (!feof(f)) {\n auto fsv = fgets(buf, sizeof buf, f);\n auto llen = strlen(buf);\n if (buf[llen-1] == '\\n')\n buf[--llen] = 0;\n ++ncs.linenum;\n if (!fsv) {\n if (!feof(f))\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\", __func__, path);\n break;\n }\n if (llen == 0)\n continue;\n auto r = do_parse_config(ncs, buf, llen);\n if (r < 0) {\n fmt::print(stderr, \"{}: do_parse_config({}) failed at line {}\\n\",\n __func__, path, ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n std::make_heap(stk.begin(), stk.end(), GtCronEntry);\n history_map.clear();\n cfg_reload = 1;\n fclose(f);\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"108b3d6b5f1c698483fee2706fa519fef9b8113a","subject":"use static approach - better performance","message":"use static approach - better performance\n","repos":"tak1n\/cake_lang,tak1n\/cake_lang","old_file":"lib\/cake_lang\/lexer.rl","new_file":"lib\/cake_lang\/lexer.rl","new_contents":"%%machine lexer;\n\nmodule CakeLang\n class Lexer\n %% write data;\n\n CONVERSION = {\n :T_INT => :to_i,\n :T_FLOAT => :to_f\n }\n\n def initialize\n reset\n end\n\n def reset\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n end\n\n # @ts, @te -> token start, token end\n # had to use @te-1 for token range end because 1 digit token (eg.: ',(,),+) and no whitespace between will \n # break the tokenization\n def data(start = @ts, stop = (@te-1))\n return @data[start..stop].pack('U*')\n end\n\n def emit(symbol, start = @ts, stop = (@te-1))\n value = data(start, stop)\n\n if symbol.eql?(:T_INT) or symbol.eql?(:T_FLOAT)\n value = value.send(CONVERSION[symbol])\n end\n\n @tokens << [symbol, value]\n end\n\n def lex(data)\n @data = data.unpack(\"U*\")\n lexer_start = self.class.lexer_start\n eof = data.length\n\n _lexer_eof_trans = self.class.send(:_lexer_eof_trans)\n _lexer_from_state_actions = self.class.send(:_lexer_from_state_actions)\n _lexer_index_offsets = self.class.send(:_lexer_index_offsets)\n _lexer_indicies = self.class.send(:_lexer_indicies)\n _lexer_key_spans = self.class.send(:_lexer_key_spans)\n _lexer_to_state_actions = self.class.send(:_lexer_to_state_actions)\n _lexer_trans_actions = self.class.send(:_lexer_trans_actions)\n _lexer_trans_keys = self.class.send(:_lexer_trans_keys)\n _lexer_trans_targs = self.class.send(:_lexer_trans_targs)\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n %%{\n access @;\n\n T_KEYWORD_DEF = '->';\n T_KEYWORD_END = '<-';\n T_KEYWORD_OUT = 'puts';\n T_DQUOTE = '\"';\n T_INT = ('+'|'-')?[0-9]+;\n T_FLOAT = ('+'|'-')?[0-9]+'.'[0-9];\n T_LITERAL = [a-zA-Z_][a-zA-Z_0-9]*;\n T_ADD = '+';\n T_SUB = '-';\n T_MUL = '*';\n T_DIV = '\/';\n T_MOD = '%';\n T_EXP = '^';\n T_LBR = '(';\n T_RBR = ')';\n T_EQ = '=';\n T_COL = ',';\n\n main := |*\n\n T_KEYWORD_DEF => {\n emit(:T_KEYWORD_DEF)\n };\n\n T_KEYWORD_END => {\n emit(:T_KEYWORD_END)\n };\n\n T_KEYWORD_OUT => {\n emit(:T_KEYWORD_OUT)\n };\n\n T_DQUOTE => {\n emit(:T_DQUOTE)\n };\n\n T_INT => {\n emit(:T_INT)\n };\n\n T_FLOAT => {\n emit(:T_FLOAT)\n };\n\n T_LITERAL => {\n emit(:T_LITERAL)\n };\n\n T_ADD => {\n emit(:T_ADD)\n };\n\n T_SUB => {\n emit(:T_SUB)\n };\n\n T_MUL => {\n emit(:T_MUL)\n };\n\n T_DIV => {\n emit(:T_DIV)\n };\n\n T_EXP => {\n emit(:T_EXP)\n };\n\n T_MOD => {\n emit(:T_MOD)\n };\n\n T_LBR => {\n emit(:T_LBR)\n };\n\n T_RBR => {\n emit(:T_RBR)\n };\n\n T_EQ => {\n emit(:T_EQ)\n };\n\n T_COL => {\n emit(:T_COL)\n };\n\n space;\n\n # any+ => {\n # emit(:UNKNOWN)\n # };\n\n *|;\n\n }%%\n end # Lexer\nend # CakeLang\n","old_contents":"%%machine lexer;\n\nmodule CakeLang\n class Lexer\n %% write data;\n\n CONVERSION = {\n :T_INT => :to_i,\n :T_FLOAT => :to_f\n }\n\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize\n reset\n end\n\n def reset\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n end\n\n # @ts, @te -> token start, token end\n # had to use @te-1 for token range end because 1 digit token (eg.: ',(,),+) and no whitespace between will \n # break the tokenization\n def data(start = @ts, stop = (@te-1))\n return @data[start..stop].pack('U*')\n end\n\n def emit(symbol, start = @ts, stop = (@te-1))\n value = data(start, stop)\n\n if symbol.eql?(:T_INT) or symbol.eql?(:T_FLOAT)\n value = value.send(CONVERSION[symbol])\n end\n\n @tokens << [symbol, value]\n end\n\n def lex(data)\n @data = data.unpack(\"U*\")\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n %%{\n access @;\n\n T_KEYWORD_DEF = '->';\n T_KEYWORD_END = '<-';\n T_KEYWORD_OUT = 'puts';\n T_DQUOTE = '\"';\n T_INT = ('+'|'-')?[0-9]+;\n T_FLOAT = ('+'|'-')?[0-9]+'.'[0-9];\n T_LITERAL = [a-zA-Z_][a-zA-Z_0-9]*;\n T_ADD = '+';\n T_SUB = '-';\n T_MUL = '*';\n T_DIV = '\/';\n T_MOD = '%';\n T_EXP = '^';\n T_LBR = '(';\n T_RBR = ')';\n T_EQ = '=';\n T_COL = ',';\n\n main := |*\n\n T_KEYWORD_DEF => {\n emit(:T_KEYWORD_DEF)\n };\n\n T_KEYWORD_END => {\n emit(:T_KEYWORD_END)\n };\n\n T_KEYWORD_OUT => {\n emit(:T_KEYWORD_OUT)\n };\n\n T_DQUOTE => {\n emit(:T_DQUOTE)\n };\n\n T_INT => {\n emit(:T_INT)\n };\n\n T_FLOAT => {\n emit(:T_FLOAT)\n };\n\n T_LITERAL => {\n emit(:T_LITERAL)\n };\n\n T_ADD => {\n emit(:T_ADD)\n };\n\n T_SUB => {\n emit(:T_SUB)\n };\n\n T_MUL => {\n emit(:T_MUL)\n };\n\n T_DIV => {\n emit(:T_DIV)\n };\n\n T_EXP => {\n emit(:T_EXP)\n };\n\n T_MOD => {\n emit(:T_MOD)\n };\n\n T_LBR => {\n emit(:T_LBR)\n };\n\n T_RBR => {\n emit(:T_RBR)\n };\n\n T_EQ => {\n emit(:T_EQ)\n };\n\n T_COL => {\n emit(:T_COL)\n };\n\n space;\n\n # any+ => {\n # emit(:UNKNOWN)\n # };\n\n *|;\n\n }%%\n end # Lexer\nend # CakeLang\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"5dea3c532577c7a5db653658d0904381d265ba10","subject":"formatting","message":"formatting\n","repos":"hoytech\/libqstruct,hoytech\/libqstruct","old_file":"parser.rl","new_file":"parser.rl","new_contents":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qstruct\/compiler.h\"\n\nint calculate_qstruct_packing(struct qstruct_definition *);\n\n\n%%{\n machine qstruct;\n write data;\n}%%\n\nstruct qstruct_definition *parse_qstructs(char *schema, size_t schema_size, char *err_buf, size_t err_buf_size) {\n char *p = schema, *pe = schema + schema_size, *eof = 0;\n int cs = -1;\n\n int curr_line = 1;\n ssize_t i;\n size_t j;\n int err = 0;\n\n struct qstruct_definition *def = NULL, *new_def, *curr_def, *temp_def;\n struct qstruct_item curr_item;\n ssize_t curr_item_index;\n struct qstruct_definition *def_hash_by_name = NULL, *def_lookup;\n\n struct qstruct_item *new_items;\n ssize_t items_allocated;\n ssize_t largest_item;\n struct qstruct_item *item_hash_by_name = NULL, *item_lookup;\n\n char err_ctx_buf[256];\n char err_desc_buf[512];\n char *err_ctx_start, *err_ctx_end;\n\n\n \/\/ Parsing phase\n\n\n \/\/ the ragel state machine will initialise these variables, assignments silence compiler warnings\n curr_item_index = 0;\n memset(&curr_item, '\\0', sizeof(curr_item));\n items_allocated = 0;\n largest_item = -1;\n\n\n #define PARSE_ERROR(...) do { \\\n snprintf(err_desc_buf, sizeof(err_desc_buf), __VA_ARGS__); \\\n for(err_ctx_start=p; err_ctx_start>schema && *err_ctx_start != '\\n' && (p-err_ctx_start) < 20; err_ctx_start--) {} \\\n while (isspace(*err_ctx_start) && err_ctx_start < p) err_ctx_start++; \\\n for(err_ctx_end=p; err_ctx_end<(pe-1) && *err_ctx_end != '\\n' && (err_ctx_end-p) < 20; err_ctx_end++) {} \\\n memcpy(err_ctx_buf, err_ctx_start, err_ctx_end - err_ctx_start); \\\n *(err_ctx_buf + (err_ctx_end - err_ctx_start)) = '\\0'; \\\n snprintf(err_buf, err_buf_size, \"\\n------------------------------------------------------------\\nQstruct schema parse error (line %d, character %d)\\n\\n %s\\n %*s^\\n %*s|--%s\\n\\n------------------------------------------------------------\\n\", curr_line, (int)(p-schema), err_ctx_buf, (int)(p-err_ctx_start), \" \", (int)(p-err_ctx_start), \" \", err_desc_buf); \\\n err = 1; \\\n goto bail; \\\n } while(0)\n\n %%{\n action init_qstruct {\n new_def = malloc(sizeof(struct qstruct_definition));\n if (new_def == NULL)\n PARSE_ERROR(\"out of memory\");\n\n new_def->next = def;\n def = new_def;\n new_def = NULL;\n\n items_allocated = 64;\n def->items = malloc(items_allocated * sizeof(struct qstruct_item));\n if (def->items == NULL)\n PARSE_ERROR(\"out of memory\");\n\n largest_item = -1;\n for (i=0; iitems[i].occupied = 0;\n }\n\n action handle_item {\n if (curr_item_index < 0)\n PARSE_ERROR(\"id value overflow\"); \/\/ FIXME: prolly need to check upper bound\n\n if (curr_item_index >= items_allocated) {\n new_items = realloc(def->items, curr_item_index*2 * sizeof(struct qstruct_item));\n if (new_items == NULL) \n PARSE_ERROR(\"out of memory\");\n\n def->items = new_items;\n new_items = NULL;\n\n for(i=items_allocated; iitems[i].occupied = 0;\n items_allocated = curr_item_index*2;\n }\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BOOL && (curr_item.type & (QSTRUCT_TYPE_MOD_ARRAY_FIX | QSTRUCT_TYPE_MOD_ARRAY_DYN)))\n PARSE_ERROR(\"bools can't be arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_STRING && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"strings can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BLOB && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"blobs can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_NESTED && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"nested qstructs can't be fixed-size arrays\");\n\n if (def->items[curr_item_index].occupied)\n PARSE_ERROR(\"duplicated index %ld\", curr_item_index);\n\n def->items[curr_item_index].name = curr_item.name;\n def->items[curr_item_index].name_len = curr_item.name_len;\n def->items[curr_item_index].type = curr_item.type;\n def->items[curr_item_index].fixed_array_size = curr_item.fixed_array_size;\n def->items[curr_item_index].nested_name = curr_item.nested_name;\n def->items[curr_item_index].nested_name_len = curr_item.nested_name_len;\n def->items[curr_item_index].occupied = 1;\n\n if (curr_item_index > largest_item) largest_item = curr_item_index;\n }\n\n action handle_qstruct {\n assert(!item_hash_by_name);\n\n for(i=0; i<=largest_item; i++) {\n if (!def->items[i].occupied)\n PARSE_ERROR(\"missing item %ld\", i);\n\n HASH_FIND(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, item_lookup);\n if (item_lookup)\n PARSE_ERROR(\"duplicate item name '%.*s'\", (int) def->items[i].name_len, def->items[i].name);\n\n HASH_ADD_KEYPTR(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, &def->items[i]);\n }\n\n HASH_CLEAR(hh, item_hash_by_name);\n\n def[0].num_items = largest_item+1;\n }\n\n\n newline = '\\n' @{ curr_line++; };\n any_count_line = any | newline;\n whitespace_char = any_count_line - 0x21..0x7e;\n\n alnum_u = alnum | '_';\n lc_alpha_u = [a-z] | '_';\n uc_alpha_u = [A-Z] | '_';\n identifier = lc_alpha_u $!{ PARSE_ERROR(\"qstruct item names must start with lowercase letters\"); }\n alnum_u*;\n identifier_with_package = uc_alpha_u $!{ PARSE_ERROR(\"qstruct names must start with uppercase letters\"); }\n alnum_u* ('::' uc_alpha_u alnum_u*)*;\n integer = digit+;\n\n ws = whitespace_char |\n '#' [^\\n]* newline |\n '\/*' (any_count_line* - (any_count_line* '*\/' any_count_line*)) '*\/'\n ;\n\n type = 'string' %{ curr_item.type = QSTRUCT_TYPE_STRING; } |\n 'blob' %{ curr_item.type = QSTRUCT_TYPE_BLOB; } |\n 'bool' %{ curr_item.type = QSTRUCT_TYPE_BOOL; } |\n 'float' %{ curr_item.type = QSTRUCT_TYPE_FLOAT; } |\n 'double' %{ curr_item.type = QSTRUCT_TYPE_DOUBLE; } |\n 'int8' %{ curr_item.type = QSTRUCT_TYPE_INT8; } |\n 'uint8' %{ curr_item.type = QSTRUCT_TYPE_INT8 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int16' %{ curr_item.type = QSTRUCT_TYPE_INT16; } |\n 'uint16' %{ curr_item.type = QSTRUCT_TYPE_INT16 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int32' %{ curr_item.type = QSTRUCT_TYPE_INT32; } |\n 'uint32' %{ curr_item.type = QSTRUCT_TYPE_INT32 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int64' %{ curr_item.type = QSTRUCT_TYPE_INT64; } |\n 'uint64' %{ curr_item.type = QSTRUCT_TYPE_INT64 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n identifier_with_package >{ curr_item.nested_name = p; curr_item.type = QSTRUCT_TYPE_NESTED; }\n %{ curr_item.nested_name_len = p - curr_item.nested_name; }\n ;\n\n array_spec = '['\n ws*\n integer >{ curr_item.fixed_array_size = 0; }\n @{ curr_item.fixed_array_size = curr_item.fixed_array_size * 10 + (fc - '0'); }\n ws*\n ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_FIX; }\n\n |\n\n '[' ws* ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_DYN; }\n ;\n\n item = identifier >{ curr_item.name = p; curr_item.fixed_array_size = 1; }\n %{ curr_item.name_len = p - curr_item.name; }\n $!{ PARSE_ERROR(\"invalid identifier\"); }\n ws+\n '@' $!{ PARSE_ERROR(\"expected @ id\"); }\n integer >{ curr_item_index = 0; }\n @{ curr_item_index = curr_item_index * 10 + (fc - '0'); }\n ws+\n type $!{ PARSE_ERROR(\"unrecognized type\"); }\n ws*\n array_spec? $!{ PARSE_ERROR(\"invalid array specifier\"); }\n ws* ';' $!{ PARSE_ERROR(\"missing semi-colon\"); }\n ;\n\n qstruct = ws*\n ( [qQ] 'struct' ) >init_qstruct\n $!{ PARSE_ERROR(\"expected qstruct definition\"); }\n ws+\n identifier_with_package >{ def[0].name = p; }\n %{ def[0].name_len = p - def[0].name; }\n ws*\n '{'\n ws* (item @handle_item ws*)*\n '}' @handle_qstruct\n (ws* ';')?\n ;\n\n main := qstruct* ws*;\n\n write init;\n write exec;\n }%%\n\n if (cs < qstruct_first_final)\n PARSE_ERROR(\"general parse error\");\n\n\n \/\/ Compilation phase\n\n \/\/ reverse def list\n for (curr_def = NULL; def;) {\n temp_def = def->next;\n def->next = curr_def;\n curr_def = def;\n def = temp_def;\n }\n def = curr_def;\n\n assert(!def_hash_by_name);\n\n for(curr_def = def; curr_def; curr_def = curr_def->next) {\n for(j=0; jnum_items; j++) {\n if ((def->items[j].type & 0xFFFF) == QSTRUCT_TYPE_NESTED) {\n HASH_FIND(hh, def_hash_by_name, def->items[j].nested_name, def->items[j].nested_name_len, def_lookup);\n if (!def_lookup)\n PARSE_ERROR(\"type '%.*s' referred to before being defined\", (int) def->items[j].nested_name_len, def->items[j].nested_name);\n\n def->items[j].nested_def = def_lookup;\n }\n }\n\n HASH_FIND(hh, def_hash_by_name, curr_def->name, curr_def->name_len, def_lookup);\n if (def_lookup)\n PARSE_ERROR(\"duplicate def name '%.*s'\", (int) curr_def->name_len, curr_def->name);\n\n HASH_ADD_KEYPTR(hh, def_hash_by_name, curr_def->name, curr_def->name_len, curr_def);\n\n if (calculate_qstruct_packing(curr_def) < 0)\n PARSE_ERROR(\"memory error in packing\");\n }\n\n\n bail:\n\n HASH_CLEAR(hh, item_hash_by_name);\n HASH_CLEAR(hh, def_hash_by_name);\n\n if (err) {\n free_qstruct_definitions(def);\n return NULL;\n }\n\n return def;\n}\n\n\nvoid free_qstruct_definitions(struct qstruct_definition *def) {\n struct qstruct_definition *temp;\n\n while (def) {\n if (def->items) free(def->items);\n temp = def->next;\n free(def);\n def = temp;\n }\n}\n","old_contents":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qstruct\/compiler.h\"\n\nint calculate_qstruct_packing(struct qstruct_definition *);\n\n\n%%{\n machine qstruct;\n write data;\n}%%\n\nstruct qstruct_definition *parse_qstructs(char *schema, size_t schema_size, char *err_buf, size_t err_buf_size) {\n char *p = schema, *pe = schema + schema_size, *eof = 0;\n int cs = -1;\n\n int curr_line = 1;\n ssize_t i;\n size_t j;\n int err = 0;\n\n struct qstruct_definition *def = NULL, *new_def, *curr_def, *temp_def;\n struct qstruct_item curr_item;\n ssize_t curr_item_index;\n struct qstruct_definition *def_hash_by_name = NULL, *def_lookup;\n\n struct qstruct_item *new_items;\n ssize_t items_allocated;\n ssize_t largest_item;\n struct qstruct_item *item_hash_by_name = NULL, *item_lookup;\n\n char err_ctx_buf[256];\n char err_desc_buf[512];\n char *err_ctx_start, *err_ctx_end;\n\n\n \/\/ Parsing phase\n\n\n \/\/ the ragel state machine will initialise these variables, assignments silence compiler warnings\n curr_item_index = 0;\n memset(&curr_item, '\\0', sizeof(curr_item));\n items_allocated = 0;\n largest_item = -1;\n\n\n #define PARSE_ERROR(...) do { \\\n snprintf(err_desc_buf, sizeof(err_desc_buf), __VA_ARGS__); \\\n for(err_ctx_start=p; err_ctx_start>schema && *err_ctx_start != '\\n' && (p-err_ctx_start) < 20; err_ctx_start--) {} \\\n while (isspace(*err_ctx_start) && err_ctx_start < p) err_ctx_start++; \\\n for(err_ctx_end=p; err_ctx_end<(pe-1) && *err_ctx_end != '\\n' && (err_ctx_end-p) < 20; err_ctx_end++) {} \\\n memcpy(err_ctx_buf, err_ctx_start, err_ctx_end - err_ctx_start); \\\n *(err_ctx_buf + (err_ctx_end - err_ctx_start)) = '\\0'; \\\n snprintf(err_buf, err_buf_size, \"\\n------------------------------------------------------------\\nQstruct schema parse error (line %d, character %d)\\n\\n %s\\n %*s^\\n %*s|--%s\\n\\n------------------------------------------------------------\\n\", curr_line, (int)(p-schema), err_ctx_buf, (int)(p-err_ctx_start), \" \", (int)(p-err_ctx_start), \" \", err_desc_buf); \\\n err = 1; \\\n goto bail; \\\n } while(0)\n\n %%{\n action init_qstruct {\n new_def = malloc(sizeof(struct qstruct_definition));\n if (new_def == NULL)\n PARSE_ERROR(\"out of memory\");\n\n new_def->next = def;\n def = new_def;\n new_def = NULL;\n\n items_allocated = 64;\n def->items = malloc(items_allocated * sizeof(struct qstruct_item));\n if (def->items == NULL)\n PARSE_ERROR(\"out of memory\");\n\n largest_item = -1;\n for (i=0; iitems[i].occupied = 0;\n }\n\n action handle_item {\n if (curr_item_index < 0)\n PARSE_ERROR(\"id value overflow\"); \/\/ FIXME: prolly need to check upper bound\n\n if (curr_item_index >= items_allocated) {\n new_items = realloc(def->items, curr_item_index*2 * sizeof(struct qstruct_item));\n if (new_items == NULL) \n PARSE_ERROR(\"out of memory\");\n\n def->items = new_items;\n new_items = NULL;\n\n for(i=items_allocated; iitems[i].occupied = 0;\n items_allocated = curr_item_index*2;\n }\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BOOL && (curr_item.type & (QSTRUCT_TYPE_MOD_ARRAY_FIX | QSTRUCT_TYPE_MOD_ARRAY_DYN)))\n PARSE_ERROR(\"bools can't be arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_STRING && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"strings can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BLOB && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"blobs can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_NESTED && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"nested qstructs can't be fixed-size arrays\");\n\n if (def->items[curr_item_index].occupied)\n PARSE_ERROR(\"duplicated index %ld\", curr_item_index);\n\n def->items[curr_item_index].name = curr_item.name;\n def->items[curr_item_index].name_len = curr_item.name_len;\n def->items[curr_item_index].type = curr_item.type;\n def->items[curr_item_index].fixed_array_size = curr_item.fixed_array_size;\n def->items[curr_item_index].nested_name = curr_item.nested_name;\n def->items[curr_item_index].nested_name_len = curr_item.nested_name_len;\n def->items[curr_item_index].occupied = 1;\n\n if (curr_item_index > largest_item) largest_item = curr_item_index;\n }\n\n action handle_qstruct {\n assert(!item_hash_by_name);\n\n for(i=0; i<=largest_item; i++) {\n if (!def->items[i].occupied)\n PARSE_ERROR(\"missing item %ld\", i);\n\n HASH_FIND(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, item_lookup);\n if (item_lookup)\n PARSE_ERROR(\"duplicate item name '%.*s'\", (int) def->items[i].name_len, def->items[i].name);\n\n HASH_ADD_KEYPTR(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, &def->items[i]);\n }\n\n HASH_CLEAR(hh, item_hash_by_name);\n\n def[0].num_items = largest_item+1;\n }\n\n\n newline = '\\n' @{curr_line++;};\n any_count_line = any | newline;\n whitespace_char = any_count_line - 0x21..0x7e;\n\n alnum_u = alnum | '_';\n lc_alpha_u = [a-z] | '_';\n uc_alpha_u = [A-Z] | '_';\n identifier = lc_alpha_u $!{ PARSE_ERROR(\"qstruct item names must start with lowercase letters\"); }\n alnum_u*;\n identifier_with_package = uc_alpha_u $!{ PARSE_ERROR(\"qstruct names must start with uppercase letters\"); }\n alnum_u* ('::' uc_alpha_u alnum_u*)*;\n integer = digit+;\n\n ws = (\n whitespace_char |\n ( '#' [^\\n]* newline ) |\n ( '\/*' ( ( any_count_line )* - ( any_count_line* '*\/' any_count_line* ) ) '*\/' )\n );\n\n type = 'string' %{ curr_item.type = QSTRUCT_TYPE_STRING; } |\n 'blob' %{ curr_item.type = QSTRUCT_TYPE_BLOB; } |\n 'bool' %{ curr_item.type = QSTRUCT_TYPE_BOOL; } |\n 'float' %{ curr_item.type = QSTRUCT_TYPE_FLOAT; } |\n 'double' %{ curr_item.type = QSTRUCT_TYPE_DOUBLE; } |\n 'int8' %{ curr_item.type = QSTRUCT_TYPE_INT8; } |\n 'uint8' %{ curr_item.type = QSTRUCT_TYPE_INT8 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int16' %{ curr_item.type = QSTRUCT_TYPE_INT16; } |\n 'uint16' %{ curr_item.type = QSTRUCT_TYPE_INT16 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int32' %{ curr_item.type = QSTRUCT_TYPE_INT32; } |\n 'uint32' %{ curr_item.type = QSTRUCT_TYPE_INT32 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int64' %{ curr_item.type = QSTRUCT_TYPE_INT64; } |\n 'uint64' %{ curr_item.type = QSTRUCT_TYPE_INT64 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n identifier_with_package >{ curr_item.nested_name = p; curr_item.type = QSTRUCT_TYPE_NESTED; }\n %{ curr_item.nested_name_len = p - curr_item.nested_name; }\n ;\n\n array_spec = '['\n ws*\n integer >{ curr_item.fixed_array_size = 0; }\n @{ curr_item.fixed_array_size = curr_item.fixed_array_size * 10 + (fc - '0'); }\n ws*\n ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_FIX; }\n\n |\n\n '[' ws* ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_DYN; }\n ;\n\n item = identifier >{ curr_item.name = p; curr_item.fixed_array_size = 1; }\n %{ curr_item.name_len = p - curr_item.name; }\n $!{ PARSE_ERROR(\"invalid identifier\"); }\n ws+\n '@' $!{ PARSE_ERROR(\"expected @ id\"); }\n integer >{ curr_item_index = 0; }\n @{ curr_item_index = curr_item_index * 10 + (fc - '0'); }\n ws+\n type $!{ PARSE_ERROR(\"unrecognized type\"); }\n ws*\n array_spec?\n $!{ PARSE_ERROR(\"invalid array specifier\"); }\n ws* ';' $!{ PARSE_ERROR(\"missing semi-colon\"); }\n ;\n\n qstruct = ws*\n ( [qQ] 'struct' ) >init_qstruct\n $!{ PARSE_ERROR(\"expected qstruct definition\"); }\n ws+\n identifier_with_package >{ def[0].name = p; }\n %{ def[0].name_len = p - def[0].name; }\n ws*\n '{'\n ws* (item @handle_item ws*)*\n '}' @handle_qstruct\n (ws* ';')?\n ;\n\n ########################\n\n main := qstruct* ws*;\n\n write init;\n write exec;\n }%%\n\n if (cs < qstruct_first_final)\n PARSE_ERROR(\"general parse error\");\n\n\n \/\/ Compilation phase\n\n \/\/ reverse def list\n for (curr_def=NULL; def;) {\n temp_def = def->next;\n def->next = curr_def;\n curr_def = def;\n def = temp_def;\n }\n def = curr_def;\n\n assert(!def_hash_by_name);\n\n for(curr_def = def; curr_def; curr_def = curr_def->next) {\n for(j=0; jnum_items; j++) {\n if ((def->items[j].type & 0xFFFF) == QSTRUCT_TYPE_NESTED) {\n HASH_FIND(hh, def_hash_by_name, def->items[j].nested_name, def->items[j].nested_name_len, def_lookup);\n if (!def_lookup)\n PARSE_ERROR(\"type '%.*s' referred to before being defined\", (int) def->items[j].nested_name_len, def->items[j].nested_name);\n\n def->items[j].nested_def = def_lookup;\n }\n }\n\n HASH_FIND(hh, def_hash_by_name, curr_def->name, curr_def->name_len, def_lookup);\n if (def_lookup)\n PARSE_ERROR(\"duplicate def name '%.*s'\", (int) curr_def->name_len, curr_def->name);\n\n HASH_ADD_KEYPTR(hh, def_hash_by_name, curr_def->name, curr_def->name_len, curr_def);\n\n if (calculate_qstruct_packing(curr_def) < 0)\n PARSE_ERROR(\"memory error in packing\");\n }\n\n\n bail:\n\n HASH_CLEAR(hh, item_hash_by_name);\n HASH_CLEAR(hh, def_hash_by_name);\n\n if (err) {\n free_qstruct_definitions(def);\n return NULL;\n }\n\n return def;\n}\n\n\nvoid free_qstruct_definitions(struct qstruct_definition *def) {\n struct qstruct_definition *temp;\n\n while (def) {\n if (def->items) free(def->items);\n temp = def->next;\n free(def);\n def = temp;\n }\n}\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"28514650098c2a0b5cb16841f986773bf96b012b","subject":"Remove line counting, unneeded.","message":"Remove line counting, unneeded.\n","repos":"winlinvip\/feng,winlinvip\/feng,lscube\/feng,lscube\/feng,winlinvip\/feng,lscube\/feng","old_file":"src\/network\/common.rl","new_file":"src\/network\/common.rl","new_contents":"%%{\n machine common;\n\n action mark {mark = fpc;}\n\n\tBIT = \"0\" | \"1\";\n\tCHAR = 0x01..0x7f;\n\tCR = \"\\r\";\n\tLF = \"\\n\";\n\tCRLF = CR* LF;\n\tCTL = 0x00..0x1f | 0x7f;\n\tDQUOTE = \"\\\"\";\n\tHTAB = \"\\t\";\n\tSP = \" \";\n\tWSP = SP | HTAB;\n\tLWSP = ( WSP | ( CRLF WSP ) )*;\n\tOCTET = 0x00..0xff;\n\tVCHAR = 0x21..0x7e;\n\tscheme = alpha ( alpha | digit | \"+\" | \"-\" | \".\" )*;\n\tunreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n\tpct_encoded = \"%\" xdigit xdigit;\n\tsub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\" | \"=\";\n\tuserinfo = ( unreserved | pct_encoded | sub_delims | \":\" )*;\n\th16 = xdigit{1,4};\n\tdec_octet = digit | ( 0x31..0x39 digit ) | ( \"1\" digit{2} ) | ( \"2\" 0x30..0x34 digit ) | ( \"25\" 0x30..0x35 );\n\tIPv4address = dec_octet \".\" dec_octet \".\" dec_octet \".\" dec_octet;\n\tls32 = ( h16 \":\" h16 ) | IPv4address;\n\tIPv6address = ( ( h16 \":\" ){6} ls32 ) | ( \"::\" ( h16 \":\" ){5} ls32 ) | ( h16? \"::\" ( h16 \":\" ){4} ls32 ) | ( ( ( h16 \":\" )? h16 )? \"::\" ( h16 \":\" ){3} ls32 ) | ( ( ( h16 \":\" ){,2} h16 )? \"::\" ( h16 \":\" ){2} ls32 ) | ( ( ( h16 \":\" ){,3} h16 )? \"::\" h16 \":\" ls32 ) | ( ( ( h16 \":\" ){,4} h16 )? \"::\" ls32 ) | ( ( ( h16 \":\" ){,5} h16 )? \"::\" h16 ) | ( ( ( h16 \":\" ){,6} h16 )? \"::\" );\n\tIPvFuture = \"v\"i xdigit+ \".\" ( unreserved | sub_delims | \":\" )+;\n\tIP_literal = \"[\" ( IPv6address | IPvFuture ) \"]\";\n}%%\n","old_contents":"%%{\n machine common;\n\n action mark {mark = fpc;}\n\n\tBIT = \"0\" | \"1\";\n\tCHAR = 0x01..0x7f;\n\tCR = \"\\r\";\n\tLF = \"\\n\" %{line++;};\n\tCRLF = CR* LF;\n\tCTL = 0x00..0x1f | 0x7f;\n\tDQUOTE = \"\\\"\";\n\tHTAB = \"\\t\";\n\tSP = \" \";\n\tWSP = SP | HTAB;\n\tLWSP = ( WSP | ( CRLF WSP ) )*;\n\tOCTET = 0x00..0xff;\n\tVCHAR = 0x21..0x7e;\n\tscheme = alpha ( alpha | digit | \"+\" | \"-\" | \".\" )*;\n\tunreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n\tpct_encoded = \"%\" xdigit xdigit;\n\tsub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\" | \"=\";\n\tuserinfo = ( unreserved | pct_encoded | sub_delims | \":\" )*;\n\th16 = xdigit{1,4};\n\tdec_octet = digit | ( 0x31..0x39 digit ) | ( \"1\" digit{2} ) | ( \"2\" 0x30..0x34 digit ) | ( \"25\" 0x30..0x35 );\n\tIPv4address = dec_octet \".\" dec_octet \".\" dec_octet \".\" dec_octet;\n\tls32 = ( h16 \":\" h16 ) | IPv4address;\n\tIPv6address = ( ( h16 \":\" ){6} ls32 ) | ( \"::\" ( h16 \":\" ){5} ls32 ) | ( h16? \"::\" ( h16 \":\" ){4} ls32 ) | ( ( ( h16 \":\" )? h16 )? \"::\" ( h16 \":\" ){3} ls32 ) | ( ( ( h16 \":\" ){,2} h16 )? \"::\" ( h16 \":\" ){2} ls32 ) | ( ( ( h16 \":\" ){,3} h16 )? \"::\" h16 \":\" ls32 ) | ( ( ( h16 \":\" ){,4} h16 )? \"::\" ls32 ) | ( ( ( h16 \":\" ){,5} h16 )? \"::\" h16 ) | ( ( ( h16 \":\" ){,6} h16 )? \"::\" );\n\tIPvFuture = \"v\"i xdigit+ \".\" ( unreserved | sub_delims | \":\" )+;\n\tIP_literal = \"[\" ( IPv6address | IPvFuture ) \"]\";\n}%%\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"adab1addff58b0b577ec3a68805be6ca08ee4137","subject":"* lexer.rl: rename variable names from lit to current_literal.","message":"* lexer.rl: rename variable names from lit to current_literal.\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n current_literal = literal\n if !current_literal.heredoc? && (token = current_literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n current_literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n current_literal = literal\n if current_literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if current_literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if current_literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n current_literal.extend_string(tok, @ts, @te)\n else\n current_literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if current_literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n current_literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n current_literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n current_literal = literal\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(current_literal.str_s, current_literal.str_s + 1)\n end\n\n if current_literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if current_literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n lit = literal\n if !lit.heredoc? && (token = lit.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n lit.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n lit = literal\n if lit.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if lit.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if lit.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n lit.extend_string(tok, @ts, @te)\n else\n lit.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if lit.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n lit.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n lit.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n lit = literal\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(lit.str_s, lit.str_s + 1)\n end\n\n if lit.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if lit.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"2a56742cbbc24ec32b899ac54667aee89938a0a1","subject":"- += if an array, otherwise << shift in","message":"- += if an array, otherwise << shift in\n","repos":"joekiller\/logstash-kafka,tinglinux\/logstash-kafka,Aloomaio\/logstash-kafka,Aloomaio\/logstash-kafka,tinglinux\/logstash-kafka,opentable\/logstash-kafka,opentable\/logstash-kafka,joekiller\/logstash-kafka","old_file":"lib\/logstash\/config\/grammar.rl","new_file":"lib\/logstash\/config\/grammar.rl","new_contents":"require \"rubygems\"\nrequire \"logstash\/namespace\"\n\n%%{\n machine logstash_config;\n\n action mark {\n @tokenstack.push(p)\n #puts \"Mark: #{self.line(string, p)}##{self.column(string, p)}\"\n }\n\n action stack_numeric {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"numeric: #{token}\"\n #puts \"numeric?: #{string[startpos,50]}\"\n #puts [startpos, endpos].join(\",\")\n @stack << token.to_i\n }\n\n action stack_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"string: #{token}\"\n @stack << token\n }\n\n action stack_quoted_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos + 1 ... endpos - 1] # Skip quotations\n\n # Parse escapes.\n token.gsub(\/\\\\.\/) { |m| m[1,1] }\n #puts \"quotedstring: #{token}\"\n @stack << token\n }\n\n action array_init {\n @array = []\n @stack << :array_init\n }\n\n action array_push {\n while @stack.last != :array_init\n @array.unshift @stack.pop\n end\n @stack.pop # pop :array_init\n\n @stack << @array\n }\n\n action parameter_init {\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action parameter {\n value = @stack.pop\n name = @stack.pop\n #puts \"parameter: #{name} => #{value}\"\n if value.is_a?(Array)\n @parameters[name] += value\n else\n @parameters[name] << value\n end\n }\n\n action plugin {\n @components ||= []\n name = @stack.pop\n #@components << { :name => name, :parameters => @parameters }\n @components << { name => @parameters }\n @parameters = {}\n }\n\n action component_init {\n puts \"current component: \" + @stack.last\n @components = []\n }\n\n action component {\n name = @stack.pop\n @config ||= Hash.new { |h,k| h[k] = [] }\n @config[name] += @components\n puts \"Config component: #{name}\"\n }\n\n comment = \"#\" (any - [\\n])* >mark %{ e = @tokenstack.pop; puts \"Comment: #{string[e ... p]}\" };\n ws = ([ \\t\\n] | comment)** ;\n #ws = ([ \\t\\n])** ;\n\n # TODO(sissel): Support floating point values?\n numeric = ( (\"+\" | \"-\")? [0-9] :>> [0-9]** ) >mark %stack_numeric;\n quoted_string = ( \n ( \"\\\"\" ( ( (any - [\\\\\"\\n]) | \"\\\\\" any )* ) \"\\\"\" )\n | ( \"'\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"'\" ) \n ) >mark %stack_quoted_string ;\n naked_string = ( [A-Za-z_] :>> [A-Za-z0-9_]* ) >mark %stack_string ;\n string = ( quoted_string | naked_string ) ;\n\n # TODO(sissel): allow use of this.\n regexp_literal = ( \"\/\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"\/\" ) ;\n\n array = ( \"[\" ws string ws (\",\" ws string ws)* \"]\" ) >array_init %array_push;\n parameter_value = ( numeric | string | array );\n parameter = ( string ws \"=>\" ws parameter_value ) %parameter ;\n parameters = ( parameter ( ws parameter )** ) >parameter_init ;\n\n # Statement:\n # component {\n # plugin_name {\n # bar => ...\n # baz => ...\n # }\n # ...\n # }\n\n plugin = (\n (\n naked_string ws \"{\" ws\n parameters\n ws \"}\"\n ) | ( \n naked_string ws \"{\" ws \"}\" \n )\n ) %plugin ; \n\n component = (\n naked_string ws \"{\"\n >component_init\n ( ws plugin )**\n ws \"}\"\n ) %component ;\n\n config = (ws component? )** ;\n\n main := config %{ puts \"END\" }\n $err { \n # Compute line and column of the cursor (p)\n puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n # TODO(sissel): Note what we were expecting?\n } ;\n}%%\n\nclass LogStash::Config::Grammar\n attr_accessor :eof\n attr_accessor :config\n\n def initialize\n # BEGIN RAGEL DATA\n %% write data;\n # END RAGEL DATA\n\n @tokenstack = Array.new\n @stack = Array.new\n\n @types = Hash.new { |h,k| h[k] = [] }\n @edges = []\n end\n\n def parse(string)\n data = string.unpack(\"c*\")\n\n # BEGIN RAGEL INIT\n %% write init;\n # END RAGEL INIT\n\n begin \n # BEGIN RAGEL EXEC \n %% write exec;\n # END RAGEL EXEC\n rescue => e\n # Compute line and column of the cursor (p)\n raise e\n end\n\n if cs < self.logstash_config_first_final\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n raise \"Invalid Configuration. Check syntax of config file.\"\n end\n return cs\n end # def parse\n\n def line(str, pos)\n return str[0 .. pos].count(\"\\n\") + 1\n end\n\n def column(str, pos)\n return str[0 .. pos].split(\"\\n\").last.length\n end\nend # class LogStash::Config::Grammar\n\n#def parse(string)\n #cfgparser = LogStash::Config::Grammar.new\n #result = cfgparser.parse(string)\n #puts \"result %s\" % result\n #ap cfgparser.config\n#end\n\n#parse(File.open(ARGV[0]).read)\n","old_contents":"require \"rubygems\"\nrequire \"logstash\/namespace\"\n\n%%{\n machine logstash_config;\n\n action mark {\n @tokenstack.push(p)\n #puts \"Mark: #{self.line(string, p)}##{self.column(string, p)}\"\n }\n\n action stack_numeric {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"numeric: #{token}\"\n #puts \"numeric?: #{string[startpos,50]}\"\n #puts [startpos, endpos].join(\",\")\n @stack << token.to_i\n }\n\n action stack_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"string: #{token}\"\n @stack << token\n }\n\n action stack_quoted_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos + 1 ... endpos - 1] # Skip quotations\n\n # Parse escapes.\n token.gsub(\/\\\\.\/) { |m| m[1,1] }\n #puts \"quotedstring: #{token}\"\n @stack << token\n }\n\n action array_init {\n @array = []\n @stack << :array_init\n }\n\n action array_push {\n while @stack.last != :array_init\n @array.unshift @stack.pop\n end\n @stack.pop # pop :array_init\n\n @stack << @array\n }\n\n action parameter_init {\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action parameter {\n value = @stack.pop\n name = @stack.pop\n #puts \"parameter: #{name} => #{value}\"\n @parameters[name] << value\n }\n\n action plugin {\n @components ||= []\n name = @stack.pop\n #@components << { :name => name, :parameters => @parameters }\n @components << { name => @parameters }\n @parameters = {}\n }\n\n action component_init {\n puts \"current component: \" + @stack.last\n @components = []\n }\n\n action component {\n name = @stack.pop\n @config ||= Hash.new { |h,k| h[k] = [] }\n @config[name] += @components\n puts \"Config component: #{name}\"\n }\n\n comment = \"#\" (any - [\\n])* >mark %{ e = @tokenstack.pop; puts \"Comment: #{string[e ... p]}\" };\n ws = ([ \\t\\n] | comment)** ;\n #ws = ([ \\t\\n])** ;\n\n # TODO(sissel): Support floating point values?\n numeric = ( (\"+\" | \"-\")? [0-9] :>> [0-9]** ) >mark %stack_numeric;\n quoted_string = ( \n ( \"\\\"\" ( ( (any - [\\\\\"\\n]) | \"\\\\\" any )* ) \"\\\"\" )\n | ( \"'\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"'\" ) \n ) >mark %stack_quoted_string ;\n naked_string = ( [A-Za-z_] :>> [A-Za-z0-9_]* ) >mark %stack_string ;\n string = ( quoted_string | naked_string ) ;\n\n # TODO(sissel): allow use of this.\n regexp_literal = ( \"\/\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"\/\" ) ;\n\n array = ( \"[\" ws string ws (\",\" ws string ws)* \"]\" ) >array_init %array_push;\n parameter_value = ( numeric | string | array );\n parameter = ( string ws \"=>\" ws parameter_value ) %parameter ;\n parameters = ( parameter ( ws parameter )** ) >parameter_init ;\n\n # Statement:\n # component {\n # plugin_name {\n # bar => ...\n # baz => ...\n # }\n # ...\n # }\n\n plugin = (\n (\n naked_string ws \"{\" ws\n parameters\n ws \"}\"\n ) | ( \n naked_string ws \"{\" ws \"}\" \n )\n ) %plugin ; \n\n component = (\n naked_string ws \"{\"\n >component_init\n ( ws plugin )**\n ws \"}\"\n ) %component ;\n\n config = (ws component? )** ;\n\n main := config %{ puts \"END\" }\n $err { \n # Compute line and column of the cursor (p)\n puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n # TODO(sissel): Note what we were expecting?\n } ;\n}%%\n\nclass LogStash::Config::Grammar\n attr_accessor :eof\n attr_accessor :config\n\n def initialize\n # BEGIN RAGEL DATA\n %% write data;\n # END RAGEL DATA\n\n @tokenstack = Array.new\n @stack = Array.new\n\n @types = Hash.new { |h,k| h[k] = [] }\n @edges = []\n end\n\n def parse(string)\n data = string.unpack(\"c*\")\n\n # BEGIN RAGEL INIT\n %% write init;\n # END RAGEL INIT\n\n begin \n # BEGIN RAGEL EXEC \n %% write exec;\n # END RAGEL EXEC\n rescue => e\n # Compute line and column of the cursor (p)\n raise e\n end\n\n if cs < self.logstash_config_first_final\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n raise \"Invalid Configuration. Check syntax of config file.\"\n end\n return cs\n end # def parse\n\n def line(str, pos)\n return str[0 .. pos].count(\"\\n\") + 1\n end\n\n def column(str, pos)\n return str[0 .. pos].split(\"\\n\").last.length\n end\nend # class LogStash::Config::Grammar\n\n#def parse(string)\n #cfgparser = LogStash::Config::Grammar.new\n #result = cfgparser.parse(string)\n #puts \"result %s\" % result\n #ap cfgparser.config\n#end\n\n#parse(File.open(ARGV[0]).read)\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"9e858c1b4d36dad4ba811dc0ac30f47c85be1047","subject":"Use nk_uidgidbyname() and nk_gidbyname() from ncmlib.","message":"Use nk_uidgidbyname() and nk_gidbyname() from ncmlib.\n","repos":"niklata\/ncron,niklata\/ncron","old_file":"config.rl","new_file":"config.rl","new_contents":"\/* config.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n#include \"nk\/malloc.h\"\n#include \"nk\/privilege.h\"\n\n#include \"defines.h\"\n#include \"config.h\"\n#include \"sched.h\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\n\nstruct ParseCfgState\n{\n char v_str[1024];\n\n cronentry_t *stack;\n cronentry_t *deadstack;\n cronentry_t *ce;\n\n char *execfile;\n\n char *jobid_st;\n char *time_st;\n char *intv_st;\n char *intv2_st;\n char *strv_st;\n\n size_t v_strlen;\n\n unsigned int v_jobid;\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int noextime;\n int cmdret;\n\n bool intv2_exist;\n};\n\nstatic void nullify_item(cronentry_t *item)\n{\n if (!item)\n return;\n item->id = 0;\n item->command = NULL;\n item->args = NULL;\n item->chroot = NULL;\n item->numruns = 0;\n item->maxruns = 0;\n item->journal = 0;\n item->user = 0;\n item->group = 0;\n item->month = NULL;\n item->day = NULL;\n item->weekday = NULL;\n item->hour = NULL;\n item->minute = NULL;\n item->interval = 0;\n item->exectime = 0;\n item->lasttime = 0;\n item->limits = NULL;\n item->next = NULL;\n}\n\nstatic void nullify_limits(limit_t *l)\n{\n if (!l)\n return;\n l->cpu = NULL;\n l->fsize = NULL;\n l->data = NULL;\n l->stack = NULL;\n l->core = NULL;\n l->rss = NULL;\n l->nproc = NULL;\n l->nofile = NULL;\n l->memlock = NULL;\n l->as = NULL;\n}\n\nstruct hstm {\n char *st;\n int cs;\n int id;\n time_t exectime;\n time_t lasttime;\n unsigned int numruns;\n bool got_exectime:1;\n bool got_lasttime:1;\n bool got_numruns:1;\n};\n\n%%{\n machine history_m;\n access hstm->;\n\n action St { hstm->st = p; }\n action LastTimeEn {\n hstm->lasttime = atoi(p);\n hstm->got_lasttime = 1;\n }\n action NumRunsEn {\n hstm->numruns = atoi(p);\n hstm->got_numruns = 1;\n }\n action ExecTimeEn {\n hstm->exectime = atoi(p);\n hstm->got_exectime = 1;\n }\n action IdEn { hstm->id = atoi(p); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_get_history(struct hstm *hstm, char *buf, size_t blen)\n{\n char *p = buf;\n const char *pe = buf + blen;\n const char *eof = pe;\n\n %% write exec;\n\n if (hstm->cs >= history_m_first_final)\n return 1;\n if (hstm->cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic void get_history(cronentry_t *item, char *path, int noextime)\n{\n struct hstm hstm = {0};\n\n assert(item);\n\n if (!noextime && !hstm.got_exectime)\n item->exectime = 0;\n\n FILE *f = fopen(path, \"r\");\n\n if (!f) {\n log_line(\"failed to open history file \\\"%s\\\" for read\", path);\n if (!noextime)\n item->exectime = (time_t)0; \/* gracefully fail *\/\n return;\n }\n\n char buf[MAXLINE];\n memset(buf, 0, sizeof buf);\n\n while (!feof(f)) {\n char *s = fgets(buf, (int)(sizeof buf), f);\n if (!s)\n break;\n int r = do_get_history(&hstm, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_get_history(%s) failed\", __func__, path);\n if (r == 1) {\n if (hstm.id == item->id) {\n if (hstm.got_lasttime)\n item->lasttime = hstm.lasttime;\n if (hstm.got_numruns)\n item->numruns = hstm.numruns;\n if (hstm.got_exectime && !noextime)\n item->exectime = hstm.exectime;\n break;\n }\n }\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n}\n\nstatic void setlim(struct ParseCfgState *ncs, int type)\n{\n struct rlimit **p = NULL;\n if (!ncs->ce->limits) {\n ncs->ce->limits = xmalloc(sizeof(limit_t));\n nullify_limits(ncs->ce->limits);\n }\n switch (type) {\n case RLIMIT_CPU: *p = ncs->ce->limits->cpu; break;\n case RLIMIT_FSIZE: *p = ncs->ce->limits->fsize; break;\n case RLIMIT_DATA: *p = ncs->ce->limits->data; break;\n case RLIMIT_STACK: *p = ncs->ce->limits->stack; break;\n case RLIMIT_CORE: *p = ncs->ce->limits->core; break;\n case RLIMIT_RSS: *p = ncs->ce->limits->rss; break;\n case RLIMIT_NPROC: *p = ncs->ce->limits->nproc; break;\n case RLIMIT_NOFILE: *p = ncs->ce->limits->nofile; break;\n case RLIMIT_MEMLOCK: *p = ncs->ce->limits->memlock; break;\n#ifndef BSD\n case RLIMIT_AS: *p = ncs->ce->limits->as; break;\n#endif \/* BSD *\/\n default: return;\n }\n if (!p)\n suicide(\"%s: unexpected NULL, corruption?\", __func__);\n if (!*p)\n *p = xmalloc(sizeof(struct rlimit));\n if (ncs->v_int == 0) (*p)->rlim_cur = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int;\n\n if (ncs->v_int2 == 0) (*p)->rlim_max = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int2;\n}\n\nstatic void addipairlist(struct ParseCfgState *ncs,\n ipair_node_t **list, int wildcard, int min, int max)\n{\n ipair_node_t *l;\n int low, high = wildcard;\n\n low = ncs->v_int;\n if (ncs->intv2_exist)\n high = ncs->v_int2;\n\n if (high == wildcard)\n high = low;\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (*list == NULL) {\n *list = xmalloc(sizeof(ipair_node_t));\n l = *list;\n } else {\n l = *list;\n while (l->next)\n l = l->next;\n\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n }\n\n \/* discontinuous range, split into two continuous rules... *\/\n if (low > high) {\n l->node.l = low;\n l->node.h = max;\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n l->node.l = min;\n l->node.h = high;\n l->next = NULL;\n } else {\n \/* handle continuous ranges normally *\/\n l->node.l = low;\n l->node.h = high;\n l->next = NULL;\n }\n}\n\nstatic void setgroupv(struct ParseCfgState *ncs)\n{\n if (nk_gidbyname(ncs->v_str, &ncs->ce->group))\n suicide(\"%s: nonexistent group specified at line %zu\", ncs->linenum);\n}\n\nstatic void setuserv(struct ParseCfgState *ncs)\n{\n if (nk_uidgidbyname(ncs->v_str, &ncs->ce->user, &ncs->ce->group))\n suicide(\"%s: nonexistent user specified at line %zu\", ncs->linenum);\n}\n\nstatic void parse_assign_str(char **dest, char *src, size_t srclen)\n{\n if (srclen > INT_MAX)\n suicide(\"%s: srclen would overflow int\", __func__);\n free(*dest);\n *dest = xmalloc(srclen+1);\n ssize_t l = snprintf(*dest, srclen+1, \"%.*s\", (int)srclen, src);\n if (l < 0 || (size_t)l >= srclen+1)\n suicide(\"%s: snprintf failed l=%u srclen+1=%u\", __func__, l, srclen+1);\n}\n\nstruct pckm {\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n size_t cmdlen = p - pckm.st;\n parse_assign_str(&ncs->ce->command, pckm.st, cmdlen);\n \/\/ Unescape \"\\\\\" and \"\\ \".\n int prevsl = 0;\n size_t i = 0;\n while (ncs->ce->command[i]) {\n if (prevsl && (ncs->ce->command[i] == '\\\\'\n || ncs->ce->command[i] == ' ')) {\n memmove(ncs->ce->command + i - 1,\n ncs->ce->command + i, cmdlen--);\n continue;\n }\n if (ncs->ce->command[i] == '\\\\')\n prevsl = 1;\n ++i;\n }\n }\n action ArgEn {\n parse_assign_str(&ncs->ce->args, pckm.st, p - pckm.st);\n }\n\n sptab = [ \\t];\n cmd = sptab+ ([^\\0 \\\\] | '\\\\\\\\' | '\\\\ ')+ > St % CmdEn;\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(struct ParseCfgState *ncs)\n{\n char *p = ncs->v_str;\n const char *pe = ncs->v_str + ncs->v_strlen;\n const char *eof = pe;\n\n struct pckm pckm = {0};\n\n if (ncs->cmdret != 0) {\n ncs->cmdret = -3;\n return;\n }\n\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error)\n ncs->cmdret = -1;\n else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs->cmdret = 1;\n else\n ncs->cmdret = -2;\n}\n\nstatic void create_ce(struct ParseCfgState *ncs)\n{\n assert(!ncs->ce);\n ncs->ce = xmalloc(sizeof(cronentry_t));\n nullify_item(ncs->ce);\n ncs->cmdret = 0;\n ncs->noextime = 0;\n}\n\nstatic void finish_ce(struct ParseCfgState *ncs)\n{\n assert(ncs->ce);\n if (ncs->ce->id <= 0\n || (ncs->ce->interval <= 0 && ncs->ce->exectime <= 0)\n || !ncs->ce->command || ncs->cmdret < 1) {\n free_cronentry(&ncs->ce);\n return;\n }\n\n \/* we have a job to insert *\/\n if (ncs->ce->exectime != 0) { \/* runat task *\/\n get_history(ncs->ce, ncs->execfile, 1);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n } else { \/* interval task *\/\n get_history(ncs->ce, ncs->execfile, ncs->noextime && !cfg_reload);\n\n \/* compensate for user edits to job constraints *\/\n time_t ttm = get_first_time(ncs->ce);\n if (ttm - ncs->ce->lasttime >= ncs->ce->interval)\n ncs->ce->exectime = ttm;\n else\n force_to_constraint(ncs->ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n && ncs->ce->exectime != 0)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n }\n ncs->ce = NULL;\n}\n\n%%{\n machine ncrontab;\n access ncs->;\n\n eqsep = [ \\t]+ '=' [ \\t]+;\n cmdterm = '\\0';\n\n action TUnitSt { ncs->time_st = p; ncs->v_time = 0; }\n action TSecEn { ncs->v_time += atoi(ncs->time_st); }\n action TMinEn { ncs->v_time += 60 * atoi(ncs->time_st); }\n action THrEn { ncs->v_time += 3600 * atoi(ncs->time_st); }\n action TDayEn { ncs->v_time += 86400 * atoi(ncs->time_st); }\n action TWeekEn { ncs->v_time += 604800 * atoi(ncs->time_st); }\n\n action IntValSt {\n ncs->intv_st = p;\n ncs->v_int = ncs->v_int2 = 0;\n ncs->intv2_exist = false;\n }\n action IntValEn { ncs->v_int = atoi(ncs->intv_st); }\n action IntVal2St { ncs->intv2_st = p; }\n action IntVal2En {\n ncs->v_int2 = atoi(ncs->intv2_st);\n ncs->intv2_exist = true;\n }\n\n action StrValSt { ncs->strv_st = p; ncs->v_strlen = 0; }\n action StrValEn {\n ncs->v_strlen = p - ncs->strv_st;\n if (ncs->v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs->v_str, sizeof ncs->v_str,\n \"%.*s\", (int)ncs->v_strlen, ncs->strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs->v_str) {\n \/\/ XXX: Error\/truncated.\n }\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn) cmdterm;\n timeval = t_any ([ \\t]* t_any)* cmdterm;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))? cmdterm;\n stringval = ([^\\0]+ > StrValSt % StrValEn) cmdterm;\n\n action JournalEn { ncs->ce->journal = 1; }\n action NoExecTimeEn { ncs->noextime = 1; }\n\n journal = 'journal'i cmdterm % JournalEn;\n noexectime = 'noexectime'i cmdterm % NoExecTimeEn;\n\n action RunAtEn {\n ncs->ce->exectime = ncs->v_int;\n ncs->ce->maxruns = 1;\n ncs->ce->journal = 1;\n }\n action MaxRunsEn {\n if (ncs->ce->exectime == 0)\n ncs->ce->maxruns = ncs->v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n\n action IntervalEn { ncs->ce->interval = ncs->v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addipairlist(ncs, &ncs->ce->month, 0, 1, 12); }\n action DayEn { addipairlist(ncs, &ncs->ce->day, 0, 1, 31); }\n action WeekdayEn { addipairlist(ncs, &ncs->ce->weekday, 0, 1, 7); }\n action HourEn { addipairlist(ncs, &ncs->ce->hour, 24, 0, 23); }\n action MinuteEn { addipairlist(ncs, &ncs->ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn { parse_assign_str(&ncs->ce->chroot,\n ncs->v_str, ncs->v_strlen); }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n maxruns | runat | noexectime | journal;\n\n action JobIdSt { ncs->jobid_st = p; }\n action JobIdEn { ncs->v_jobid = atoi(ncs->jobid_st); }\n action CreateCe { create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) cmdterm % JobIdEn;\n\n action FinishCe { finish_ce(ncs); }\n\n job = jobid cmds+ % FinishCe;\n main := job+;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(struct ParseCfgState *ncs,\n char *data, size_t len, bool is_eof)\n{\n char *p = data;\n const char *pe = data + len;\n const char *eof = is_eof ? pe : 0;\n\n %% write exec;\n\n if (ncs->cs == ncrontab_error)\n return -1;\n if (ncs->cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(char *path, char *execfile, cronentry_t **stk,\n cronentry_t **deadstk)\n{\n char buf[MAXLINE];\n struct ParseCfgState ncs;\n memset(buf, 0, sizeof buf);\n memset(&ncs, 0, sizeof ncs);\n ncs.execfile = execfile;\n ncs.stack = *stk;\n ncs.deadstack = *deadstk;\n\n FILE *f = fopen(path, \"r\");\n if (!f)\n suicide(\"%s: fopen(%s) failed: %s\", __func__, path, strerror(errno));\n\n while (!feof(f)) {\n char *s = fgets(buf, (int)(sizeof buf), f);\n int r = do_parse_config(&ncs, buf, strlen(buf), s == NULL);\n if (r < 0)\n suicide(\"%s: do_parse_config(%s) failed\", __func__, path);\n if (r == 1)\n break;\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n *stk = ncs.stack;\n *deadstk = ncs.deadstack;\n if (ncs.ce)\n free_cronentry(&ncs.ce); \/\/ Free partially built unused item.\n cfg_reload = 1;\n}\n\n","old_contents":"\/* config.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n#include \"nk\/malloc.h\"\n\n#include \"defines.h\"\n#include \"config.h\"\n#include \"sched.h\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\n\nstruct ParseCfgState\n{\n char v_str[1024];\n\n cronentry_t *stack;\n cronentry_t *deadstack;\n cronentry_t *ce;\n\n char *execfile;\n\n char *jobid_st;\n char *time_st;\n char *intv_st;\n char *intv2_st;\n char *strv_st;\n\n size_t v_strlen;\n\n unsigned int v_jobid;\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int noextime;\n int cmdret;\n\n bool intv2_exist;\n};\n\nstatic void nullify_item(cronentry_t *item)\n{\n if (!item)\n return;\n item->id = 0;\n item->command = NULL;\n item->args = NULL;\n item->chroot = NULL;\n item->numruns = 0;\n item->maxruns = 0;\n item->journal = 0;\n item->user = 0;\n item->group = 0;\n item->month = NULL;\n item->day = NULL;\n item->weekday = NULL;\n item->hour = NULL;\n item->minute = NULL;\n item->interval = 0;\n item->exectime = 0;\n item->lasttime = 0;\n item->limits = NULL;\n item->next = NULL;\n}\n\nstatic void nullify_limits(limit_t *l)\n{\n if (!l)\n return;\n l->cpu = NULL;\n l->fsize = NULL;\n l->data = NULL;\n l->stack = NULL;\n l->core = NULL;\n l->rss = NULL;\n l->nproc = NULL;\n l->nofile = NULL;\n l->memlock = NULL;\n l->as = NULL;\n}\n\nstruct hstm {\n char *st;\n int cs;\n int id;\n time_t exectime;\n time_t lasttime;\n unsigned int numruns;\n bool got_exectime:1;\n bool got_lasttime:1;\n bool got_numruns:1;\n};\n\n%%{\n machine history_m;\n access hstm->;\n\n action St { hstm->st = p; }\n action LastTimeEn {\n hstm->lasttime = atoi(p);\n hstm->got_lasttime = 1;\n }\n action NumRunsEn {\n hstm->numruns = atoi(p);\n hstm->got_numruns = 1;\n }\n action ExecTimeEn {\n hstm->exectime = atoi(p);\n hstm->got_exectime = 1;\n }\n action IdEn { hstm->id = atoi(p); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_get_history(struct hstm *hstm, char *buf, size_t blen)\n{\n char *p = buf;\n const char *pe = buf + blen;\n const char *eof = pe;\n\n %% write exec;\n\n if (hstm->cs >= history_m_first_final)\n return 1;\n if (hstm->cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic void get_history(cronentry_t *item, char *path, int noextime)\n{\n struct hstm hstm = {0};\n\n assert(item);\n\n if (!noextime && !hstm.got_exectime)\n item->exectime = 0;\n\n FILE *f = fopen(path, \"r\");\n\n if (!f) {\n log_line(\"failed to open history file \\\"%s\\\" for read\", path);\n if (!noextime)\n item->exectime = (time_t)0; \/* gracefully fail *\/\n return;\n }\n\n char buf[MAXLINE];\n memset(buf, 0, sizeof buf);\n\n while (!feof(f)) {\n char *s = fgets(buf, (int)(sizeof buf), f);\n if (!s)\n break;\n int r = do_get_history(&hstm, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_get_history(%s) failed\", __func__, path);\n if (r == 1) {\n if (hstm.id == item->id) {\n if (hstm.got_lasttime)\n item->lasttime = hstm.lasttime;\n if (hstm.got_numruns)\n item->numruns = hstm.numruns;\n if (hstm.got_exectime && !noextime)\n item->exectime = hstm.exectime;\n break;\n }\n }\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n}\n\nstatic void setlim(struct ParseCfgState *ncs, int type)\n{\n struct rlimit **p = NULL;\n if (!ncs->ce->limits) {\n ncs->ce->limits = xmalloc(sizeof(limit_t));\n nullify_limits(ncs->ce->limits);\n }\n switch (type) {\n case RLIMIT_CPU: *p = ncs->ce->limits->cpu; break;\n case RLIMIT_FSIZE: *p = ncs->ce->limits->fsize; break;\n case RLIMIT_DATA: *p = ncs->ce->limits->data; break;\n case RLIMIT_STACK: *p = ncs->ce->limits->stack; break;\n case RLIMIT_CORE: *p = ncs->ce->limits->core; break;\n case RLIMIT_RSS: *p = ncs->ce->limits->rss; break;\n case RLIMIT_NPROC: *p = ncs->ce->limits->nproc; break;\n case RLIMIT_NOFILE: *p = ncs->ce->limits->nofile; break;\n case RLIMIT_MEMLOCK: *p = ncs->ce->limits->memlock; break;\n#ifndef BSD\n case RLIMIT_AS: *p = ncs->ce->limits->as; break;\n#endif \/* BSD *\/\n default: return;\n }\n if (!p)\n suicide(\"%s: unexpected NULL, corruption?\", __func__);\n if (!*p)\n *p = xmalloc(sizeof(struct rlimit));\n if (ncs->v_int == 0) (*p)->rlim_cur = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int;\n\n if (ncs->v_int2 == 0) (*p)->rlim_max = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int2;\n}\n\nstatic void addipairlist(struct ParseCfgState *ncs,\n ipair_node_t **list, int wildcard, int min, int max)\n{\n ipair_node_t *l;\n int low, high = wildcard;\n\n low = ncs->v_int;\n if (ncs->intv2_exist)\n high = ncs->v_int2;\n\n if (high == wildcard)\n high = low;\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (*list == NULL) {\n *list = xmalloc(sizeof(ipair_node_t));\n l = *list;\n } else {\n l = *list;\n while (l->next)\n l = l->next;\n\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n }\n\n \/* discontinuous range, split into two continuous rules... *\/\n if (low > high) {\n l->node.l = low;\n l->node.h = max;\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n l->node.l = min;\n l->node.h = high;\n l->next = NULL;\n } else {\n \/* handle continuous ranges normally *\/\n l->node.l = low;\n l->node.h = high;\n l->next = NULL;\n }\n}\n\nstatic void setgroupv(struct ParseCfgState *ncs)\n{\n struct group *grp = getgrnam(ncs->v_str);\n if (grp)\n ncs->ce->group = grp->gr_gid;\n}\n\nstatic void setuserv(struct ParseCfgState *ncs)\n{\n struct passwd *pwd = getpwnam(ncs->v_str);\n if (pwd)\n ncs->ce->user = pwd->pw_uid;\n}\n\nstatic void parse_assign_str(char **dest, char *src, size_t srclen)\n{\n if (srclen > INT_MAX)\n suicide(\"%s: srclen would overflow int\", __func__);\n free(*dest);\n *dest = xmalloc(srclen+1);\n ssize_t l = snprintf(*dest, srclen+1, \"%.*s\", (int)srclen, src);\n if (l < 0 || (size_t)l >= srclen+1)\n suicide(\"%s: snprintf failed l=%u srclen+1=%u\", __func__, l, srclen+1);\n}\n\nstruct pckm {\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n size_t cmdlen = p - pckm.st;\n parse_assign_str(&ncs->ce->command, pckm.st, cmdlen);\n \/\/ Unescape \"\\\\\" and \"\\ \".\n int prevsl = 0;\n size_t i = 0;\n while (ncs->ce->command[i]) {\n if (prevsl && (ncs->ce->command[i] == '\\\\'\n || ncs->ce->command[i] == ' ')) {\n memmove(ncs->ce->command + i - 1,\n ncs->ce->command + i, cmdlen--);\n continue;\n }\n if (ncs->ce->command[i] == '\\\\')\n prevsl = 1;\n ++i;\n }\n }\n action ArgEn {\n parse_assign_str(&ncs->ce->args, pckm.st, p - pckm.st);\n }\n\n sptab = [ \\t];\n cmd = sptab+ ([^\\0 \\\\] | '\\\\\\\\' | '\\\\ ')+ > St % CmdEn;\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(struct ParseCfgState *ncs)\n{\n char *p = ncs->v_str;\n const char *pe = ncs->v_str + ncs->v_strlen;\n const char *eof = pe;\n\n struct pckm pckm = {0};\n\n if (ncs->cmdret != 0) {\n ncs->cmdret = -3;\n return;\n }\n\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error)\n ncs->cmdret = -1;\n else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs->cmdret = 1;\n else\n ncs->cmdret = -2;\n}\n\nstatic void create_ce(struct ParseCfgState *ncs)\n{\n assert(!ncs->ce);\n ncs->ce = xmalloc(sizeof(cronentry_t));\n nullify_item(ncs->ce);\n ncs->cmdret = 0;\n ncs->noextime = 0;\n}\n\nstatic void finish_ce(struct ParseCfgState *ncs)\n{\n assert(ncs->ce);\n if (ncs->ce->id <= 0\n || (ncs->ce->interval <= 0 && ncs->ce->exectime <= 0)\n || !ncs->ce->command || ncs->cmdret < 1) {\n free_cronentry(&ncs->ce);\n return;\n }\n\n \/* we have a job to insert *\/\n if (ncs->ce->exectime != 0) { \/* runat task *\/\n get_history(ncs->ce, ncs->execfile, 1);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n } else { \/* interval task *\/\n get_history(ncs->ce, ncs->execfile, ncs->noextime && !cfg_reload);\n\n \/* compensate for user edits to job constraints *\/\n time_t ttm = get_first_time(ncs->ce);\n if (ttm - ncs->ce->lasttime >= ncs->ce->interval)\n ncs->ce->exectime = ttm;\n else\n force_to_constraint(ncs->ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n && ncs->ce->exectime != 0)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n }\n ncs->ce = NULL;\n}\n\n%%{\n machine ncrontab;\n access ncs->;\n\n eqsep = [ \\t]+ '=' [ \\t]+;\n cmdterm = '\\0';\n\n action TUnitSt { ncs->time_st = p; ncs->v_time = 0; }\n action TSecEn { ncs->v_time += atoi(ncs->time_st); }\n action TMinEn { ncs->v_time += 60 * atoi(ncs->time_st); }\n action THrEn { ncs->v_time += 3600 * atoi(ncs->time_st); }\n action TDayEn { ncs->v_time += 86400 * atoi(ncs->time_st); }\n action TWeekEn { ncs->v_time += 604800 * atoi(ncs->time_st); }\n\n action IntValSt {\n ncs->intv_st = p;\n ncs->v_int = ncs->v_int2 = 0;\n ncs->intv2_exist = false;\n }\n action IntValEn { ncs->v_int = atoi(ncs->intv_st); }\n action IntVal2St { ncs->intv2_st = p; }\n action IntVal2En {\n ncs->v_int2 = atoi(ncs->intv2_st);\n ncs->intv2_exist = true;\n }\n\n action StrValSt { ncs->strv_st = p; ncs->v_strlen = 0; }\n action StrValEn {\n ncs->v_strlen = p - ncs->strv_st;\n if (ncs->v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs->v_str, sizeof ncs->v_str,\n \"%.*s\", (int)ncs->v_strlen, ncs->strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs->v_str) {\n \/\/ XXX: Error\/truncated.\n }\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn) cmdterm;\n timeval = t_any ([ \\t]* t_any)* cmdterm;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))? cmdterm;\n stringval = ([^\\0]+ > StrValSt % StrValEn) cmdterm;\n\n action JournalEn { ncs->ce->journal = 1; }\n action NoExecTimeEn { ncs->noextime = 1; }\n\n journal = 'journal'i cmdterm % JournalEn;\n noexectime = 'noexectime'i cmdterm % NoExecTimeEn;\n\n action RunAtEn {\n ncs->ce->exectime = ncs->v_int;\n ncs->ce->maxruns = 1;\n ncs->ce->journal = 1;\n }\n action MaxRunsEn {\n if (ncs->ce->exectime == 0)\n ncs->ce->maxruns = ncs->v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n\n action IntervalEn { ncs->ce->interval = ncs->v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addipairlist(ncs, &ncs->ce->month, 0, 1, 12); }\n action DayEn { addipairlist(ncs, &ncs->ce->day, 0, 1, 31); }\n action WeekdayEn { addipairlist(ncs, &ncs->ce->weekday, 0, 1, 7); }\n action HourEn { addipairlist(ncs, &ncs->ce->hour, 24, 0, 23); }\n action MinuteEn { addipairlist(ncs, &ncs->ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn { parse_assign_str(&ncs->ce->chroot,\n ncs->v_str, ncs->v_strlen); }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n maxruns | runat | noexectime | journal;\n\n action JobIdSt { ncs->jobid_st = p; }\n action JobIdEn { ncs->v_jobid = atoi(ncs->jobid_st); }\n action CreateCe { create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) cmdterm % JobIdEn;\n\n action FinishCe { finish_ce(ncs); }\n\n job = jobid cmds+ % FinishCe;\n main := job+;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(struct ParseCfgState *ncs,\n char *data, size_t len, bool is_eof)\n{\n char *p = data;\n const char *pe = data + len;\n const char *eof = is_eof ? pe : 0;\n\n %% write exec;\n\n if (ncs->cs == ncrontab_error)\n return -1;\n if (ncs->cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(char *path, char *execfile, cronentry_t **stk,\n cronentry_t **deadstk)\n{\n char buf[MAXLINE];\n struct ParseCfgState ncs;\n memset(buf, 0, sizeof buf);\n memset(&ncs, 0, sizeof ncs);\n ncs.execfile = execfile;\n ncs.stack = *stk;\n ncs.deadstack = *deadstk;\n\n FILE *f = fopen(path, \"r\");\n if (!f)\n suicide(\"%s: fopen(%s) failed: %s\", __func__, path, strerror(errno));\n\n while (!feof(f)) {\n char *s = fgets(buf, (int)(sizeof buf), f);\n int r = do_parse_config(&ncs, buf, strlen(buf), s == NULL);\n if (r < 0)\n suicide(\"%s: do_parse_config(%s) failed\", __func__, path);\n if (r == 1)\n break;\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n *stk = ncs.stack;\n *deadstk = ncs.deadstack;\n if (ncs.ce)\n free_cronentry(&ncs.ce); \/\/ Free partially built unused item.\n cfg_reload = 1;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"d19c93f71039ea502d5a18fd6244d4facdd961aa","subject":"+ lexer.rl: warn at \"foo **bar\".","message":"+ lexer.rl: warn at \"foo **bar\".\n","repos":"bbatsov\/parser,modulexcite\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n attr_reader :source_buffer\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n\n attr_accessor :cond, :cmdarg\n\n attr_reader :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel-related variables:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n end\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @comments = \"\" # collected comments\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n # Heredoc processing coupled with weird newline quirks\n # require three '\\0' (EOF) chars to be appended; after\n # `p = @heredoc_s`, if `p` points at EOF, the FSM could\n # not bail out early enough and will crash.\n #\n # Patches accepted.\n #\n @source = @source_buffer.source.gsub(\/\\r\\n\/, \"\\n\") + \"\\0\\0\\0\"\n else\n @source = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_beg => lex_en_expr_beg,\n :expr_value => lex_en_expr_value,\n :expr_mid => lex_en_expr_mid,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_end => lex_en_expr_end,\n :expr_arg => lex_en_expr_arg,\n :expr_endarg => lex_en_expr_endarg,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_actions = self.class.send :_lex_actions\n _lex_key_offsets = self.class.send :_lex_key_offsets\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_single_lengths = self.class.send :_lex_single_lengths\n _lex_range_lengths = self.class.send :_lex_range_lengths\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n\n p, pe, eof = @p, @source.length + 1, nil\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n [ false, [ '$eof', range(p - 1, p) ] ]\n end\n end\n\n # Return the current collected comment block and clear the storage.\n def clear_comments\n comments = @comments\n @comments = \"\"\n\n comments\n end\n\n protected\n\n def eof_char?(char)\n [0x04, 0x1a, 0x00].include? char.ord\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e - 1)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n @token_queue << [ type, [ value, range(s, e) ] ]\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def diagnostic(type, message, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, message, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.type == :tWORDS_BEG\n self.class.lex_en_interp_words\n elsif new_literal.type == :tQWORDS_BEG\n self.class.lex_en_plain_words\n elsif new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE\n }\n\n %%{\n # %\n\n access @;\n getkey @source[p].ord;\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise line and column reporting.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n c_eof = 0x04 | 0x1a | 0; # ^D, ^Z, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof - zlen;\n c_line = c_any - c_nl;\n\n c_unicode = c_any - 0x00..0x7f;\n c_lower = [a-z_] | c_unicode;\n c_upper = [A-Z] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '**' | '<<' | '>>' |\n '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = [A-Z] c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' [A-Za-z0-9_]?\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n # TODO better location reporting\n diagnostic :error, Parser::ERRORS[:unicode_point_too_large],\n range(@escape_s, p)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n end\n }\n\n action unescape_char {\n @escape = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }.fetch(@source[p - 1].chr, @source[p - 1].chr)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_escape]\n end\n }\n\n action slash_c_char {\n @escape = (@escape[0].ord & 0x9f).chr\n }\n\n action slash_m_char {\n @escape = (@escape[0].ord | 0x80).chr\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = tok(@escape_s, p).to_i(8).chr }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_hex_escape],\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_unicode_escape],\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, Parser::ERRORS[:unterminated_unicode],\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' | 'cM' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, Parser::ERRORS[:escape_eof],\n range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts < extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space_nl => { literal.flush_string };\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space_nl => { literal.flush_string };\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n message = Parser::ERRORS[:regexp_options] % { :options => unknown_options.join }\n diagnostic :error, message\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === EXPRESSION PARSING ===\n #\n\n # These rules implement a form of manually defined lookahead.\n # The default longest-match scanning does not work here due\n # to sheer ambiguity.\n\n ambiguous_fid_suffix = # actual parsed\n [?!] %{ tm = p } | # a? a?\n '!=' %{ tm = p - 2 } # a!=b a != b\n ;\n\n ambiguous_ident_suffix = # actual parsed\n ambiguous_fid_suffix |\n '=' %{ tm = p } | # a= a=\n '==' %{ tm = p - 2 } | # a==b a == b\n '=~' %{ tm = p - 2 } | # a=~b a =~ b\n '=>' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embegging\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n message = Parser::ERRORS[:cvar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n message = Parser::ERRORS[:ivar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS[tok]);\n fnext expr_end; fbreak; };\n\n bareword\n => { emit(:tIDENTIFIER)\n fnext expr_end; fbreak; };\n\n bareword ambiguous_ident_suffix\n => { emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n fnext expr_end; p = tm - 1; fbreak; };\n\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_end; fbreak; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n global_var\n => { p = @ts - 1\n fcall expr_variable; };\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext expr_arg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext expr_arg; fbreak; };\n\n call_or_var ambiguous_ident_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext expr_arg; p = tm - 1; fbreak; };\n\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n '\\\\' e_heredoc_nl;\n '#' c_line*;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n c_space+ e_lparen\n => { emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n c_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n c_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a ?b\n # Character literal.\n c_space+ '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n c_space+ ( '%' [^= ]\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n | '\/' ( c_any - c_space_nl - '=' )\n # a < { fhold; fhold; fgoto expr_beg; };\n\n # x +1\n # Ambiguous unary operator or regexp literal.\n c_space+ [+\\-\/]\n => {\n diagnostic :warning, Parser::ERRORS[:ambiguous_literal],\n range(@te - 1, @te)\n\n fhold; fhold; fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n c_space+ %{ tm = p } ( '*' | '&' | '**' )\n => {\n message = Parser::ERRORS[:ambiguous_prefix] % { :prefix => tok(tm, @te) }\n diagnostic :warning, message,\n range(tm, @te)\n\n fhold; fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n c_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n c_space* ':'\n => { fhold; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n c_space+ '?' c_space_nl\n => { fhold; fhold; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n c_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n c_space+ keyword_modifier |\n # Miscellanea.\n c_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n c_space* ( '#' c_line* )? c_nl\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit(:kDO_BLOCK)\n fnext expr_value; };\n\n c_space;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # TODO whitespace rule\n c_space;\n '#' c_line*;\n\n e_heredoc_nl\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-')\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( c_any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:string_eof],\n range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = $2.empty? ? '\"' : $2\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | c_any - c_space_nl - e_bs % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tSTRING, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[@ts + 1]]\n message = Parser::ERRORS[:invalid_escape_use] % { :escape => escape }\n diagnostic :warning, message,\n range(@ts, @ts + 1)\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:incomplete_escape],\n range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a([1, 2])\n e_lbrack |\n # a({b=>c})\n e_lbrace |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue'\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n bareword ':' ( c_any - ':' )\n => {\n fhold;\n\n if version?(18)\n emit(:tIDENTIFIER, tok(@ts, @te - 2), @ts, @te - 2)\n fhold; # continue as a symbol\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => {\n emit(:tIDENTIFIER)\n\n if @static_env && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n #\n # WHITESPACE\n #\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n '\\\\' e_heredoc_nl;\n\n '#' c_line* c_eol\n => { @comments << tok\n fhold; };\n\n e_heredoc_nl '=begin' ( c_space | c_eol )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n bareword ':'\n => { p = @ts - 1\n fgoto expr_end; };\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION)\n\n @lambda_stack.push @paren_nest\n fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active?\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' c_space_nl* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_beg; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p }\n ( xdigit+ '_' )* xdigit* '_'?\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p }\n ( [01]+ '_' )* [01]* '_'?\n | [1-9] digit*\n %{ @num_base = 10; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n | '0' %{ @num_base = 8; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n )\n => {\n digits = tok(@num_digits_s)\n\n if digits.end_with? '_'\n diagnostic :error, Parser::ERRORS[:trailing_underscore],\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, Parser::ERRORS[:empty_numeric]\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, Parser::ERRORS[:invalid_octal],\n range(invalid_s, invalid_s + 1)\n end\n\n emit(:tINTEGER, digits.to_i(@num_base))\n fbreak;\n };\n\n # Floating point literals cannot start with 0 except when a dot\n # follows immediately, probably to avoid confusion with octal literals.\n ( [1-9] [0-9]* ( '_' digit+ )* |\n '0'\n )?\n (\n '.' ( digit+ '_' )* digit+ |\n ( '.' ( digit+ '_' )* digit+ )? [eE] [+\\-]? ( digit+ '_' )* digit+\n )\n => {\n if tok.start_with? '.'\n diagnostic :error, Parser::ERRORS[:no_dot_digit_literal]\n elsif tok =~ \/^[eE]\/\n # The rule above allows to specify floats as just `e10', which is\n # certainly not a float. Send a patch if you can do this better.\n emit(:tIDENTIFIER, tok)\n fbreak;\n end\n\n emit(:tFLOAT, tok.to_f)\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext expr_arg; fbreak; };\n\n call_or_var ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_arg; fbreak; };\n\n #\n # OPERATORS\n #\n\n ( e_lparen |\n operator_arithmetic |\n operator_rest\n ) %{ tm = p } c_space_nl*\n => { emit_table(PUNCTUATION, @ts, tm)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => { emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n fbreak; };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n # TODO whitespace rule\n '\\\\' e_heredoc_nl;\n\n '\\\\' c_line {\n diagnostic :error, Parser::ERRORS[:bare_backslash],\n range(@ts, @ts + 1)\n fhold;\n };\n\n c_space+;\n\n '#' c_line*\n => { @comments << tok(@ts, @te + 1) };\n\n e_heredoc_nl\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n c_any\n => {\n message = Parser::ERRORS[:unexpected] % { :character => tok.inspect }\n diagnostic :fatal, message\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fnext line_begin; fhold; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl\n => { @comments << tok\n fgoto line_begin; };\n\n c_line* c_nl\n => { @comments << tok };\n\n c_eof\n => {\n # TODO better location information here\n diagnostic :fatal, Parser::ERRORS[:embedded_document], range(p - 1, p)\n };\n *|;\n\n line_begin := |*\n # TODO whitespace rule\n c_space_nl+;\n\n '#' c_line* c_eol\n => { @comments << tok\n fhold; };\n\n '=begin' ( c_space | c_eol )\n => { @comments << tok(@ts, @te)\n fgoto line_comment; };\n\n '__END__' c_eol\n => { p = pe - 1 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n attr_reader :source_buffer\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n\n attr_accessor :cond, :cmdarg\n\n attr_reader :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel-related variables:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n end\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @comments = \"\" # collected comments\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n # Heredoc processing coupled with weird newline quirks\n # require three '\\0' (EOF) chars to be appended; after\n # `p = @heredoc_s`, if `p` points at EOF, the FSM could\n # not bail out early enough and will crash.\n #\n # Patches accepted.\n #\n @source = @source_buffer.source.gsub(\/\\r\\n\/, \"\\n\") + \"\\0\\0\\0\"\n else\n @source = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_beg => lex_en_expr_beg,\n :expr_value => lex_en_expr_value,\n :expr_mid => lex_en_expr_mid,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_end => lex_en_expr_end,\n :expr_arg => lex_en_expr_arg,\n :expr_endarg => lex_en_expr_endarg,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_actions = self.class.send :_lex_actions\n _lex_key_offsets = self.class.send :_lex_key_offsets\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_single_lengths = self.class.send :_lex_single_lengths\n _lex_range_lengths = self.class.send :_lex_range_lengths\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n\n p, pe, eof = @p, @source.length + 1, nil\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n [ false, [ '$eof', range(p - 1, p) ] ]\n end\n end\n\n # Return the current collected comment block and clear the storage.\n def clear_comments\n comments = @comments\n @comments = \"\"\n\n comments\n end\n\n protected\n\n def eof_char?(char)\n [0x04, 0x1a, 0x00].include? char.ord\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e - 1)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n @token_queue << [ type, [ value, range(s, e) ] ]\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def diagnostic(type, message, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, message, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.type == :tWORDS_BEG\n self.class.lex_en_interp_words\n elsif new_literal.type == :tQWORDS_BEG\n self.class.lex_en_plain_words\n elsif new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE\n }\n\n %%{\n # %\n\n access @;\n getkey @source[p].ord;\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise line and column reporting.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n c_eof = 0x04 | 0x1a | 0; # ^D, ^Z, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof - zlen;\n c_line = c_any - c_nl;\n\n c_unicode = c_any - 0x00..0x7f;\n c_lower = [a-z_] | c_unicode;\n c_upper = [A-Z] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '**' | '<<' | '>>' |\n '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = [A-Z] c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' [A-Za-z0-9_]?\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n # TODO better location reporting\n diagnostic :error, Parser::ERRORS[:unicode_point_too_large],\n range(@escape_s, p)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n end\n }\n\n action unescape_char {\n @escape = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }.fetch(@source[p - 1].chr, @source[p - 1].chr)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_escape]\n end\n }\n\n action slash_c_char {\n @escape = (@escape[0].ord & 0x9f).chr\n }\n\n action slash_m_char {\n @escape = (@escape[0].ord | 0x80).chr\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = tok(@escape_s, p).to_i(8).chr }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_hex_escape],\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :error, Parser::ERRORS[:invalid_unicode_escape],\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, Parser::ERRORS[:unterminated_unicode],\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' | 'cM' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, Parser::ERRORS[:escape_eof],\n range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts < extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space_nl => { literal.flush_string };\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space_nl => { literal.flush_string };\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n message = Parser::ERRORS[:regexp_options] % { :options => unknown_options.join }\n diagnostic :error, message\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === EXPRESSION PARSING ===\n #\n\n # These rules implement a form of manually defined lookahead.\n # The default longest-match scanning does not work here due\n # to sheer ambiguity.\n\n ambiguous_fid_suffix = # actual parsed\n [?!] %{ tm = p } | # a? a?\n '!=' %{ tm = p - 2 } # a!=b a != b\n ;\n\n ambiguous_ident_suffix = # actual parsed\n ambiguous_fid_suffix |\n '=' %{ tm = p } | # a= a=\n '==' %{ tm = p - 2 } | # a==b a == b\n '=~' %{ tm = p - 2 } | # a=~b a =~ b\n '=>' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embegging\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n message = Parser::ERRORS[:cvar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n message = Parser::ERRORS[:ivar_name] % { :name => tok }\n diagnostic :error, message\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS[tok]);\n fnext expr_end; fbreak; };\n\n bareword\n => { emit(:tIDENTIFIER)\n fnext expr_end; fbreak; };\n\n bareword ambiguous_ident_suffix\n => { emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n fnext expr_end; p = tm - 1; fbreak; };\n\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_end; fbreak; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n global_var\n => { p = @ts - 1\n fcall expr_variable; };\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext expr_arg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext expr_arg; fbreak; };\n\n call_or_var ambiguous_ident_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext expr_arg; p = tm - 1; fbreak; };\n\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n '\\\\' e_heredoc_nl;\n '#' c_line*;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n c_space+ e_lparen\n => { emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n c_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n c_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a ?b\n # Character literal.\n c_space+ '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n c_space+ ( '%' [^= ]\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n | '\/' ( c_any - c_space_nl - '=' )\n # a < { fhold; fhold; fgoto expr_beg; };\n\n # x +1\n # Ambiguous unary operator or regexp literal.\n c_space+ [+\\-\/]\n => {\n diagnostic :warning, Parser::ERRORS[:ambiguous_literal],\n range(@te - 1, @te)\n\n fhold; fhold; fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat or block-pass.\n c_space+ [*&]\n => {\n message = Parser::ERRORS[:ambiguous_prefix] % { :prefix => tok(@te - 1, @te) }\n diagnostic :warning, message,\n range(@te - 1, @te)\n\n fhold; fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n c_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n c_space* ':'\n => { fhold; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n c_space+ '?' c_space_nl\n => { fhold; fhold; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n c_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n c_space+ keyword_modifier |\n # Miscellanea.\n c_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n c_space* ( '#' c_line* )? c_nl\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit(:kDO_BLOCK)\n fnext expr_value; };\n\n c_space;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # TODO whitespace rule\n c_space;\n '#' c_line*;\n\n e_heredoc_nl\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-')\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( c_any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:string_eof],\n range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = $2.empty? ? '\"' : $2\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | c_any - c_space_nl - e_bs % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tSTRING, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[@ts + 1]]\n message = Parser::ERRORS[:invalid_escape_use] % { :escape => escape }\n diagnostic :warning, message,\n range(@ts, @ts + 1)\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, Parser::ERRORS[:incomplete_escape],\n range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a([1, 2])\n e_lbrack |\n # a({b=>c})\n e_lbrace |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue'\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n bareword ':' ( c_any - ':' )\n => {\n fhold;\n\n if version?(18)\n emit(:tIDENTIFIER, tok(@ts, @te - 2), @ts, @te - 2)\n fhold; # continue as a symbol\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => {\n emit(:tIDENTIFIER)\n\n if @static_env && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n #\n # WHITESPACE\n #\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n '\\\\' e_heredoc_nl;\n\n '#' c_line* c_eol\n => { @comments << tok\n fhold; };\n\n e_heredoc_nl '=begin' ( c_space | c_eol )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n bareword ':'\n => { p = @ts - 1\n fgoto expr_end; };\n\n # TODO whitespace rule\n c_space;\n e_heredoc_nl;\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION)\n\n @lambda_stack.push @paren_nest\n fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active?\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' c_space_nl* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_beg; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p }\n ( xdigit+ '_' )* xdigit* '_'?\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p }\n ( digit+ '_' )* digit* '_'?\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p }\n ( [01]+ '_' )* [01]* '_'?\n | [1-9] digit*\n %{ @num_base = 10; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n | '0' %{ @num_base = 8; @num_digits_s = @ts }\n ( '_' digit+ )* digit* '_'?\n )\n => {\n digits = tok(@num_digits_s)\n\n if digits.end_with? '_'\n diagnostic :error, Parser::ERRORS[:trailing_underscore],\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, Parser::ERRORS[:empty_numeric]\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, Parser::ERRORS[:invalid_octal],\n range(invalid_s, invalid_s + 1)\n end\n\n emit(:tINTEGER, digits.to_i(@num_base))\n fbreak;\n };\n\n # Floating point literals cannot start with 0 except when a dot\n # follows immediately, probably to avoid confusion with octal literals.\n ( [1-9] [0-9]* ( '_' digit+ )* |\n '0'\n )?\n (\n '.' ( digit+ '_' )* digit+ |\n ( '.' ( digit+ '_' )* digit+ )? [eE] [+\\-]? ( digit+ '_' )* digit+\n )\n => {\n if tok.start_with? '.'\n diagnostic :error, Parser::ERRORS[:no_dot_digit_literal]\n elsif tok =~ \/^[eE]\/\n # The rule above allows to specify floats as just `e10', which is\n # certainly not a float. Send a patch if you can do this better.\n emit(:tIDENTIFIER, tok)\n fbreak;\n end\n\n emit(:tFLOAT, tok.to_f)\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext expr_arg; fbreak; };\n\n call_or_var ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n p = tm - 1\n fnext expr_arg; fbreak; };\n\n #\n # OPERATORS\n #\n\n ( e_lparen |\n operator_arithmetic |\n operator_rest\n ) %{ tm = p } c_space_nl*\n => { emit_table(PUNCTUATION, @ts, tm)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => { emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n fbreak; };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n # TODO whitespace rule\n '\\\\' e_heredoc_nl;\n\n '\\\\' c_line {\n diagnostic :error, Parser::ERRORS[:bare_backslash],\n range(@ts, @ts + 1)\n fhold;\n };\n\n c_space+;\n\n '#' c_line*\n => { @comments << tok(@ts, @te + 1) };\n\n e_heredoc_nl\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n c_any\n => {\n message = Parser::ERRORS[:unexpected] % { :character => tok.inspect }\n diagnostic :fatal, message\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fnext line_begin; fhold; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl\n => { @comments << tok\n fgoto line_begin; };\n\n c_line* c_nl\n => { @comments << tok };\n\n c_eof\n => {\n # TODO better location information here\n diagnostic :fatal, Parser::ERRORS[:embedded_document], range(p - 1, p)\n };\n *|;\n\n line_begin := |*\n # TODO whitespace rule\n c_space_nl+;\n\n '#' c_line* c_eol\n => { @comments << tok\n fhold; };\n\n '=begin' ( c_space | c_eol )\n => { @comments << tok(@ts, @te)\n fgoto line_comment; };\n\n '__END__' c_eol\n => { p = pe - 1 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"3b74b1d051e5c97e4e838800cc496d5145c2a1f8","subject":"Updated accessor for Float values.","message":"Updated accessor for Float values.\n","repos":"rubinius\/rapa","old_file":"actions\/rubinius\/pack_code.rl","new_file":"actions\/rubinius\/pack_code.rl","new_contents":"\/* This file was generated by Ragel. Your edits will be lost.\n *\n * This is a state machine implementation of Array#pack.\n * See http:\/\/github.com\/rubinius\/rapa.\n *\n * vim: filetype=cpp\n *\/\n\n#include \n#include \n\n#include \"machine\/config.h\"\n\n#include \"alloc.hpp\"\n#include \"memory.hpp\"\n#include \"object_utils.hpp\"\n#include \"on_stack.hpp\"\n#include \"state.hpp\"\n#include \"vm.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/byte_array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/encoding.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n\n#ifdef RBX_WINDOWS\n#include \n#endif\n\nnamespace rubinius {\n namespace pack {\n inline Object* to_int(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->symbol(\"pack_to_int\"), args);\n }\n\n#define BITS_LONG (RBX_SIZEOF_LONG * 8)\n\n inline long check_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_LONG);\n return big->to_long();\n }\n }\n\n#define BITS_64 (64)\n\n inline long long check_long_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_64);\n return big->to_long_long();\n }\n }\n\n inline Object* to_f(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->symbol(\"pack_to_float\"), args);\n }\n\n inline String* encoding_string(STATE, Object* obj, const char* coerce_name)\n {\n String* s = try_as(obj);\n if(s) return s;\n\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n std::string coerce_method(\"pack_\");\n coerce_method += coerce_name;\n Object* result = G(rubinius)->send(state, state->symbol(coerce_method.c_str()), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n inline uint16_t swap_2bytes(uint16_t x) {\n return (((x & 0x00ff)<<8) | ((x & 0xff00)>>8));\n }\n\n inline uint32_t swap_4bytes(uint32_t x) {\n return (((x & 0x000000ff) << 24)\n |((x & 0xff000000) >> 24)\n |((x & 0x0000ff00) << 8)\n |((x & 0x00ff0000) >> 8));\n }\n\n inline uint64_t swap_8bytes(uint64_t x) {\n return (((x & 0x00000000000000ffLL) << 56)\n |((x & 0xff00000000000000LL) >> 56)\n |((x & 0x000000000000ff00LL) << 40)\n |((x & 0x00ff000000000000LL) >> 40)\n |((x & 0x0000000000ff0000LL) << 24)\n |((x & 0x0000ff0000000000LL) >> 24)\n |((x & 0x00000000ff000000LL) << 8)\n |((x & 0x000000ff00000000LL) >> 8));\n }\n\n inline void swap_float(std::string& str, float value) {\n uint32_t x;\n\n memcpy(&x, &value, sizeof(float));\n x = swap_4bytes(x);\n\n str.append((const char*)&x, sizeof(uint32_t));\n }\n\n inline void swap_double(std::string& str, double value) {\n uint64_t x;\n\n memcpy(&x, &value, sizeof(double));\n x = swap_8bytes(x);\n\n str.append((const char*)&x, sizeof(uint64_t));\n }\n\n inline void double_element(std::string& str, double value) {\n str.append((const char*)&value, sizeof(double));\n }\n\n inline void float_element(std::string& str, float value) {\n str.append((const char*)&value, sizeof(float));\n }\n\n inline void short_element(std::string& str, int16_t value) {\n str.append((const char*)&value, sizeof(int16_t));\n }\n\n inline void int_element(std::string& str, int32_t value) {\n str.append((const char*)&value, sizeof(int32_t));\n }\n\n inline void long_element(std::string& str, int64_t value) {\n str.append((const char*)&value, sizeof(int64_t));\n }\n\n inline int32_t int32_element(STATE, Integer* value) {\n if(value->fixnum_p()) {\n long l = as(value)->to_long();\n if(l > INT32_MAX || l < INT32_MIN) {\n Exception::raise_range_error(state, \"Fixnum value out of range of int32\");\n }\n return l;\n } else {\n Bignum* big = as(value);\n big->verify_size(state, 32);\n return big->to_int();\n }\n }\n\n#define QUOTABLE_PRINTABLE_BUFSIZE 1024\n\n static const char hex_table[] = \"0123456789ABCDEF\";\n void quotable_printable(String* s, std::string& str, int count) {\n char buf[QUOTABLE_PRINTABLE_BUFSIZE];\n\n uint8_t* b = s->byte_address();\n uint8_t* e = b + s->byte_size();\n int i = 0, n = 0, prev = -1;\n\n for(; b < e; b++) {\n if((*b > 126) || (*b < 32 && *b != '\\n' && *b != '\\t') || (*b == '=')) {\n buf[i++] = '=';\n buf[i++] = hex_table[*b >> 4];\n buf[i++] = hex_table[*b & 0x0f];\n n += 3;\n prev = -1;\n } else if(*b == '\\n') {\n if(prev == ' ' || prev == '\\t') {\n buf[i++] = '=';\n buf[i++] = *b;\n }\n buf[i++] = *b;\n n = 0;\n prev = *b;\n } else {\n buf[i++] = *b;\n n++;\n prev = *b;\n }\n\n if(n > count) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n n = 0;\n prev = '\\n';\n }\n\n if(i > QUOTABLE_PRINTABLE_BUFSIZE - 5) {\n str.append(buf, i);\n i = 0;\n }\n }\n\n if(n > 0) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n }\n\n if(i > 0) {\n str.append(buf, i);\n }\n }\n\n static const char uu_table[] =\n \"`!\\\"#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_\";\n static const char b64_table[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n\n#define b64_uu_byte1(t, b) t[077 & (*b >> 2)]\n#define b64_uu_byte2(t, b, c) t[077 & (((*b << 4) & 060) | ((c >> 4) & 017))]\n#define b64_uu_byte3(t, b, c) t[077 & (((b[1] << 2) & 074) | ((c >> 6) & 03))];\n#define b64_uu_byte4(t, b) t[077 & b[2]];\n\n void b64_uu_encode(String* s, std::string& str,\n native_int count, native_int count_flag,\n const char* table, int padding, bool encode_size)\n {\n char *buf = ALLOCA_N(char, count * 4 \/ 3 + 6);\n native_int i, chars, line, total = s->byte_size();\n uint8_t* b = s->byte_address();\n\n for(i = 0; total > 0; i = 0, total -= line) {\n line = total > count ? count : total;\n\n if(encode_size) buf[i++] = line + ' ';\n\n for(chars = line; chars >= 3; chars -= 3, b += 3) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, b[2]);\n buf[i++] = b64_uu_byte4(table, b);\n }\n\n if(chars == 2) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, '\\0');\n buf[i++] = padding;\n } else if(chars == 1) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, '\\0');\n buf[i++] = padding;\n buf[i++] = padding;\n }\n\n b += chars;\n if(encode_size || (!encode_size && count_flag > 0)) {\n buf[i++] = '\\n';\n }\n str.append(buf, i);\n }\n }\n\n void utf8_encode(STATE, std::string& str, Integer* value) {\n int32_t v = int32_element(state, value);\n\n if(!(v & ~0x7f)) {\n str.push_back(v);\n } else if(!(v & ~0x7ff)) {\n str.push_back(((v >> 6) & 0xff) | 0xc0);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0xffff)) {\n str.push_back(((v >> 12) & 0xff) | 0xe0);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x1fffff)) {\n str.push_back(((v >> 18) & 0xff) | 0xf0);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x3ffffff)) {\n str.push_back(((v >> 24) & 0xff) | 0xf8);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x7fffffff)) {\n str.push_back(((v >> 30) & 0xff) | 0xfc);\n str.push_back(((v >> 24) & 0x3f) | 0x80);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else {\n Exception::raise_range_error(state, \"pack('U') value out of range\");\n }\n }\n\n void ber_encode(STATE, std::string& str, Integer* value) {\n if(!value->positive_p()) {\n Exception::raise_argument_error(state, \"cannot BER compress a negative number\");\n }\n\n std::string buf;\n\n if(try_as(value)) {\n Fixnum* base = Fixnum::from(128);\n while(try_as(value)) {\n Array* ary;\n if(value->fixnum_p()) {\n ary = as(value)->divmod(state, base);\n } else {\n ary = as(value)->divmod(state, base);\n }\n buf.push_back(as(ary->get(state, 1))->to_native() | 0x80);\n value = as(ary->get(state, 0));\n }\n }\n\n long v = value->to_long();\n\n while(v) {\n buf.push_back((v & 0x7f) | 0x80);\n v >>= 7;\n }\n\n if(buf.size() > 0) {\n char* a = const_cast(buf.c_str());\n char* b = a + buf.size() - 1;\n\n \/\/ clear continue bit\n *a &= 0x7f;\n\n \/\/ reverse string\n while(a < b) {\n int k = *a;\n *a++ = *b;\n *b-- = k;\n }\n\n str.append(buf.c_str(), buf.size());\n } else {\n str.push_back(0);\n }\n }\n\n inline native_int bit_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count - size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void bit_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n byte |= *b & 1;\n if(i & 7) {\n byte <<= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte <<= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n void bit_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(*b & 1)\n byte |= 128;\n\n if(i & 7) {\n byte >>= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte >>= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n inline native_int hex_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count + 1) \/ 2 - (size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void hex_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= ((*b & 15) + 9) & 15;\n } else {\n byte |= *b & 15;\n }\n\n if(i & 1) {\n byte <<= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n void hex_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= (((*b & 15) + 9) & 15) << 4;\n } else {\n byte |= (*b & 15) << 4;\n }\n\n if(i & 1) {\n byte >>= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n ByteArray* prepare_directives(STATE, String* directives,\n const char** p, const char** pe)\n {\n native_int size = directives->byte_size();\n ByteArray* ba = ByteArray::create_pinned(state, size + 1);\n char* b = reinterpret_cast(ba->raw_bytes());\n char* d = reinterpret_cast(directives->byte_address());\n int i = 0, j = 0;\n\n while(i < size) {\n switch(d[i]) {\n case 0:\n case ' ':\n case '\\t':\n case '\\n':\n case '\\v':\n case '\\f':\n case '\\r':\n i++;\n break;\n case '#':\n while(++i < size && d[i] != '\\n')\n ; \/\/ ignore\n if(d[i] == '\\n') i++;\n break;\n default:\n b[j++] = d[i++];\n break;\n }\n }\n\n *p = const_cast(b);\n *pe = *p + j;\n\n return ba;\n }\n\n void exceeds_length_of_string(STATE, native_int count) {\n std::ostringstream msg;\n msg << \"X\" << count << \" exceeds length of string\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n\n void non_native_error(STATE, const char c) {\n std::ostringstream msg;\n msg << \"'\" << c << \"' allowed only after types sSiIlL\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n }\n\n\n\/\/ Pack Float elements\n#define pack_float_elements(format) pack_elements(Float, pack::to_f, format)\n\n#define pack_double_le pack_float_elements(pack_double_element_le)\n#define pack_double_be pack_float_elements(pack_double_element_be)\n\n#define pack_float_le pack_float_elements(pack_float_element_le)\n#define pack_float_be pack_float_elements(pack_float_element_be)\n\n\/\/ Pack Integer elements\n#define pack_integer_elements(format) pack_elements(Integer, pack::to_int, format)\n\n#define pack_byte_element(v) str.push_back(pack::check_long(state, v))\n#define pack_byte pack_integer_elements(pack_byte_element)\n\n#define pack_short_le pack_integer_elements(pack_short_element_le)\n#define pack_short_be pack_integer_elements(pack_short_element_be)\n\n#define pack_int_le pack_integer_elements(pack_int_element_le)\n#define pack_int_be pack_integer_elements(pack_int_element_be)\n\n#define pack_long_le pack_integer_elements(pack_long_element_le)\n#define pack_long_be pack_integer_elements(pack_long_element_be)\n\n\/\/ Pack UTF-8 elements\n#define pack_utf8_element(v) pack::utf8_encode(state, str, v)\n#define pack_utf8 pack_elements(Integer, pack::to_int, pack_utf8_element)\n\n\/\/ Pack BER-compressed integers\n#define pack_ber_element(v) pack::ber_encode(state, str, v)\n#define pack_ber pack_elements(Integer, pack::to_int, pack_ber_element)\n\n\/\/ Wraps the logic for iterating over a number of elements,\n\/\/ coercing them to the correct class and formatting them\n\/\/ for the output string.\n#define pack_elements(T, coerce, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n format(value); \\\n }\n\n\/\/ Macros that depend on endianness\n#ifdef RBX_LITTLE_ENDIAN\n\n# define pack_double_element_le(v) (pack::double_element(str, (v)->value()))\n# define pack_double_element_be(v) (pack::swap_double(str, (v)->value()))\n# define pack_double pack_double_le\n\n# define pack_float_element_le(v) (pack::float_element(str, (v)->value()))\n# define pack_float_element_be(v) (pack::swap_float(str, (v)->value()))\n# define pack_float pack_float_le\n\n# define pack_short_element_le(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short_element_be(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short pack_short_le\n\n# define pack_int_element_le(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int_element_be(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int pack_int_le\n\n# define pack_long_element_le(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long_element_be(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long pack_long_le\n\n#else \/\/ Big endian\n\n# define pack_double_element_le(v) (pack::swap_double(str, (v)->value()))\n# define pack_double_element_be(v) (pack::double_element(str, (v)->value()))\n# define pack_double pack_double_be\n\n# define pack_float_element_le(v) (pack::swap_float(str, (v)->value()))\n# define pack_float_element_be(v) (pack::float_element(str, (v)->value()))\n# define pack_float pack_float_be\n\n# define pack_short_element_le(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short_element_be(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short pack_short_be\n\n# define pack_int_element_le(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int_element_be(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int pack_int_be\n\n# define pack_long_element_le(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long_element_be(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long pack_long_be\n\n#endif\n\n\n String* Array::pack(STATE, String* directives) {\n \/\/ Ragel-specific variables\n const char* p;\n const char* pe;\n ByteArray* d = pack::prepare_directives(state, directives, &p, &pe);\n const char *eof = pe;\n int cs;\n\n \/\/ pack-specific variables\n Array* self = this;\n OnStack<2> sv(state, self, d);\n\n native_int array_size = self->size();\n native_int index = 0;\n native_int count UNUSED = 0;\n native_int count_flag = -1;\n native_int stop = 0;\n bool rest UNUSED = false;\n bool tainted UNUSED = false;\n bool untrusted UNUSED = false;\n bool ascii_encoding = false;\n bool utf8_encoding = false;\n bool string_encoding = false;\n\n String* string_value = 0;\n std::string str(\"\");\n\n \/\/ Use information we have to reduce repeated allocation.\n str.reserve(array_size * 4);\n\n if(directives->byte_size() == 0) ascii_encoding = true;\n if(CBOOL(directives->tainted_p(state))) tainted = true;\n if(CBOOL(directives->untrusted_p(state))) untrusted = true;\n%%{\n\n machine pack;\n\n include \"pack.rl\";\n\n}%%\n\n if(en_main) {\n \/\/ do nothing\n }\n\n return force_as(Primitives::failure());\n }\n}\n","old_contents":"\/* This file was generated by Ragel. Your edits will be lost.\n *\n * This is a state machine implementation of Array#pack.\n * See http:\/\/github.com\/rubinius\/rapa.\n *\n * vim: filetype=cpp\n *\/\n\n#include \n#include \n\n#include \"machine\/config.h\"\n\n#include \"alloc.hpp\"\n#include \"memory.hpp\"\n#include \"object_utils.hpp\"\n#include \"on_stack.hpp\"\n#include \"state.hpp\"\n#include \"vm.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/byte_array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/encoding.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n\n#ifdef RBX_WINDOWS\n#include \n#endif\n\nnamespace rubinius {\n namespace pack {\n inline Object* to_int(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->symbol(\"pack_to_int\"), args);\n }\n\n#define BITS_LONG (RBX_SIZEOF_LONG * 8)\n\n inline long check_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_LONG);\n return big->to_long();\n }\n }\n\n#define BITS_64 (64)\n\n inline long long check_long_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_64);\n return big->to_long_long();\n }\n }\n\n inline Object* to_f(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->symbol(\"pack_to_float\"), args);\n }\n\n inline String* encoding_string(STATE, Object* obj, const char* coerce_name)\n {\n String* s = try_as(obj);\n if(s) return s;\n\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n std::string coerce_method(\"pack_\");\n coerce_method += coerce_name;\n Object* result = G(rubinius)->send(state, state->symbol(coerce_method.c_str()), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n inline uint16_t swap_2bytes(uint16_t x) {\n return (((x & 0x00ff)<<8) | ((x & 0xff00)>>8));\n }\n\n inline uint32_t swap_4bytes(uint32_t x) {\n return (((x & 0x000000ff) << 24)\n |((x & 0xff000000) >> 24)\n |((x & 0x0000ff00) << 8)\n |((x & 0x00ff0000) >> 8));\n }\n\n inline uint64_t swap_8bytes(uint64_t x) {\n return (((x & 0x00000000000000ffLL) << 56)\n |((x & 0xff00000000000000LL) >> 56)\n |((x & 0x000000000000ff00LL) << 40)\n |((x & 0x00ff000000000000LL) >> 40)\n |((x & 0x0000000000ff0000LL) << 24)\n |((x & 0x0000ff0000000000LL) >> 24)\n |((x & 0x00000000ff000000LL) << 8)\n |((x & 0x000000ff00000000LL) >> 8));\n }\n\n inline void swap_float(std::string& str, float value) {\n uint32_t x;\n\n memcpy(&x, &value, sizeof(float));\n x = swap_4bytes(x);\n\n str.append((const char*)&x, sizeof(uint32_t));\n }\n\n inline void swap_double(std::string& str, double value) {\n uint64_t x;\n\n memcpy(&x, &value, sizeof(double));\n x = swap_8bytes(x);\n\n str.append((const char*)&x, sizeof(uint64_t));\n }\n\n inline void double_element(std::string& str, double value) {\n str.append((const char*)&value, sizeof(double));\n }\n\n inline void float_element(std::string& str, float value) {\n str.append((const char*)&value, sizeof(float));\n }\n\n inline void short_element(std::string& str, int16_t value) {\n str.append((const char*)&value, sizeof(int16_t));\n }\n\n inline void int_element(std::string& str, int32_t value) {\n str.append((const char*)&value, sizeof(int32_t));\n }\n\n inline void long_element(std::string& str, int64_t value) {\n str.append((const char*)&value, sizeof(int64_t));\n }\n\n inline int32_t int32_element(STATE, Integer* value) {\n if(value->fixnum_p()) {\n long l = as(value)->to_long();\n if(l > INT32_MAX || l < INT32_MIN) {\n Exception::raise_range_error(state, \"Fixnum value out of range of int32\");\n }\n return l;\n } else {\n Bignum* big = as(value);\n big->verify_size(state, 32);\n return big->to_int();\n }\n }\n\n#define QUOTABLE_PRINTABLE_BUFSIZE 1024\n\n static const char hex_table[] = \"0123456789ABCDEF\";\n void quotable_printable(String* s, std::string& str, int count) {\n char buf[QUOTABLE_PRINTABLE_BUFSIZE];\n\n uint8_t* b = s->byte_address();\n uint8_t* e = b + s->byte_size();\n int i = 0, n = 0, prev = -1;\n\n for(; b < e; b++) {\n if((*b > 126) || (*b < 32 && *b != '\\n' && *b != '\\t') || (*b == '=')) {\n buf[i++] = '=';\n buf[i++] = hex_table[*b >> 4];\n buf[i++] = hex_table[*b & 0x0f];\n n += 3;\n prev = -1;\n } else if(*b == '\\n') {\n if(prev == ' ' || prev == '\\t') {\n buf[i++] = '=';\n buf[i++] = *b;\n }\n buf[i++] = *b;\n n = 0;\n prev = *b;\n } else {\n buf[i++] = *b;\n n++;\n prev = *b;\n }\n\n if(n > count) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n n = 0;\n prev = '\\n';\n }\n\n if(i > QUOTABLE_PRINTABLE_BUFSIZE - 5) {\n str.append(buf, i);\n i = 0;\n }\n }\n\n if(n > 0) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n }\n\n if(i > 0) {\n str.append(buf, i);\n }\n }\n\n static const char uu_table[] =\n \"`!\\\"#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_\";\n static const char b64_table[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n\n#define b64_uu_byte1(t, b) t[077 & (*b >> 2)]\n#define b64_uu_byte2(t, b, c) t[077 & (((*b << 4) & 060) | ((c >> 4) & 017))]\n#define b64_uu_byte3(t, b, c) t[077 & (((b[1] << 2) & 074) | ((c >> 6) & 03))];\n#define b64_uu_byte4(t, b) t[077 & b[2]];\n\n void b64_uu_encode(String* s, std::string& str,\n native_int count, native_int count_flag,\n const char* table, int padding, bool encode_size)\n {\n char *buf = ALLOCA_N(char, count * 4 \/ 3 + 6);\n native_int i, chars, line, total = s->byte_size();\n uint8_t* b = s->byte_address();\n\n for(i = 0; total > 0; i = 0, total -= line) {\n line = total > count ? count : total;\n\n if(encode_size) buf[i++] = line + ' ';\n\n for(chars = line; chars >= 3; chars -= 3, b += 3) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, b[2]);\n buf[i++] = b64_uu_byte4(table, b);\n }\n\n if(chars == 2) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, '\\0');\n buf[i++] = padding;\n } else if(chars == 1) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, '\\0');\n buf[i++] = padding;\n buf[i++] = padding;\n }\n\n b += chars;\n if(encode_size || (!encode_size && count_flag > 0)) {\n buf[i++] = '\\n';\n }\n str.append(buf, i);\n }\n }\n\n void utf8_encode(STATE, std::string& str, Integer* value) {\n int32_t v = int32_element(state, value);\n\n if(!(v & ~0x7f)) {\n str.push_back(v);\n } else if(!(v & ~0x7ff)) {\n str.push_back(((v >> 6) & 0xff) | 0xc0);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0xffff)) {\n str.push_back(((v >> 12) & 0xff) | 0xe0);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x1fffff)) {\n str.push_back(((v >> 18) & 0xff) | 0xf0);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x3ffffff)) {\n str.push_back(((v >> 24) & 0xff) | 0xf8);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x7fffffff)) {\n str.push_back(((v >> 30) & 0xff) | 0xfc);\n str.push_back(((v >> 24) & 0x3f) | 0x80);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else {\n Exception::raise_range_error(state, \"pack('U') value out of range\");\n }\n }\n\n void ber_encode(STATE, std::string& str, Integer* value) {\n if(!value->positive_p()) {\n Exception::raise_argument_error(state, \"cannot BER compress a negative number\");\n }\n\n std::string buf;\n\n if(try_as(value)) {\n Fixnum* base = Fixnum::from(128);\n while(try_as(value)) {\n Array* ary;\n if(value->fixnum_p()) {\n ary = as(value)->divmod(state, base);\n } else {\n ary = as(value)->divmod(state, base);\n }\n buf.push_back(as(ary->get(state, 1))->to_native() | 0x80);\n value = as(ary->get(state, 0));\n }\n }\n\n long v = value->to_long();\n\n while(v) {\n buf.push_back((v & 0x7f) | 0x80);\n v >>= 7;\n }\n\n if(buf.size() > 0) {\n char* a = const_cast(buf.c_str());\n char* b = a + buf.size() - 1;\n\n \/\/ clear continue bit\n *a &= 0x7f;\n\n \/\/ reverse string\n while(a < b) {\n int k = *a;\n *a++ = *b;\n *b-- = k;\n }\n\n str.append(buf.c_str(), buf.size());\n } else {\n str.push_back(0);\n }\n }\n\n inline native_int bit_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count - size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void bit_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n byte |= *b & 1;\n if(i & 7) {\n byte <<= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte <<= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n void bit_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(*b & 1)\n byte |= 128;\n\n if(i & 7) {\n byte >>= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte >>= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n inline native_int hex_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count + 1) \/ 2 - (size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void hex_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= ((*b & 15) + 9) & 15;\n } else {\n byte |= *b & 15;\n }\n\n if(i & 1) {\n byte <<= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n void hex_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= (((*b & 15) + 9) & 15) << 4;\n } else {\n byte |= (*b & 15) << 4;\n }\n\n if(i & 1) {\n byte >>= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n ByteArray* prepare_directives(STATE, String* directives,\n const char** p, const char** pe)\n {\n native_int size = directives->byte_size();\n ByteArray* ba = ByteArray::create_pinned(state, size + 1);\n char* b = reinterpret_cast(ba->raw_bytes());\n char* d = reinterpret_cast(directives->byte_address());\n int i = 0, j = 0;\n\n while(i < size) {\n switch(d[i]) {\n case 0:\n case ' ':\n case '\\t':\n case '\\n':\n case '\\v':\n case '\\f':\n case '\\r':\n i++;\n break;\n case '#':\n while(++i < size && d[i] != '\\n')\n ; \/\/ ignore\n if(d[i] == '\\n') i++;\n break;\n default:\n b[j++] = d[i++];\n break;\n }\n }\n\n *p = const_cast(b);\n *pe = *p + j;\n\n return ba;\n }\n\n void exceeds_length_of_string(STATE, native_int count) {\n std::ostringstream msg;\n msg << \"X\" << count << \" exceeds length of string\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n\n void non_native_error(STATE, const char c) {\n std::ostringstream msg;\n msg << \"'\" << c << \"' allowed only after types sSiIlL\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n }\n\n\n\/\/ Pack Float elements\n#define pack_float_elements(format) pack_elements(Float, pack::to_f, format)\n\n#define pack_double_le pack_float_elements(pack_double_element_le)\n#define pack_double_be pack_float_elements(pack_double_element_be)\n\n#define pack_float_le pack_float_elements(pack_float_element_le)\n#define pack_float_be pack_float_elements(pack_float_element_be)\n\n\/\/ Pack Integer elements\n#define pack_integer_elements(format) pack_elements(Integer, pack::to_int, format)\n\n#define pack_byte_element(v) str.push_back(pack::check_long(state, v))\n#define pack_byte pack_integer_elements(pack_byte_element)\n\n#define pack_short_le pack_integer_elements(pack_short_element_le)\n#define pack_short_be pack_integer_elements(pack_short_element_be)\n\n#define pack_int_le pack_integer_elements(pack_int_element_le)\n#define pack_int_be pack_integer_elements(pack_int_element_be)\n\n#define pack_long_le pack_integer_elements(pack_long_element_le)\n#define pack_long_be pack_integer_elements(pack_long_element_be)\n\n\/\/ Pack UTF-8 elements\n#define pack_utf8_element(v) pack::utf8_encode(state, str, v)\n#define pack_utf8 pack_elements(Integer, pack::to_int, pack_utf8_element)\n\n\/\/ Pack BER-compressed integers\n#define pack_ber_element(v) pack::ber_encode(state, str, v)\n#define pack_ber pack_elements(Integer, pack::to_int, pack_ber_element)\n\n\/\/ Wraps the logic for iterating over a number of elements,\n\/\/ coercing them to the correct class and formatting them\n\/\/ for the output string.\n#define pack_elements(T, coerce, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n format(value); \\\n }\n\n\/\/ Macros that depend on endianness\n#ifdef RBX_LITTLE_ENDIAN\n\n# define pack_double_element_le(v) (pack::double_element(str, (v)->val))\n# define pack_double_element_be(v) (pack::swap_double(str, (v)->val))\n# define pack_double pack_double_le\n\n# define pack_float_element_le(v) (pack::float_element(str, (v)->val))\n# define pack_float_element_be(v) (pack::swap_float(str, (v)->val))\n# define pack_float pack_float_le\n\n# define pack_short_element_le(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short_element_be(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short pack_short_le\n\n# define pack_int_element_le(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int_element_be(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int pack_int_le\n\n# define pack_long_element_le(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long_element_be(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long pack_long_le\n\n#else \/\/ Big endian\n\n# define pack_double_element_le(v) (pack::swap_double(str, (v)->val))\n# define pack_double_element_be(v) (pack::double_element(str, (v)->val))\n# define pack_double pack_double_be\n\n# define pack_float_element_le(v) (pack::swap_float(str, (v)->val))\n# define pack_float_element_be(v) (pack::float_element(str, (v)->val))\n# define pack_float pack_float_be\n\n# define pack_short_element_le(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short_element_be(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short pack_short_be\n\n# define pack_int_element_le(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int_element_be(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int pack_int_be\n\n# define pack_long_element_le(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long_element_be(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long pack_long_be\n\n#endif\n\n\n String* Array::pack(STATE, String* directives) {\n \/\/ Ragel-specific variables\n const char* p;\n const char* pe;\n ByteArray* d = pack::prepare_directives(state, directives, &p, &pe);\n const char *eof = pe;\n int cs;\n\n \/\/ pack-specific variables\n Array* self = this;\n OnStack<2> sv(state, self, d);\n\n native_int array_size = self->size();\n native_int index = 0;\n native_int count UNUSED = 0;\n native_int count_flag = -1;\n native_int stop = 0;\n bool rest UNUSED = false;\n bool tainted UNUSED = false;\n bool untrusted UNUSED = false;\n bool ascii_encoding = false;\n bool utf8_encoding = false;\n bool string_encoding = false;\n\n String* string_value = 0;\n std::string str(\"\");\n\n \/\/ Use information we have to reduce repeated allocation.\n str.reserve(array_size * 4);\n\n if(directives->byte_size() == 0) ascii_encoding = true;\n if(CBOOL(directives->tainted_p(state))) tainted = true;\n if(CBOOL(directives->untrusted_p(state))) untrusted = true;\n%%{\n\n machine pack;\n\n include \"pack.rl\";\n\n}%%\n\n if(en_main) {\n \/\/ do nothing\n }\n\n return force_as(Primitives::failure());\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f74a29383d81f85978b831ca6e1dbf6425f095e4","subject":"some helpful printfs on error (for now)","message":"some helpful printfs on error (for now)\n","repos":"jneen\/tnetstrings-ruby,jneen\/tnetstrings-ruby","old_file":"ext\/tnetstrings.c.rl","new_file":"ext\/tnetstrings.c.rl","new_contents":"#include \n#include \n#include \n#include \n#include \"tnetstrings.h\"\n\n%%{\n machine tnetstrings;\n access parser->;\n\n action mark_ends {\n \/\/ this marks the start of the payload -\n \/\/ move ahead 2 for the colon and the type spec.\n parser->payload = p + 2;\n\n \/\/ this is a bit hacky, but I think it's the only way to do it.\n \/\/ only now do we know where the end is, since we've parsed the payload_size.\n \/\/ This will cause EOF actions to be triggered at the end of the payload.\n \/\/ TODO: eventually, have an option to read this from a stream,\n \/\/ which is arguably the whole point.\n eof = pe = parser->payload + parser->payload_size;\n\n \/\/ assert(pe < str + size, \"Holy crap we overfloweded the buffer\");\n }\n\n action collect_payload_size {\n parser->payload_size *= 10;\n parser->payload_size += CTOI(fc);\n }\n\n # -*- boolean (!) -*- #\n action wrap_true { parser->result = TNETS_WRAP_TRUE; }\n action wrap_false { parser->result = TNETS_WRAP_FALSE; }\n\n # -*- null (~) -*- #\n action wrap_null { parser->result = Qnil; }\n\n # -*- number (#) -*- #\n action neg {\n parser->seen_neg = 1;\n }\n\n action collect_num {\n parser->num_builder *= 10;\n parser->num_builder += CTOI(fc);\n }\n\n action wrap_num {\n if (parser->seen_neg) parser->num_builder *= -1;\n parser->result = TNETS_WRAP_NUM(parser->num_builder);\n }\n\n # -*- string (,) -*- #\n action wrap_str {\n parser->result = TNETS_WRAP_STR(p+1, parser->payload_size);\n }\n\n action parse_dict { }\n action parse_arr {\n VALUE arr = TNETS_NEW_ARR;\n tnets_parser* sub_parser = tnets_parser_new();\n char* sub_data = parser->payload;\n int sub_size = parser->payload_size;\n do {\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n TNETS_ARR_PUSH(arr, sub_parser->result);\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n \/\/ reset current state and such\n tnets_parser_clear(sub_parser);\n\n } while(sub_size > 0);\n free(sub_parser);\n\n parser->result = arr;\n }\n\n action error {\n printf(\"error!\\n\"); \/\/ TODO: real error handling\n printf(\"p: [%s]\\n\", p);\n printf(\"pe: [%s]\\n\", pe);\n printf(\"str: [%s]\\n\", str);\n }\n\n # parses the size spec at the start of the payload\n tnets_size = digit+ $collect_payload_size;\n colon = ':' @mark_ends;\n\n # primitives\n tnets_num = '#' ('-' @neg)? (digit+ $collect_num) %\/wrap_num;\n tnets_str = ',' @wrap_str;\n # NB: any string that is not \"true\" will return \"false\".\n tnets_bool = '!' ('true' %\/wrap_true | !'true' %\/wrap_false);\n tnets_null = '~' %\/wrap_null;\n\n # recursive structures\n tnets_dict = '}' @parse_dict;\n tnets_arr = ']' @parse_arr;\n\n main := tnets_size colon (\n tnets_dict |\n tnets_arr |\n tnets_num |\n tnets_str |\n tnets_bool |\n tnets_null\n ) @err(error);\n}%%\n\n%% write data;\n\nint tnets_parser_init(tnets_parser *parser) {\n %% write init;\n}\n\nint tnets_parser_clear(tnets_parser *parser) {\n tnets_parser_init(parser);\n parser->num_builder = 0;\n parser->seen_neg = 0;\n parser->result = TNETS_WRAP_NULL;\n parser->payload = NULL;\n parser->payload_size = 0;\n}\n\nint tnets_parser_chunk(tnets_parser *parser, char *str, int size) {\n char *p = str;\n \/\/ pe gets re-set once we've parsed the length.\n \/\/ set to 10 characters here because that's the maximum\n \/\/ length of the length spec.\n char *pe = p + 11;\n char *eof;\n\n %% write exec;\n\nprintf(\"%s\\n\", RSTRING_PTR(rb_funcall(parser->result, rb_intern(\"inspect\"), 0)));\n return 0;\n}\n\ntnets_parser *tnets_parser_new(void) {\n tnets_parser *parser = calloc(sizeof(tnets_parser), 1);\n tnets_parser_init(parser);\n return parser;\n}\n\ntnets_parser *parse_str(char *str, int size) {\n tnets_parser *parser = tnets_parser_new();\n tnets_parser_chunk(parser, str, size);\n return parser;\n}\n\nVALUE rb_parse_tnets(VALUE self, VALUE rbstr) {\n char *tnets = RSTRING_PTR(rbstr);\n int len = RSTRING_LEN(rbstr);\n\n tnets_parser *parser = parse_str(RSTRING_PTR(rbstr), len);\n\n VALUE result = parser->result;\n free(parser);\n\n return result;\n}\n\nvoid Init_tnetstrings() {\n VALUE module = rb_define_module(\"TnetstringsCMethods\");\n\n rb_define_method(module, \"c_parse\", rb_parse_tnets, 1);\n}\n","old_contents":"#include \n#include \n#include \n#include \n#include \"tnetstrings.h\"\n\n%%{\n machine tnetstrings;\n access parser->;\n\n action mark_ends {\n \/\/ this marks the start of the payload -\n \/\/ move ahead 2 for the colon and the type spec.\n parser->payload = p + 2;\n\n \/\/ this is a bit hacky, but I think it's the only way to do it.\n \/\/ only now do we know where the end is, since we've parsed the payload_size.\n \/\/ This will cause EOF actions to be triggered at the end of the payload.\n \/\/ TODO: eventually, have an option to read this from a stream,\n \/\/ which is arguably the whole point.\n eof = pe = parser->payload + parser->payload_size;\n\n \/\/ assert(pe < str + size, \"Holy crap we overfloweded the buffer\");\n }\n\n action collect_payload_size {\n parser->payload_size *= 10;\n parser->payload_size += CTOI(fc);\n }\n\n # -*- boolean (!) -*- #\n action wrap_true { parser->result = TNETS_WRAP_TRUE; }\n action wrap_false { parser->result = TNETS_WRAP_FALSE; }\n\n # -*- null (~) -*- #\n action wrap_null { parser->result = Qnil; }\n\n # -*- number (#) -*- #\n action neg {\n parser->seen_neg = 1;\n }\n\n action collect_num {\n parser->num_builder *= 10;\n parser->num_builder += CTOI(fc);\n }\n\n action wrap_num {\n if (parser->seen_neg) parser->num_builder *= -1;\n parser->result = TNETS_WRAP_NUM(parser->num_builder);\n }\n\n # -*- string (,) -*- #\n action wrap_str {\n parser->result = TNETS_WRAP_STR(p+1, parser->payload_size);\n }\n\n action parse_dict { }\n action parse_arr {\n VALUE arr = TNETS_NEW_ARR;\n tnets_parser* sub_parser = tnets_parser_new();\n char* sub_data = parser->payload;\n int sub_size = parser->payload_size;\n do {\n tnets_parser_chunk(sub_parser, sub_data, sub_size);\n TNETS_ARR_PUSH(arr, sub_parser->result);\n\n sub_data += (sub_parser->payload_size + 2 + 1);\n sub_size -= (sub_parser->payload_size + 2 + 1);\n \/\/ reset current state and such\n tnets_parser_clear(sub_parser);\n\n } while(sub_size > 0);\n free(sub_parser);\n\n parser->result = arr;\n }\n\n action error {\n printf(\"error!\\n\"); \/\/ TODO: real error handling\n }\n\n # parses the size spec at the start of the payload\n tnets_size = digit+ $collect_payload_size;\n colon = ':' @mark_ends;\n\n # primitives\n tnets_num = '#' ('-' @neg)? (digit+ $collect_num) %\/wrap_num;\n tnets_str = ',' @wrap_str;\n # NB: any string that is not \"true\" will return \"false\".\n tnets_bool = '!' ('true' %\/wrap_true | !'true' %\/wrap_false);\n tnets_null = '~' %\/wrap_null;\n\n # recursive structures\n tnets_dict = '}' @parse_dict;\n tnets_arr = ']' @parse_arr;\n\n main := tnets_size colon (\n tnets_dict |\n tnets_arr |\n tnets_num |\n tnets_str |\n tnets_bool |\n tnets_null\n ) @err(error);\n}%%\n\n%% write data;\n\nint tnets_parser_init(tnets_parser *parser) {\n %% write init;\n}\n\nint tnets_parser_clear(tnets_parser *parser) {\n tnets_parser_init(parser);\n parser->num_builder = 0;\n parser->seen_neg = 0;\n parser->result = TNETS_WRAP_NULL;\n parser->payload = NULL;\n parser->payload_size = 0;\n}\n\nint tnets_parser_chunk(tnets_parser *parser, char *str, int size) {\n char *p = str;\n \/\/ pe gets re-set once we've parsed the length.\n \/\/ set to 10 characters here because that's the maximum\n \/\/ length of the length spec.\n char *pe = p + 11;\n char *eof;\n\n %% write exec;\n\nprintf(\"%s\\n\", RSTRING_PTR(rb_funcall(parser->result, rb_intern(\"inspect\"), 0)));\n return 0;\n}\n\ntnets_parser *tnets_parser_new(void) {\n tnets_parser *parser = calloc(sizeof(tnets_parser), 1);\n tnets_parser_init(parser);\n return parser;\n}\n\ntnets_parser *parse_str(char *str, int size) {\n tnets_parser *parser = tnets_parser_new();\n tnets_parser_chunk(parser, str, size);\n return parser;\n}\n\nVALUE rb_parse_tnets(VALUE self, VALUE rbstr) {\n char *tnets = RSTRING_PTR(rbstr);\n int len = RSTRING_LEN(rbstr);\n\n tnets_parser *parser = parse_str(RSTRING_PTR(rbstr), len);\n\n VALUE result = parser->result;\n free(parser);\n\n return result;\n}\n\nvoid Init_tnetstrings() {\n VALUE module = rb_define_module(\"TnetstringsCMethods\");\n\n rb_define_method(module, \"c_parse\", rb_parse_tnets, 1);\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f772d941838236e2d2c6c55762780f6d09265c9e","subject":"added documentation to lexer","message":"added documentation to lexer\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/lexer.h.rl","new_file":"src\/hext\/lexer.h.rl","new_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/lexer-util.h\"\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\n\/\/\/ lexer contains the ragel state machine and shields the user from its\n\/\/\/ details.\nclass lexer\n{\npublic:\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg);\n };\n\n \/\/\/ Setup ragel\n lexer(const char * begin, const char * end);\n\n \/\/\/ Throws lexer::lex_error on invalid input (by calling lexer::throw_error)\n std::vector lex();\n\nprivate:\n \/\/\/ Print diagnostics and throw lexer::lex_error.\n void throw_error() const;\n\n \/\/\/ A pointer to the beginning of the overall input is needed to provide\n \/\/\/ good error diagnostics.\n const char * p_begin;\n\n \/\/\/ ragel's runtime state\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","old_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/lexer-util.h\"\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\nclass lexer\n{\npublic:\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg);\n };\n\n lexer(const char * begin, const char * end);\n\n std::vector lex();\n\nprivate:\n void throw_error() const;\n\n const char * p_begin;\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"bc94319654680b66ac846b13c97272072f1ea100","subject":"handle EOF on one list branch","message":"handle EOF on one list branch\n","repos":"nbargnesi\/bel-parser,OpenBEL\/bel_parser,nbargnesi\/bel-parser,OpenBEL\/bel_parser,nbargnesi\/bel-parser,OpenBEL\/bel_parser","old_file":"lib\/bel_parser\/parsers\/common\/list.rl","new_file":"lib\/bel_parser\/parsers\/common\/list.rl","new_contents":"# begin: ragel\n=begin\n%%{\n machine bel;\n\n include 'common.rl';\n include 'identifier.rl';\n include 'string.rl';\n\n action start_list {\n $stderr.puts \"LIST start_list\"\n @list_opened = true\n @incomplete[:list] = list()\n }\n\n action stop_list {\n $stderr.puts \"LIST stop_list\"\n @list_closed = true\n }\n\n action add_string {\n $stderr.puts \"LIST add_string\"\n string = @buffers.delete(:string)\n item = list_item(string, complete: string.complete)\n @incomplete[:list] <<= item\n }\n\n action add_ident {\n $stderr.puts \"LIST add_ident\"\n ident = @buffers.delete(:ident)\n item = list_item(ident, complete: ident.complete)\n @incomplete[:list] <<= item\n }\n\n action list_end {\n $stderr.puts \"LIST list_end\"\n if @list_opened && @list_closed\n list = @incomplete.delete(:list)\n list.complete = true\n elsif !@list_closed\n list = @incomplete.delete(:list)\n list.complete = false\n end\n @buffers[:list] = list\n }\n\n action a_list_eof {\n $stderr.puts \"LIST a_list_eof\"\n list = @incomplete.delete(:list)\n string = @buffers.delete(:string)\n unless string.nil?\n item = list_item(string, complete: string.complete)\n list <<= item\n end\n ident = @buffers.delete(:ident)\n unless ident.nil?\n item = list_item(ident, complete: ident.complete)\n list <<= item\n end\n if @list_opened && @list_closed\n list.complete = true\n else\n list.complete = false\n end\n @buffers[:list] = list\n }\n\n action list_node_eof {\n $stderr.puts \"LIST list_node_eof\"\n list = @incomplete.delete(:list)\n string = @buffers.delete(:string)\n item = list_item(string, complete: string.complete)\n list <<= item\n list.complete = false\n yield list\n }\n\n action yield_list {\n $stderr.puts \"LIST yield_list\"\n yield @buffers[:list]\n }\n\n START_LIST = '{' SP* >start_list;\n END_LIST = '}' %stop_list;\n\n string_item =\n a_string\n %add_string\n ;\n\n ident_item =\n an_ident\n %add_ident\n ;\n\n item =\n string_item |\n ident_item\n ;\n\n list_item_0 =\n item\n ;\n\n list_item_n =\n COMMA_DELIM\n item\n ;\n\n items =\n list_item_0\n list_item_n*\n SP*\n ;\n\n a_list =\n START_LIST\n items\n END_LIST\n %list_end\n @eof(a_list_eof)\n ;\n\n list_node :=\n START_LIST\n items?\n @eof(list_node_eof)\n END_LIST?\n @eof(list_node_eof)\n NL?\n %list_end\n %yield_list\n ;\n}%%\n=end\n# end: ragel\n\nrequire_relative '..\/ast\/node'\nrequire_relative '..\/mixin\/buffer'\nrequire_relative '..\/nonblocking_io_wrapper'\n\nmodule BELParser\n module Parsers\n module Common\n module List\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def parse(content)\n return nil unless content\n\n Parser.new(content).each do |obj|\n yield obj\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n include BELParser::Parsers::Buffer\n include BELParser::Parsers::AST::Sexp\n\n def initialize(content)\n @content = content\n $stderr.puts \"\\n---\\ncontent: '\" + @content + \"'\"\n # begin: ragel\n %% write data;\n # end: ragel\n end\n\n def each\n @buffers = {}\n @incomplete = {}\n @list_opened = false\n @list_closed = false\n data = @content.unpack('C*')\n p = 0\n pe = data.length\n eof = data.length\n\n # begin: ragel\n %% write init;\n %% write exec;\n # end: ragel\n end\n end\n end\n end\n end\nend\n\nif __FILE__ == $0\n $stdin.each_line do |line|\n BELParser::Parsers::Common::List.parse(line) { |obj|\n puts obj.inspect\n }\n end\nend\n\n# vim: ft=ruby ts=2 sw=2:\n# encoding: utf-8\n","old_contents":"# begin: ragel\n=begin\n%%{\n machine bel;\n\n include 'common.rl';\n include 'identifier.rl';\n include 'string.rl';\n\n action start_list {\n $stderr.puts \"LIST start_list\"\n @list_opened = true\n @incomplete[:list] = list()\n }\n\n action stop_list {\n $stderr.puts \"LIST stop_list\"\n @list_closed = true\n }\n\n action add_string {\n $stderr.puts \"LIST add_string\"\n string = @buffers.delete(:string)\n item = list_item(string, complete: string.complete)\n @incomplete[:list] <<= item\n }\n\n action add_ident {\n $stderr.puts \"LIST add_ident\"\n ident = @buffers.delete(:ident)\n item = list_item(ident, complete: ident.complete)\n @incomplete[:list] <<= item\n }\n\n action list_end {\n $stderr.puts \"LIST list_end\"\n if @list_opened && @list_closed\n list = @incomplete.delete(:list)\n list.complete = true\n elsif !@list_closed\n list = @incomplete.delete(:list)\n list.complete = false\n end\n @buffers[:list] = list\n }\n\n action list_node_eof {\n $stderr.puts \"LIST list_node_eof\"\n list = @incomplete.delete(:list)\n string = @buffers.delete(:string)\n item = list_item(string, complete: string.complete)\n list <<= item\n list.complete = false\n yield list\n }\n\n action yield_list {\n $stderr.puts \"LIST yield_list\"\n yield @buffers[:list]\n }\n\n START_LIST = '{' SP* >start_list;\n END_LIST = '}' %stop_list;\n\n string_item =\n a_string\n %add_string\n ;\n\n ident_item =\n an_ident\n %add_ident\n ;\n\n item =\n string_item |\n ident_item\n ;\n\n list_item_0 =\n item\n ;\n\n list_item_n =\n COMMA_DELIM\n item\n ;\n\n items =\n list_item_0\n list_item_n*\n SP*\n ;\n\n a_list =\n START_LIST\n items\n END_LIST\n %list_end\n ;\n\n list_node :=\n START_LIST\n items?\n @eof(list_node_eof)\n END_LIST?\n @eof(list_node_eof)\n NL?\n %list_end\n %yield_list\n ;\n}%%\n=end\n# end: ragel\n\nrequire_relative '..\/ast\/node'\nrequire_relative '..\/mixin\/buffer'\nrequire_relative '..\/nonblocking_io_wrapper'\n\nmodule BELParser\n module Parsers\n module Common\n module List\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def parse(content)\n return nil unless content\n\n Parser.new(content).each do |obj|\n yield obj\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n include BELParser::Parsers::Buffer\n include BELParser::Parsers::AST::Sexp\n\n def initialize(content)\n @content = content\n $stderr.puts \"\\n---\\ncontent: '\" + @content + \"'\"\n # begin: ragel\n %% write data;\n # end: ragel\n end\n\n def each\n @buffers = {}\n @incomplete = {}\n @list_opened = false\n @list_closed = false\n data = @content.unpack('C*')\n p = 0\n pe = data.length\n eof = data.length\n\n # begin: ragel\n %% write init;\n %% write exec;\n # end: ragel\n end\n end\n end\n end\n end\nend\n\nif __FILE__ == $0\n $stdin.each_line do |line|\n BELParser::Parsers::Common::List.parse(line) { |obj|\n puts obj.inspect\n }\n end\nend\n\n# vim: ft=ruby ts=2 sw=2:\n# encoding: utf-8\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"db0362c25cd52674681468d6e46f962a295482f1","subject":"Fixed constants starting with an underbar","message":"Fixed constants starting with an underbar\n","repos":"gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil","old_file":"Source\/Tranquil\/lex.rl","new_file":"Source\/Tranquil\/lex.rl","new_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\n#define PushStr(dblQuot, rstr) \\\n [strings addObject:[NSDictionary dictionaryWithObjectsAndKeys: \\\n [NSNumber numberWithBool:dblQuot], @\"dblQuot\", \\\n [NSNumber numberWithBool:rstr], @\"isRstr\", \\\n [NSMutableString string], @\"value\", nil]];\n#define PopStr() ({ id last = [Str() retain]; [strings removeLastObject]; [last autorelease]; })\n#define Str() [[strings lastObject] objectForKey:@\"value\"]\n#define IsDblQuot() [[[strings lastObject] objectForKey:@\"dblQuot\"] boolValue]\n#define IsRstr() [[[strings lastObject] objectForKey:@\"isRstr\"] boolValue]\n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n NSError *syntaxError;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n int tokenId_ = tokenId; \\\n id val_ = val; \\\n \/*NSLog(@\"emitting %d = '%@' on line: %d\", tokenId, val_, parserState.currentLine); *\/\\\n Parse(parser, tokenId_, [TQToken withId:tokenId value:val_ line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken(tokenId, [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) NSUInteger id, lineNumber;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.lineNumber = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n lGuillemet = 0xC2 0xAB; # \u00ab\n rGuillemet = 0xC2 0xBB; # \u00bb\n specialChar = 0xC2 | '\"' | \"'\" | '.' | ',' | ';' | ':' | '|' | '#' | '@' | '~' | '`' | '{' | '}' | '[' | ']' | '(' | ')' | '+' | '-' | '*' | '\/' | '%' | '=' | '<' | '>' | '^' | '\\\\' | '\\r' | '\\n' | space;\n\n char = (any - specialChar) | (0xC2 ^(0xAB|0xBB));\n constant = '_'* uupper char*;\n identifier = (char -- (uupper|udigit)) char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n simpleStr = ('\"' (any - '\"')* '\"') | (\"'\" (any - \"'\")* \"'\");\n constStr = \"#\" (simpleStr | (char | [:@#~+\\-*\/%=<>^])+);\n selector = char* \":\";\n\n regexCont = (ualnum | ascii) - '\/' - '\\\\';\n\nstring := |*\n '\\n' => { [Str() appendString:@\"\\n\"]; IncrementLine(); };\n '\\\\n' => { [Str() appendString:@\"\\n\"]; };\n '\\\\t' => { [Str() appendString:@\"\\t\"]; };\n '\\\\r' => { [Str() appendString:@\"\\r\"]; };\n '\\\\\"' => { [Str() appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [Str() appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [Str() appendString:@\"\\\\\"]; };\n \"\\\\\" lGuillemet => { [Str() appendString:@\"\u00ab\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [Str() appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" any => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n\n lGuillemet => { _EmitToken(IsRstr() ? MSTR : LSTR, Str()); fret; };\n '\"' term => {\n if(IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTRNL : STRNL, PopStr());\n BacktrackTerm();\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n '\"' => {\n if(IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTR : STR, PopStr());\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n \"'\" term => {\n if(!IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTRNL : STRNL, PopStr());\n BacktrackTerm();\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n \"'\" => {\n if(!IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTR : STR, PopStr());\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n\n any => { [Str() appendString:NSStr(0, 0)]; };\n*|;\n\nregex := |*\n '\\n' => { [Str() appendString:@\"\\n\"]; IncrementLine(); };\n \"\\\\\/\" => { [Str() appendString:@\"\\\\\/\"]; };\n \"\\\\\" => { [Str() appendString:@\"\\\\\"]; };\n regexCont => { [Str() appendString:NSStr(0, 0)]; };\n \"\/\" [im]* term => { [Str() appendString:@\"\/\"]; _EmitToken(REGEXNL, PopStr());\n BacktrackTerm(); fret; };\n \"\/\" [im]* => { [Str() appendString:@\"\/\"]; _EmitToken(REGEX, PopStr()); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else {\n PushStr(false, false);\n [Str() appendString:@\"\/\"];\n fcall regex;\n }\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"@\" => { EmitToken(ATMARK); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"do\" term? => { EmitToken(DO); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { PushStr(YES, NO); fcall string; };\n \"'\" => { PushStr(NO, NO); fcall string; };\n rGuillemet => {\n BOOL dbl = IsDblQuot();\n PopStr();\n PushStr(dbl, YES);\n fcall string;\n };\n\n \".\" => { EmitToken(PERIOD); };\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableArray *strings = [NSMutableArray array];\n\n unsigned char *temp1, *temp2;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new], nil\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n _EmitToken(0, @\"EOF\");\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = parserState.syntaxError;\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","old_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\n#define PushStr(dblQuot, rstr) \\\n [strings addObject:[NSDictionary dictionaryWithObjectsAndKeys: \\\n [NSNumber numberWithBool:dblQuot], @\"dblQuot\", \\\n [NSNumber numberWithBool:rstr], @\"isRstr\", \\\n [NSMutableString string], @\"value\", nil]];\n#define PopStr() ({ id last = [Str() retain]; [strings removeLastObject]; [last autorelease]; })\n#define Str() [[strings lastObject] objectForKey:@\"value\"]\n#define IsDblQuot() [[[strings lastObject] objectForKey:@\"dblQuot\"] boolValue]\n#define IsRstr() [[[strings lastObject] objectForKey:@\"isRstr\"] boolValue]\n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n NSError *syntaxError;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n int tokenId_ = tokenId; \\\n id val_ = val; \\\n \/*NSLog(@\"emitting %d = '%@' on line: %d\", tokenId, val_, parserState.currentLine); *\/\\\n Parse(parser, tokenId_, [TQToken withId:tokenId value:val_ line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken(tokenId, [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) NSUInteger id, lineNumber;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.lineNumber = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n lGuillemet = 0xC2 0xAB; # \u00ab\n rGuillemet = 0xC2 0xBB; # \u00bb\n specialChar = 0xC2 | '\"' | \"'\" | '.' | ',' | ';' | ':' | '|' | '#' | '@' | '~' | '`' | '{' | '}' | '[' | ']' | '(' | ')' | '+' | '-' | '*' | '\/' | '%' | '=' | '<' | '>' | '^' | '\\\\' | '\\r' | '\\n' | space;\n\n char = (any - specialChar) | (0xC2 ^(0xAB|0xBB));\n constant = uupper char*;\n identifier = (char -- (uupper|udigit)) char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n simpleStr = ('\"' (any - '\"')* '\"') | (\"'\" (any - \"'\")* \"'\");\n constStr = \"#\" (simpleStr | (char | [:@#~+\\-*\/%=<>^])+);\n selector = char* \":\";\n\n regexCont = (ualnum | ascii) - '\/' - '\\\\';\n\nstring := |*\n '\\n' => { [Str() appendString:@\"\\n\"]; IncrementLine(); };\n '\\\\n' => { [Str() appendString:@\"\\n\"]; };\n '\\\\t' => { [Str() appendString:@\"\\t\"]; };\n '\\\\r' => { [Str() appendString:@\"\\r\"]; };\n '\\\\\"' => { [Str() appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [Str() appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [Str() appendString:@\"\\\\\"]; };\n \"\\\\\" lGuillemet => { [Str() appendString:@\"\u00ab\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [Str() appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" any => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n\n lGuillemet => { _EmitToken(IsRstr() ? MSTR : LSTR, Str()); fret; };\n '\"' term => {\n if(IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTRNL : STRNL, PopStr());\n BacktrackTerm();\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n '\"' => {\n if(IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTR : STR, PopStr());\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n \"'\" term => {\n if(!IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTRNL : STRNL, PopStr());\n BacktrackTerm();\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n \"'\" => {\n if(!IsDblQuot()) {\n _EmitToken(IsRstr() ? RSTR : STR, PopStr());\n fret;\n } else\n [Str() appendString:NSStr(0,0)];\n };\n\n any => { [Str() appendString:NSStr(0, 0)]; };\n*|;\n\nregex := |*\n '\\n' => { [Str() appendString:@\"\\n\"]; IncrementLine(); };\n \"\\\\\/\" => { [Str() appendString:@\"\\\\\/\"]; };\n \"\\\\\" => { [Str() appendString:@\"\\\\\"]; };\n regexCont => { [Str() appendString:NSStr(0, 0)]; };\n \"\/\" [im]* term => { [Str() appendString:@\"\/\"]; _EmitToken(REGEXNL, PopStr());\n BacktrackTerm(); fret; };\n \"\/\" [im]* => { [Str() appendString:@\"\/\"]; _EmitToken(REGEX, PopStr()); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else {\n PushStr(false, false);\n [Str() appendString:@\"\/\"];\n fcall regex;\n }\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"@\" => { EmitToken(ATMARK); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"do\" term? => { EmitToken(DO); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { PushStr(YES, NO); fcall string; };\n \"'\" => { PushStr(NO, NO); fcall string; };\n rGuillemet => {\n BOOL dbl = IsDblQuot();\n PopStr();\n PushStr(dbl, YES);\n fcall string;\n };\n\n \".\" => { EmitToken(PERIOD); };\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableArray *strings = [NSMutableArray array];\n\n unsigned char *temp1, *temp2;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new], nil\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n _EmitToken(0, @\"EOF\");\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = parserState.syntaxError;\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"ace2e888710ea8e0c5620e5a574e24654cb9dadc","subject":"fix match-regex and cap-regex containing regex-slashes","message":"fix match-regex and cap-regex containing regex-slashes\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/hext.rl","new_file":"src\/hext\/hext.rl","new_contents":"%%{\n machine hext;\n\n action error {\n throw_error();\n }\n\n cap_limit = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( alpha (alnum | '-' | '_')** );\n match_literal = ( alpha (alnum | '-' | '_' | ' ')** );\n cap_regex = ( [^\/]+* );\n match_regex = ( [^\/]+* );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n '@' >{ LX_TK_START(TK_BUILTIN); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_ATTR_NAME); }\n %{ LX_TK_STOP; }\n )\n <:\n (\n '=\"'\n (\n (\n (\n '{' >{ LX_TK_START(TK_CAP_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n cap_var** >{ LX_TK_START(TK_CAP_VAR); }\n %{ LX_TK_STOP; }\n )\n (\n '\/'\n (\n cap_regex >{ LX_TK_START(TK_CAP_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )?\n (\n '}' >{ LX_TK_START(TK_CAP_END); }\n %{ LX_TK_STOP; }\n )\n )\n |\n (\n (\n '\/'\n (\n match_regex** >{ LX_TK_START(TK_MATCH_REGEX); }\n %{ LX_TK_STOP; }\n )\n '\/'\n )\n |\n (\n match_literal** >{ LX_TK_START(TK_MATCH_LITERAL); }\n %{ LX_TK_STOP; }\n )\n )\n )\n '\"'\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' >{ LX_TK_START(TK_INDENT); }\n %{ LX_TK_STOP; }\n )*\n (\n '<' >{ LX_TK_START(TK_RULE_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n '!' >{ LX_TK_START(TK_DIRECT_DESC); }\n %{ LX_TK_STOP; }\n )?\n (\n cap_limit >{ LX_TK_START(TK_CAP_LIMIT); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_TAG_NAME); }\n %{ LX_TK_STOP; }\n )?\n attributes?\n (\n '>' >{ LX_TK_START(TK_RULE_END); }\n %{ LX_TK_STOP; }\n )\n )\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n )**\n $err(error) $\/{ LX_TK_START(TK_EOF); fbreak; };\n}%%\n","old_contents":"%%{\n machine hext;\n\n action error {\n throw_error();\n }\n\n cap_limit = ( [1-9][0-9]** );\n attr_name = ( alpha (alnum | '-' | '_')** );\n cap_var = ( alpha (alnum | '-' | '_')** );\n match_literal = ( alpha (alnum | '-' | '_' | ' ')** );\n cap_regex = ( '\/' [^\/]+* '\/' );\n match_regex = ( '\/' [^\/]+* '\/' );\n\n comment = (\n ' '*\n '#'\n (any - '\\n')*\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n );\n\n attributes = \n (\n space+ \n (\n (\n '@' >{ LX_TK_START(TK_BUILTIN); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_ATTR_NAME); }\n %{ LX_TK_STOP; }\n )\n <:\n (\n '=\"'\n (\n (\n (\n '{' >{ LX_TK_START(TK_CAP_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n cap_var** >{ LX_TK_START(TK_CAP_VAR); }\n %{ LX_TK_STOP; }\n )\n (\n cap_regex >{ LX_TK_START(TK_CAP_REGEX); }\n %{ LX_TK_STOP; }\n )?\n (\n '}' >{ LX_TK_START(TK_CAP_END); }\n %{ LX_TK_STOP; }\n )\n )\n |\n (\n (\n match_regex** >{ LX_TK_START(TK_MATCH_REGEX); }\n %{ LX_TK_STOP; }\n )\n |\n (\n match_literal** >{ LX_TK_START(TK_MATCH_LITERAL); }\n %{ LX_TK_STOP; }\n )\n )\n )\n '\"'\n )?\n )\n )+;\n\n main := \n ( \n comment\n |\n (\n (\n ' ' >{ LX_TK_START(TK_INDENT); }\n %{ LX_TK_STOP; }\n )*\n (\n '<' >{ LX_TK_START(TK_RULE_BEGIN); }\n %{ LX_TK_STOP; }\n )\n (\n '!' >{ LX_TK_START(TK_DIRECT_DESC); }\n %{ LX_TK_STOP; }\n )?\n (\n cap_limit >{ LX_TK_START(TK_CAP_LIMIT); }\n %{ LX_TK_STOP; }\n )?\n (\n attr_name >{ LX_TK_START(TK_TAG_NAME); }\n %{ LX_TK_STOP; }\n )?\n attributes?\n (\n '>' >{ LX_TK_START(TK_RULE_END); }\n %{ LX_TK_STOP; }\n )\n )\n (\n '\\n' >{ LX_TK_START(TK_NEWLINE); }\n %{ LX_TK_STOP; }\n )\n )**\n $err(error) $\/{ LX_TK_START(TK_EOF); fbreak; };\n}%%\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"14b8ed129bb7108f3a12076b16d4b6c4c899f565","subject":"Fixed \"\\\\\" escape","message":"Fixed \"\\\\\" escape\n","repos":"fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil","old_file":"Source\/Tranquil\/lex.rl","new_file":"Source\/Tranquil\/lex.rl","new_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")+ \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new]\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = [NSError errorWithDomain:kTQSyntaxErrorDomain\n code:kTQGenericError\n userInfo:[NSDictionary dictionaryWithObject:[e reason] forKey:@\"reason\"]];\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","old_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")+ \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new]\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = [NSError errorWithDomain:kTQSyntaxErrorDomain\n code:kTQGenericError\n userInfo:[NSDictionary dictionaryWithObject:[e reason] forKey:@\"reason\"]];\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"418b4ef498534f6dbf4c2a0fbfd2abe5e297dcfd","subject":"Cleaned up documentation of the XML lexer.","message":"Cleaned up documentation of the XML lexer.\n","repos":"YorickPeterse\/oga,dfockler\/oga,YorickPeterse\/oga,dfockler\/oga,YorickPeterse\/oga,altmetric\/oga,YorickPeterse\/oga,jeffreybaird\/oga,ttasanen\/oga,dfockler\/oga,jeffreybaird\/oga,altmetric\/oga,jeffreybaird\/oga,YorickPeterse\/oga,ttasanen\/oga,ttasanen\/oga,dfockler\/oga,altmetric\/oga,jeffreybaird\/oga,altmetric\/oga,dfockler\/oga,jeffreybaird\/oga,altmetric\/oga,ttasanen\/oga,ttasanen\/oga","old_file":"ext\/ragel\/base_lexer.rl","new_file":"ext\/ragel\/base_lexer.rl","new_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n #\n # ## Machine Transitions\n #\n # To transition from one machine to another always use `fnext` instead of\n # `fcall` and `fret`. This removes the need for the code to keep track of a\n # stack.\n #\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_]+;\n attribute = [a-zA-Z0-9\\-_:]+;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences would\n # actually make the rules\/actions more complex.\n #\n comment = '';\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata = '';\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote+ dquote);\n string_squote = (squote ^squote+ squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n callback(\"on_string\", data, encoding, ts + 1, te - 1);\n }\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Consumes everything between the [ and ]. Due to the use of :> the ]\n # is not consumed by any+.\n '[' any+ :> ']' => {\n callback(\"on_doctype_inline\", data, encoding, ts + 1, te - 1);\n };\n\n # Lex the public\/system IDs as regular strings.\n string => emit_string;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fnext main;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n attribute => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n string => emit_string;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n action start_element {\n callback_simple(\"on_element_start\");\n fnext element_name;\n }\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(\"on_element_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_element_name\", data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"on_newline\");\n };\n\n # Attribute names.\n attribute => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n string => emit_string;\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(\"on_element_open_end\");\n fnext main;\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(\"on_element_end\");\n fnext main;\n };\n *|;\n\n # The main machine aka the entry point of Ragel.\n main := |*\n doctype_start => start_doctype;\n xml_decl_start => start_xml_decl;\n\n comment => {\n callback(\"on_comment\", data, encoding, ts + 4, te - 3);\n };\n\n cdata => {\n callback(\"on_cdata\", data, encoding, ts + 9, te - 3);\n };\n\n # The start of an element.\n '<' => start_element;\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Treat everything else, except for \"<\", as regular text. The \"<\" sign\n # is used for tags so we can't emit text nodes for these characters.\n ^'<'+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","old_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_]+;\n attribute = [a-zA-Z0-9\\-_:]+;\n\n cdata_start = '';\n\n comment_start = '';\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote+ dquote);\n string_squote = (squote ^squote+ squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n callback(\"on_string\", data, encoding, ts + 1, te - 1);\n }\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Consumes everything between the [ and ]. Due to the use of :> the ]\n # is not consumed by any+.\n '[' any+ :> ']' => {\n callback(\"on_doctype_inline\", data, encoding, ts + 1, te - 1);\n };\n\n # Lex the public\/system IDs as regular strings.\n string => emit_string;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fnext main;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n attribute => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n string => emit_string;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n callback_simple(\"on_element_start\");\n fnext element_name;\n }\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(\"on_element_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_element_name\", data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"on_newline\");\n };\n\n # Attribute names.\n attribute => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n string => emit_string;\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(\"on_element_open_end\");\n fnext main;\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(\"on_element_end\");\n fnext main;\n };\n *|;\n\n main := |*\n doctype_start => start_doctype;\n xml_decl_start => start_xml_decl;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start any* comment_end => {\n callback(\"on_comment\", data, encoding, ts + 4, te - 3);\n };\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start any* cdata_end => {\n callback(\"on_cdata\", data, encoding, ts + 9, te - 3);\n };\n\n # The start of an element.\n '<' => start_element;\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Treat everything else, except for \"<\", as regular text. The \"<\" sign\n # is used for tags so we can't emit text nodes for these characters.\n ^'<'+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"31ef2dca1ee8d0f185c9d35f91112c97cda98de8","subject":"Use builtin alnum instead of char class","message":"Use builtin alnum instead of char class\n","repos":"jhart-r7\/regexp_parser,ammar\/regexp_parser,gjtorikian\/regexp_parser,ammar\/regexp_parser","old_file":"lib\/regexp_parser\/scanner\/scanner.rl","new_file":"lib\/regexp_parser\/scanner\/scanner.rl","new_contents":"%%{\n machine re_scanner;\n include re_property \"property.rl\";\n\n dot = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n class_name_posix = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n class_posix = ('[:' . '^'? . class_name_posix . ':]');\n\n\n # these are not supported in ruby, and need verification\n collating_sequence = '[.' . (alpha | [\\-])+ . '.]';\n character_equivalent = '[=' . alpha . '=]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n\n escaped_ascii = [abefnrstv];\n octal_sequence = [0-7]{1,3};\n\n hex_sequence = 'x' . xdigit{1,2};\n hex_sequence_err = 'x' . [^0-9a-fA-F{];\n wide_hex_sequence = 'x' . '{' . xdigit{1,8} . '}';\n\n hex_or_not = (xdigit|[^0-9a-fA-F}]); # note closing curly at end\n\n wide_hex_seq_invalid = 'x' . '{' . hex_or_not{1,9};\n wide_hex_seq_empty = 'x' . '{' . (space+)? . '}';\n\n codepoint_single = 'u' . xdigit{4};\n codepoint_list = 'u{' . (xdigit{4} . space?)+'}';\n codepoint_sequence = codepoint_single | codepoint_list;\n\n control_sequence = ('c' | 'C-');\n\n meta_sequence = 'M-' . (backslash . control_sequence)?;\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_interval = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_interval;\n\n\n conditional = '(?(';\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | (\"'\" . group_name_id . \"'\");\n group_lookup = group_name | group_number;\n\n group_named = ('?' . group_name );\n\n group_name_ref = group_ref . (('<' . group_name_id . group_level? '>') |\n (\"'\" . group_name_id . group_level? \"'\"));\n\n group_number_ref = group_ref . (('<' . group_number . group_level? '>') |\n (\"'\" . group_number . group_level? \"'\"));\n\n group_type = group_atomic | group_passive | group_named;\n\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = dot | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n ascii_print = ((0x20..0x7e) - meta_char)+;\n ascii_nonprint = (0x01..0x1f | 0x7f)+;\n\n utf8_2_byte = (0xc2..0xdf 0x80..0xbf)+;\n utf8_3_byte = (0xe0..0xef 0x80..0xbf 0x80..0xbf)+;\n utf8_4_byte = (0xf0..0xf4 0x80..0xbf 0x80..0xbf 0x80..0xbf)+;\n utf8_byte_sequence = utf8_2_byte | utf8_3_byte | utf8_4_byte;\n\n non_literal_escape = char_type | anchor_char | escaped_ascii |\n group_ref | [xucCM];\n\n # EOF error, used where it can be detected\n action premature_end_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise PrematureEndError.new( text )\n }\n\n # Invalid sequence error, used from sequences, like escapes and sets\n action invalid_sequence_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise InvalidSequenceError.new('sequence', text)\n }\n\n # group (nesting) and set open\/close actions\n action group_opened { group_depth += 1; in_group = true }\n action group_closed { group_depth -= 1; in_group = group_depth > 0 ? true : false }\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :close, *text(data, ts, te))\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '-]' { # special case, emits two tokens\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :member, copy(data, ts..te-2), ts, te)\n emit(set_type, :close, copy(data, ts+1..te-1), ts, te)\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '^' {\n text = text(data, ts, te).first\n if @tokens.last[1] == :open\n emit(set_type, :negate, text, ts, te)\n else\n emit(set_type, :member, text, ts, te)\n end\n };\n\n alnum . '-' . alnum {\n emit(set_type, :range, *text(data, ts, te))\n };\n\n '&&' {\n emit(set_type, :intersection, *text(data, ts, te))\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n '[' >(open_bracket, 1) {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n class_posix >(open_bracket, 1) @eof(premature_end_error) {\n text = text(data, ts, te).first\n\n class_name = text[2..-3]\n if class_name[0].chr == '^'\n class_name = \"non#{class_name[1..-1]}\"\n end\n\n token_sym = \"class_#{class_name}\".to_sym\n emit(set_type, token_sym, text, ts, te)\n };\n\n collating_sequence >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :collation, *text(data, ts, te))\n };\n\n character_equivalent >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :equivalent, *text(data, ts, te))\n };\n\n # exclude the closing bracket as a cleaner workaround for dealing with the\n # ambiguity caused upon exit from the unicode properties machine\n meta_char -- ']' {\n emit(set_type, :member, *text(data, ts, te))\n };\n\n any |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :member, *text(data, ts, te))\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' > (escaped_set_alpha, 2) {\n emit(set_type, :backspace, *text(data, ts, te, 1))\n fret;\n };\n\n char_type > (escaped_set_alpha, 4) {\n case text = text(data, ts, te, 1).first\n when '\\d'; emit(set_type, :type_digit, text, ts-1, te)\n when '\\D'; emit(set_type, :type_nondigit, text, ts-1, te)\n when '\\h'; emit(set_type, :type_hex, text, ts-1, te)\n when '\\H'; emit(set_type, :type_nonhex, text, ts-1, te)\n when '\\s'; emit(set_type, :type_space, text, ts-1, te)\n when '\\S'; emit(set_type, :type_nonspace, text, ts-1, te)\n when '\\w'; emit(set_type, :type_word, text, ts-1, te)\n when '\\W'; emit(set_type, :type_nonword, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n emit(set_type, :range_hex, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence {\n emit(set_type, :member_hex, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char | [\\\\\\]\\-\\,] {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n\n property_char > (escaped_set_alpha, 3) {\n fhold;\n fnext character_set;\n fcall unicode_property;\n fret;\n };\n\n # special case exclusion of escaped dash, could be cleaner.\n (ascii_print - char_type -- [\\-}]) > (escaped_set_alpha, 1) |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n [1-9] {\n text = text(data, ts, te, 1).first\n emit(:backref, :number, text, ts-1, te)\n fret;\n };\n\n octal_sequence {\n emit(:escape, :octal, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char {\n case text = text(data, ts, te, 1).first\n when '\\.'; emit(:escape, :dot, text, ts-1, te)\n when '\\|'; emit(:escape, :alternation, text, ts-1, te)\n when '\\^'; emit(:escape, :bol, text, ts-1, te)\n when '\\$'; emit(:escape, :eol, text, ts-1, te)\n when '\\?'; emit(:escape, :zero_or_one, text, ts-1, te)\n when '\\*'; emit(:escape, :zero_or_more, text, ts-1, te)\n when '\\+'; emit(:escape, :one_or_more, text, ts-1, te)\n when '\\('; emit(:escape, :group_open, text, ts-1, te)\n when '\\)'; emit(:escape, :group_close, text, ts-1, te)\n when '\\{'; emit(:escape, :interval_open, text, ts-1, te)\n when '\\}'; emit(:escape, :interval_close, text, ts-1, te)\n when '\\['; emit(:escape, :set_open, text, ts-1, te)\n when '\\]'; emit(:escape, :set_close, text, ts-1, te)\n when \"\\\\\\\\\";\n emit(:escape, :backslash, text, ts-1, te)\n end\n fret;\n };\n\n escaped_ascii > (escaped_alpha, 7) {\n # \\b is emitted as backspace only when inside a character set, otherwise\n # it is a word boundary anchor. A syntax might \"normalize\" it if needed.\n case text = text(data, ts, te, 1).first\n when '\\a'; emit(:escape, :bell, text, ts-1, te)\n when '\\e'; emit(:escape, :escape, text, ts-1, te)\n when '\\f'; emit(:escape, :form_feed, text, ts-1, te)\n when '\\n'; emit(:escape, :newline, text, ts-1, te)\n when '\\r'; emit(:escape, :carriage, text, ts-1, te)\n when '\\s'; emit(:escape, :space, text, ts-1, te)\n when '\\t'; emit(:escape, :tab, text, ts-1, te)\n when '\\v'; emit(:escape, :vertical_tab, text, ts-1, te)\n end\n fret;\n };\n\n codepoint_sequence > (escaped_alpha, 6) $eof(premature_end_error) {\n text = text(data, ts, te, 1).first\n if text[2].chr == '{'\n emit(:escape, :codepoint_list, text, ts-1, te)\n else\n emit(:escape, :codepoint, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex, *text(data, ts, te, 1))\n fret;\n };\n\n wide_hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex_wide, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence_err @invalid_sequence_error {\n fret;\n };\n\n (wide_hex_seq_invalid | wide_hex_seq_empty) {\n raise InvalidSequenceError.new(\"wide hex sequence\")\n fret;\n };\n\n control_sequence >(escaped_alpha, 4) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :control, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"control sequence\")\n end\n else\n raise PrematureEndError.new(\"control sequence\")\n end\n fret;\n };\n\n meta_sequence >(backslashed, 3) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :meta_sequence, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"meta sequence\")\n end\n else\n raise PrematureEndError.new(\"meta sequence\")\n end\n fret;\n };\n\n property_char > (escaped_alpha, 2) {\n fhold;\n fnext main;\n fcall unicode_property; fret;\n };\n\n (any -- non_literal_escape) > (escaped_alpha, 1) {\n emit(:escape, :literal, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # conditional expressions scanner\n # --------------------------------------------------------------------------\n conditional_expression := |*\n group_lookup . ')' {\n text = text(data, ts, te-1).first\n emit(:conditional, :condition, text, ts, te-1)\n emit(:conditional, :condition_close, ')', te-1, te)\n };\n\n any {\n fhold;\n fcall main;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n # ------------------------------------------------------------------------\n dot {\n emit(:meta, :dot, *text(data, ts, te))\n };\n\n alternation {\n if in_conditional and conditional_stack.length > 0 and \n conditional_stack.last[1] == group_depth\n emit(:conditional, :separator, *text(data, ts, te))\n else\n emit(:meta, :alternation, *text(data, ts, te))\n end\n };\n\n # Anchors\n # ------------------------------------------------------------------------\n beginning_of_line {\n emit(:anchor, :bol, *text(data, ts, te))\n };\n\n end_of_line {\n emit(:anchor, :eol, *text(data, ts, te))\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = text(data, ts, te).first\n when '\\\\A'; emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; emit(:anchor, :eos_ob_eol, text, ts, te)\n when '\\\\b'; emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; emit(:anchor, :nonword_boundary, text, ts, te)\n when '\\\\G'; emit(:anchor, :match_start, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in anchor at #{text} (char #{ts})\")\n end\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S space, non-space\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = text(data, ts, te).first\n when '\\\\d'; emit(:type, :digit, text, ts, te)\n when '\\\\D'; emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; emit(:type, :hex, text, ts, te)\n when '\\\\H'; emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; emit(:type, :space, text, ts, te)\n when '\\\\S'; emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; emit(:type, :word, text, ts, te)\n when '\\\\W'; emit(:type, :nonword, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in type at #{text} (char #{ts})\")\n end\n };\n\n\n # Character sets\n # ------------------------------------------------------------------------\n set_open {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n\n # Conditional expression\n # (?(condition)Y|N) conditional expression\n # ------------------------------------------------------------------------\n conditional {\n text = text(data, ts, te).first\n\n in_conditional = true unless in_conditional\n conditional_depth += 1\n conditional_stack << [conditional_depth, group_depth]\n\n emit(:conditional, :open, text[0..-2], ts, te-1)\n emit(:conditional, :condition_open, '(', te-1, te)\n fcall conditional_expression;\n };\n\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n # special case for close, action performed on all transitions to get the \n # correct closing count.\n # ------------------------------------------------------------------------\n group_open . group_comment $group_closed {\n emit(:group, :comment, *text(data, ts, te))\n };\n\n # Expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n # ------------------------------------------------------------------------\n group_open . group_options >group_opened {\n p = scan_options(p, data, ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?group_opened {\n case text = text(data, ts, te).first\n when '(?='; emit(:assertion, :lookahead, text, ts, te)\n when '(?!'; emit(:assertion, :nlookahead, text, ts, te)\n when '(?<='; emit(:assertion, :lookbehind, text, ts, te)\n when '(?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group\n # (?'name'subexp) named group (single quoted version)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type >group_opened {\n case text = text(data, ts, te).first\n when '(?:'; emit(:group, :passive, text, ts, te)\n when '(?>'; emit(:group, :atomic, text, ts, te)\n\n when \/^\\(\\?<(\\w*)>\/\n empty_name_error(:group, 'named group (ab)') if $1.empty?\n\n emit(:group, :named_ab, text, ts, te)\n\n when \/^\\(\\?'(\\w*)'\/\n empty_name_error(:group, 'named group (sq)') if $1.empty?\n\n emit(:group, :named_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown subexpression group format '#{text}'\")\n end\n };\n\n group_open @group_opened {\n text = text(data, ts, te).first\n emit(:group, :capture, text, ts, te)\n };\n\n group_close @group_closed {\n if in_conditional and conditional_stack.last and\n conditional_stack.last[1] == (group_depth + 1)\n\n emit(:conditional, :close, *text(data, ts, te))\n conditional_stack.pop\n\n if conditional_stack.length == 0\n in_conditional = false\n end\n else\n emit(:group, :close, *text(data, ts, te))\n end\n };\n\n\n # Group backreference, named and numbered\n # ------------------------------------------------------------------------\n backslash . (group_name_ref | group_number_ref) > (backslashed, 4) {\n case text = text(data, ts, te).first\n when \/^\\\\([gk])<>\/ # angle brackets\n empty_backref_error(\"ref\/call (ab)\")\n\n when \/^\\\\([gk])''\/ # single quotes\n empty_backref_error(\"ref\/call (sq)\")\n\n when \/^\\\\([gk])<[^\\d-](\\w+)?>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :name_ref_ab, text, ts, te)\n else\n emit(:backref, :name_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'[^\\d-](\\w+)?'\/ #single quotes\n if $1 == 'k'\n emit(:backref, :name_ref_sq, text, ts, te)\n else\n emit(:backref, :name_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_ref_ab, text, ts, te)\n else\n emit(:backref, :number_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_ref_sq, text, ts, te)\n else\n emit(:backref, :number_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<-\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_rel_ref_ab, text, ts, te)\n else\n emit(:backref, :number_rel_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'-\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_rel_ref_sq, text, ts, te)\n else\n emit(:backref, :number_rel_call_sq, text, ts, te)\n end\n\n when \/^\\\\k<[^\\d-](\\w+)?[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :name_nest_ref_ab, text, ts, te)\n\n when \/^\\\\k'[^\\d-](\\w+)?[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :name_nest_ref_sq, text, ts, te)\n\n when \/^\\\\([gk])<\\d+[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :number_nest_ref_ab, text, ts, te)\n\n when \/^\\\\([gk])'\\d+[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :number_nest_ref_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown backreference format '#{text}'\")\n end\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = text(data, ts, te).first\n when '?' ; emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n\n zero_or_more {\n case text = text(data, ts, te).first\n when '*' ; emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n\n one_or_more {\n case text = text(data, ts, te).first\n when '+' ; emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n quantifier_interval @err(premature_end_error) {\n emit(:quantifier, :interval, *text(data, ts, te))\n };\n\n # Escaped sequences\n # ------------------------------------------------------------------------\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Literal: any run of ASCII (pritable or non-printable), and\/or UTF-8,\n # except meta characters.\n # ------------------------------------------------------------------------\n ascii_print+ |\n ascii_nonprint+ |\n utf8_2_byte+ |\n utf8_3_byte+ |\n utf8_4_byte+ {\n append_literal(data, ts, te)\n };\n\n *|;\n}%%\n\n# THIS IS A GENERATED FILE, DO NOT EDIT DIRECTLY\n# This file was generated from lib\/regexp_parser\/scanner\/scanner.rl\n\nmodule Regexp::Scanner\n %% write data;\n\n # General scanner error (catch all)\n class ScannerError < StandardError\n def initialize(what)\n super what\n end\n end\n\n # Base for all scanner validation errors\n class ValidationError < StandardError\n def initialize(reason)\n super reason\n end\n end\n\n # Unexpected end of pattern\n class PrematureEndError < ScannerError\n def initialize(where = '')\n super \"Premature end of pattern at #{where}\"\n end\n end\n\n # Invalid sequence format. Used for escape sequences, mainly.\n class InvalidSequenceError < ValidationError\n def initialize(what = 'sequence', where = '')\n super \"Invalid #{what} at #{where}\"\n end\n end\n\n # Invalid group. Used for named groups.\n class InvalidGroupError < ValidationError\n def initialize(what, reason)\n super \"Invalid #{what}, #{reason}.\"\n end\n end\n\n # Invalid back reference. Used for name a number refs\/calls.\n class InvalidBackrefError < ValidationError\n def initialize(what, reason)\n super \"Invalid back reference #{what}, #{reason}\"\n end\n end\n\n # The property name was not recognized by the scanner.\n class UnknownUnicodePropertyError < ValidationError\n def initialize(name)\n super \"Unknown unicode character property name #{name}\"\n end\n end\n\n # Scans the given regular expression text, or Regexp object and collects the\n # emitted token into an array that gets returned at the end. If a block is\n # given, it gets called for each emitted token.\n #\n # This method may raise errors if a syntax error is encountered.\n # --------------------------------------------------------------------------\n def self.scan(input, &block)\n top, stack = 0, []\n\n input = input.source if input.is_a?(Regexp)\n data = input.unpack(\"c*\") if input.is_a?(String)\n eof = data.length\n\n @tokens = []\n @block = block_given? ? block : nil\n\n in_group, group_depth = false, 0\n in_set, set_depth, set_type = false, 0, :set\n in_conditional, conditional_depth, conditional_stack = false, 0, []\n\n %% write init;\n %% write exec;\n\n if cs == re_scanner_error\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise ScannerError.new(\"Scan error at '#{text}'\")\n end\n\n raise PrematureEndError.new(\"(missing group closing paranthesis) \"+\n \"[#{in_group}:#{group_depth}]\") if in_group\n raise PrematureEndError.new(\"(missing set closing bracket) \"+\n \"[#{in_set}:#{set_depth}]\") if in_set\n\n # when the entire expression is a literal run\n emit_literal if @literal\n\n @tokens\n end\n\n private\n\n # Ragel's regex-based scan of the group options introduced a lot of\n # ambiguity, so we just ask it to find the beginning of what looks\n # like an options run and handle the rest in here.\n def self.scan_options(p, data, ts, te)\n text = text(data, ts, te).first\n\n options_char, options_length = true, 0\n\n # Copy while we have option characters, the maximum is 7, for (?mix-mix,\n # even though it doesn't make sense it is possible.\n while options_char and options_length < 7\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c =~ \/[-mix]\/\n text << c ; p += 1 ; options_length += 1\n else\n options_char = false\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n end\n\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c == ':'\n # Include the ':' in the options text\n text << c ; p += 1 ; options_length += 1\n emit(:group, :options, text, ts, te + options_length)\n\n elsif c == ')'\n # Don't include the closing ')', let group_close handle it.\n emit(:group, :options, text, ts, te + options_length)\n\n else\n # Plain Regexp reports this as 'undefined group option'\n raise ScannerError.new(\n \"Unexpected `#{c}' in options sequence, ':' or ')' expected\")\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n\n p # return the new value of the data pointer\n end\n\n # Copy from ts to te from data as text\n def self.copy(data, range)\n data[range].pack('c*')\n end\n\n # Copy from ts to te from data as text, returning an array with the text\n # and the offsets used to copy it.\n def self.text(data, ts, te, soff = 0)\n [copy(data, ts-soff..te-1), ts-soff, te]\n end\n\n # Appends one or more characters to the literal buffer, to be emitted later\n # by a call to emit_literal. Contents can be a mix of ASCII and UTF-8.\n def self.append_literal(data, ts, te)\n @literal ||= []\n @literal << text(data, ts, te)\n end\n\n # Emits the literal run collected by calls to the append_literal method,\n # using the total start (ts) and end (te) offsets of the run.\n def self.emit_literal\n ts, te = @literal.first[1], @literal.last[2]\n text = @literal.map {|t| t[0]}.join\n\n text.force_encoding('utf-8') if text.respond_to?(:force_encoding)\n\n @literal = nil\n emit(:literal, :literal, text, ts, te)\n end\n\n # Emits an array with the details of the scanned pattern\n def self.emit(type, token, text, ts, te)\n #puts \"EMIT: type: #{type}, token: #{token}, text: #{text}, ts: #{ts}, te: #{te}\"\n\n emit_literal if @literal\n\n if @block\n @block.call type, token, text, ts, te\n end\n\n @tokens << [type, token, text, ts, te]\n end\n\n # Centralizes and unifies the handling of validation related\n # errors.\n def self.validation_error(type, what, reason)\n case type\n when :group\n error = InvalidGroupError.new(what, reason)\n when :backref\n error = InvalidBackrefError.new(what, reason)\n when :sequence\n error = InvalidSequenceError.new(what, reason)\n else\n error = ValidationError.new('expression')\n end\n\n # TODO: configuration option to treat scanner level validation\n # errors as warnings or ignore them\n if false # @@config.validation_warn\n $stderr.puts error.to_s # unless @@config.validation_ignore\n else\n raise error # unless @@config.validation_ignore\n end\n end\n\n # Used for references with an empty name or number\n def self.empty_backref_error(type, what)\n validation_error(:backref, what, 'ref ID is empty')\n end\n\n # Used for named expressions with an empty name\n def self.empty_name_error(type, what)\n validation_error(type, what, 'name is empty')\n end\n\nend # module Regexp::Scanner\n","old_contents":"%%{\n machine re_scanner;\n include re_property \"property.rl\";\n\n dot = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n class_name_posix = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n class_posix = ('[:' . '^'? . class_name_posix . ':]');\n\n\n # these are not supported in ruby, and need verification\n collating_sequence = '[.' . (alpha | [\\-])+ . '.]';\n character_equivalent = '[=' . alpha . '=]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n\n escaped_ascii = [abefnrstv];\n octal_sequence = [0-7]{1,3};\n\n hex_sequence = 'x' . xdigit{1,2};\n hex_sequence_err = 'x' . [^0-9a-fA-F{];\n wide_hex_sequence = 'x' . '{' . xdigit{1,8} . '}';\n\n hex_or_not = (xdigit|[^0-9a-fA-F}]); # note closing curly at end\n\n wide_hex_seq_invalid = 'x' . '{' . hex_or_not{1,9};\n wide_hex_seq_empty = 'x' . '{' . (space+)? . '}';\n\n codepoint_single = 'u' . xdigit{4};\n codepoint_list = 'u{' . (xdigit{4} . space?)+'}';\n codepoint_sequence = codepoint_single | codepoint_list;\n\n control_sequence = ('c' | 'C-');\n\n meta_sequence = 'M-' . (backslash . control_sequence)?;\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_interval = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_interval;\n\n\n conditional = '(?(';\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | (\"'\" . group_name_id . \"'\");\n group_lookup = group_name | group_number;\n\n group_named = ('?' . group_name );\n\n group_name_ref = group_ref . (('<' . group_name_id . group_level? '>') |\n (\"'\" . group_name_id . group_level? \"'\"));\n\n group_number_ref = group_ref . (('<' . group_number . group_level? '>') |\n (\"'\" . group_number . group_level? \"'\"));\n\n group_type = group_atomic | group_passive | group_named;\n\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = dot | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n ascii_print = ((0x20..0x7e) - meta_char)+;\n ascii_nonprint = (0x01..0x1f | 0x7f)+;\n\n utf8_2_byte = (0xc2..0xdf 0x80..0xbf)+;\n utf8_3_byte = (0xe0..0xef 0x80..0xbf 0x80..0xbf)+;\n utf8_4_byte = (0xf0..0xf4 0x80..0xbf 0x80..0xbf 0x80..0xbf)+;\n utf8_byte_sequence = utf8_2_byte | utf8_3_byte | utf8_4_byte;\n\n non_literal_escape = char_type | anchor_char | escaped_ascii |\n group_ref | [xucCM];\n\n # EOF error, used where it can be detected\n action premature_end_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise PrematureEndError.new( text )\n }\n\n # Invalid sequence error, used from sequences, like escapes and sets\n action invalid_sequence_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise InvalidSequenceError.new('sequence', text)\n }\n\n # group (nesting) and set open\/close actions\n action group_opened { group_depth += 1; in_group = true }\n action group_closed { group_depth -= 1; in_group = group_depth > 0 ? true : false }\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :close, *text(data, ts, te))\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '-]' { # special case, emits two tokens\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :member, copy(data, ts..te-2), ts, te)\n emit(set_type, :close, copy(data, ts+1..te-1), ts, te)\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '^' {\n text = text(data, ts, te).first\n if @tokens.last[1] == :open\n emit(set_type, :negate, text, ts, te)\n else\n emit(set_type, :member, text, ts, te)\n end\n };\n\n alnum . '-' . alnum {\n emit(set_type, :range, *text(data, ts, te))\n };\n\n '&&' {\n emit(set_type, :intersection, *text(data, ts, te))\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n '[' >(open_bracket, 1) {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n class_posix >(open_bracket, 1) @eof(premature_end_error) {\n text = text(data, ts, te).first\n\n class_name = text[2..-3]\n if class_name[0].chr == '^'\n class_name = \"non#{class_name[1..-1]}\"\n end\n\n token_sym = \"class_#{class_name}\".to_sym\n emit(set_type, token_sym, text, ts, te)\n };\n\n collating_sequence >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :collation, *text(data, ts, te))\n };\n\n character_equivalent >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :equivalent, *text(data, ts, te))\n };\n\n # exclude the closing bracket as a cleaner workaround for dealing with the\n # ambiguity caused upon exit from the unicode properties machine\n meta_char -- ']' {\n emit(set_type, :member, *text(data, ts, te))\n };\n\n any |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :member, *text(data, ts, te))\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' > (escaped_set_alpha, 2) {\n emit(set_type, :backspace, *text(data, ts, te, 1))\n fret;\n };\n\n char_type > (escaped_set_alpha, 4) {\n case text = text(data, ts, te, 1).first\n when '\\d'; emit(set_type, :type_digit, text, ts-1, te)\n when '\\D'; emit(set_type, :type_nondigit, text, ts-1, te)\n when '\\h'; emit(set_type, :type_hex, text, ts-1, te)\n when '\\H'; emit(set_type, :type_nonhex, text, ts-1, te)\n when '\\s'; emit(set_type, :type_space, text, ts-1, te)\n when '\\S'; emit(set_type, :type_nonspace, text, ts-1, te)\n when '\\w'; emit(set_type, :type_word, text, ts-1, te)\n when '\\W'; emit(set_type, :type_nonword, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n emit(set_type, :range_hex, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence {\n emit(set_type, :member_hex, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char | [\\\\\\]\\-\\,] {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n\n property_char > (escaped_set_alpha, 3) {\n fhold;\n fnext character_set;\n fcall unicode_property;\n fret;\n };\n\n # special case exclusion of escaped dash, could be cleaner.\n (ascii_print - char_type -- [\\-}]) > (escaped_set_alpha, 1) |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n [1-9] {\n text = text(data, ts, te, 1).first\n emit(:backref, :number, text, ts-1, te)\n fret;\n };\n\n octal_sequence {\n emit(:escape, :octal, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char {\n case text = text(data, ts, te, 1).first\n when '\\.'; emit(:escape, :dot, text, ts-1, te)\n when '\\|'; emit(:escape, :alternation, text, ts-1, te)\n when '\\^'; emit(:escape, :bol, text, ts-1, te)\n when '\\$'; emit(:escape, :eol, text, ts-1, te)\n when '\\?'; emit(:escape, :zero_or_one, text, ts-1, te)\n when '\\*'; emit(:escape, :zero_or_more, text, ts-1, te)\n when '\\+'; emit(:escape, :one_or_more, text, ts-1, te)\n when '\\('; emit(:escape, :group_open, text, ts-1, te)\n when '\\)'; emit(:escape, :group_close, text, ts-1, te)\n when '\\{'; emit(:escape, :interval_open, text, ts-1, te)\n when '\\}'; emit(:escape, :interval_close, text, ts-1, te)\n when '\\['; emit(:escape, :set_open, text, ts-1, te)\n when '\\]'; emit(:escape, :set_close, text, ts-1, te)\n when \"\\\\\\\\\";\n emit(:escape, :backslash, text, ts-1, te)\n end\n fret;\n };\n\n escaped_ascii > (escaped_alpha, 7) {\n # \\b is emitted as backspace only when inside a character set, otherwise\n # it is a word boundary anchor. A syntax might \"normalize\" it if needed.\n case text = text(data, ts, te, 1).first\n when '\\a'; emit(:escape, :bell, text, ts-1, te)\n when '\\e'; emit(:escape, :escape, text, ts-1, te)\n when '\\f'; emit(:escape, :form_feed, text, ts-1, te)\n when '\\n'; emit(:escape, :newline, text, ts-1, te)\n when '\\r'; emit(:escape, :carriage, text, ts-1, te)\n when '\\s'; emit(:escape, :space, text, ts-1, te)\n when '\\t'; emit(:escape, :tab, text, ts-1, te)\n when '\\v'; emit(:escape, :vertical_tab, text, ts-1, te)\n end\n fret;\n };\n\n codepoint_sequence > (escaped_alpha, 6) $eof(premature_end_error) {\n text = text(data, ts, te, 1).first\n if text[2].chr == '{'\n emit(:escape, :codepoint_list, text, ts-1, te)\n else\n emit(:escape, :codepoint, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex, *text(data, ts, te, 1))\n fret;\n };\n\n wide_hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex_wide, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence_err @invalid_sequence_error {\n fret;\n };\n\n (wide_hex_seq_invalid | wide_hex_seq_empty) {\n raise InvalidSequenceError.new(\"wide hex sequence\")\n fret;\n };\n\n control_sequence >(escaped_alpha, 4) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :control, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"control sequence\")\n end\n else\n raise PrematureEndError.new(\"control sequence\")\n end\n fret;\n };\n\n meta_sequence >(backslashed, 3) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :meta_sequence, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"meta sequence\")\n end\n else\n raise PrematureEndError.new(\"meta sequence\")\n end\n fret;\n };\n\n property_char > (escaped_alpha, 2) {\n fhold;\n fnext main;\n fcall unicode_property; fret;\n };\n\n (any -- non_literal_escape) > (escaped_alpha, 1) {\n emit(:escape, :literal, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # conditional expressions scanner\n # --------------------------------------------------------------------------\n conditional_expression := |*\n group_lookup . ')' {\n text = text(data, ts, te-1).first\n emit(:conditional, :condition, text, ts, te-1)\n emit(:conditional, :condition_close, ')', te-1, te)\n };\n\n any {\n fhold;\n fcall main;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n # ------------------------------------------------------------------------\n dot {\n emit(:meta, :dot, *text(data, ts, te))\n };\n\n alternation {\n if in_conditional and conditional_stack.length > 0 and \n conditional_stack.last[1] == group_depth\n emit(:conditional, :separator, *text(data, ts, te))\n else\n emit(:meta, :alternation, *text(data, ts, te))\n end\n };\n\n # Anchors\n # ------------------------------------------------------------------------\n beginning_of_line {\n emit(:anchor, :bol, *text(data, ts, te))\n };\n\n end_of_line {\n emit(:anchor, :eol, *text(data, ts, te))\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = text(data, ts, te).first\n when '\\\\A'; emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; emit(:anchor, :eos_ob_eol, text, ts, te)\n when '\\\\b'; emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; emit(:anchor, :nonword_boundary, text, ts, te)\n when '\\\\G'; emit(:anchor, :match_start, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in anchor at #{text} (char #{ts})\")\n end\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S space, non-space\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = text(data, ts, te).first\n when '\\\\d'; emit(:type, :digit, text, ts, te)\n when '\\\\D'; emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; emit(:type, :hex, text, ts, te)\n when '\\\\H'; emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; emit(:type, :space, text, ts, te)\n when '\\\\S'; emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; emit(:type, :word, text, ts, te)\n when '\\\\W'; emit(:type, :nonword, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in type at #{text} (char #{ts})\")\n end\n };\n\n\n # Character sets\n # ------------------------------------------------------------------------\n set_open {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n\n # Conditional expression\n # (?(condition)Y|N) conditional expression\n # ------------------------------------------------------------------------\n conditional {\n text = text(data, ts, te).first\n\n in_conditional = true unless in_conditional\n conditional_depth += 1\n conditional_stack << [conditional_depth, group_depth]\n\n emit(:conditional, :open, text[0..-2], ts, te-1)\n emit(:conditional, :condition_open, '(', te-1, te)\n fcall conditional_expression;\n };\n\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n # special case for close, action performed on all transitions to get the \n # correct closing count.\n # ------------------------------------------------------------------------\n group_open . group_comment $group_closed {\n emit(:group, :comment, *text(data, ts, te))\n };\n\n # Expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n # ------------------------------------------------------------------------\n group_open . group_options >group_opened {\n p = scan_options(p, data, ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?group_opened {\n case text = text(data, ts, te).first\n when '(?='; emit(:assertion, :lookahead, text, ts, te)\n when '(?!'; emit(:assertion, :nlookahead, text, ts, te)\n when '(?<='; emit(:assertion, :lookbehind, text, ts, te)\n when '(?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group\n # (?'name'subexp) named group (single quoted version)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type >group_opened {\n case text = text(data, ts, te).first\n when '(?:'; emit(:group, :passive, text, ts, te)\n when '(?>'; emit(:group, :atomic, text, ts, te)\n\n when \/^\\(\\?<(\\w*)>\/\n empty_name_error(:group, 'named group (ab)') if $1.empty?\n\n emit(:group, :named_ab, text, ts, te)\n\n when \/^\\(\\?'(\\w*)'\/\n empty_name_error(:group, 'named group (sq)') if $1.empty?\n\n emit(:group, :named_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown subexpression group format '#{text}'\")\n end\n };\n\n group_open @group_opened {\n text = text(data, ts, te).first\n emit(:group, :capture, text, ts, te)\n };\n\n group_close @group_closed {\n if in_conditional and conditional_stack.last and\n conditional_stack.last[1] == (group_depth + 1)\n\n emit(:conditional, :close, *text(data, ts, te))\n conditional_stack.pop\n\n if conditional_stack.length == 0\n in_conditional = false\n end\n else\n emit(:group, :close, *text(data, ts, te))\n end\n };\n\n\n # Group backreference, named and numbered\n # ------------------------------------------------------------------------\n backslash . (group_name_ref | group_number_ref) > (backslashed, 4) {\n case text = text(data, ts, te).first\n when \/^\\\\([gk])<>\/ # angle brackets\n empty_backref_error(\"ref\/call (ab)\")\n\n when \/^\\\\([gk])''\/ # single quotes\n empty_backref_error(\"ref\/call (sq)\")\n\n when \/^\\\\([gk])<[^\\d-](\\w+)?>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :name_ref_ab, text, ts, te)\n else\n emit(:backref, :name_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'[^\\d-](\\w+)?'\/ #single quotes\n if $1 == 'k'\n emit(:backref, :name_ref_sq, text, ts, te)\n else\n emit(:backref, :name_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_ref_ab, text, ts, te)\n else\n emit(:backref, :number_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_ref_sq, text, ts, te)\n else\n emit(:backref, :number_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<-\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_rel_ref_ab, text, ts, te)\n else\n emit(:backref, :number_rel_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'-\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_rel_ref_sq, text, ts, te)\n else\n emit(:backref, :number_rel_call_sq, text, ts, te)\n end\n\n when \/^\\\\k<[^\\d-](\\w+)?[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :name_nest_ref_ab, text, ts, te)\n\n when \/^\\\\k'[^\\d-](\\w+)?[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :name_nest_ref_sq, text, ts, te)\n\n when \/^\\\\([gk])<\\d+[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :number_nest_ref_ab, text, ts, te)\n\n when \/^\\\\([gk])'\\d+[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :number_nest_ref_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown backreference format '#{text}'\")\n end\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = text(data, ts, te).first\n when '?' ; emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n\n zero_or_more {\n case text = text(data, ts, te).first\n when '*' ; emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n\n one_or_more {\n case text = text(data, ts, te).first\n when '+' ; emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n quantifier_interval @err(premature_end_error) {\n emit(:quantifier, :interval, *text(data, ts, te))\n };\n\n # Escaped sequences\n # ------------------------------------------------------------------------\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Literal: any run of ASCII (pritable or non-printable), and\/or UTF-8,\n # except meta characters.\n # ------------------------------------------------------------------------\n ascii_print+ |\n ascii_nonprint+ |\n utf8_2_byte+ |\n utf8_3_byte+ |\n utf8_4_byte+ {\n append_literal(data, ts, te)\n };\n\n *|;\n}%%\n\n# THIS IS A GENERATED FILE, DO NOT EDIT DIRECTLY\n# This file was generated from lib\/regexp_parser\/scanner\/scanner.rl\n\nmodule Regexp::Scanner\n %% write data;\n\n # General scanner error (catch all)\n class ScannerError < StandardError\n def initialize(what)\n super what\n end\n end\n\n # Base for all scanner validation errors\n class ValidationError < StandardError\n def initialize(reason)\n super reason\n end\n end\n\n # Unexpected end of pattern\n class PrematureEndError < ScannerError\n def initialize(where = '')\n super \"Premature end of pattern at #{where}\"\n end\n end\n\n # Invalid sequence format. Used for escape sequences, mainly.\n class InvalidSequenceError < ValidationError\n def initialize(what = 'sequence', where = '')\n super \"Invalid #{what} at #{where}\"\n end\n end\n\n # Invalid group. Used for named groups.\n class InvalidGroupError < ValidationError\n def initialize(what, reason)\n super \"Invalid #{what}, #{reason}.\"\n end\n end\n\n # Invalid back reference. Used for name a number refs\/calls.\n class InvalidBackrefError < ValidationError\n def initialize(what, reason)\n super \"Invalid back reference #{what}, #{reason}\"\n end\n end\n\n # The property name was not recognized by the scanner.\n class UnknownUnicodePropertyError < ValidationError\n def initialize(name)\n super \"Unknown unicode character property name #{name}\"\n end\n end\n\n # Scans the given regular expression text, or Regexp object and collects the\n # emitted token into an array that gets returned at the end. If a block is\n # given, it gets called for each emitted token.\n #\n # This method may raise errors if a syntax error is encountered.\n # --------------------------------------------------------------------------\n def self.scan(input, &block)\n top, stack = 0, []\n\n input = input.source if input.is_a?(Regexp)\n data = input.unpack(\"c*\") if input.is_a?(String)\n eof = data.length\n\n @tokens = []\n @block = block_given? ? block : nil\n\n in_group, group_depth = false, 0\n in_set, set_depth, set_type = false, 0, :set\n in_conditional, conditional_depth, conditional_stack = false, 0, []\n\n %% write init;\n %% write exec;\n\n if cs == re_scanner_error\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise ScannerError.new(\"Scan error at '#{text}'\")\n end\n\n raise PrematureEndError.new(\"(missing group closing paranthesis) \"+\n \"[#{in_group}:#{group_depth}]\") if in_group\n raise PrematureEndError.new(\"(missing set closing bracket) \"+\n \"[#{in_set}:#{set_depth}]\") if in_set\n\n # when the entire expression is a literal run\n emit_literal if @literal\n\n @tokens\n end\n\n private\n\n # Ragel's regex-based scan of the group options introduced a lot of\n # ambiguity, so we just ask it to find the beginning of what looks\n # like an options run and handle the rest in here.\n def self.scan_options(p, data, ts, te)\n text = text(data, ts, te).first\n\n options_char, options_length = true, 0\n\n # Copy while we have option characters, the maximum is 7, for (?mix-mix,\n # even though it doesn't make sense it is possible.\n while options_char and options_length < 7\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c =~ \/[-mix]\/\n text << c ; p += 1 ; options_length += 1\n else\n options_char = false\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n end\n\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c == ':'\n # Include the ':' in the options text\n text << c ; p += 1 ; options_length += 1\n emit(:group, :options, text, ts, te + options_length)\n\n elsif c == ')'\n # Don't include the closing ')', let group_close handle it.\n emit(:group, :options, text, ts, te + options_length)\n\n else\n # Plain Regexp reports this as 'undefined group option'\n raise ScannerError.new(\n \"Unexpected `#{c}' in options sequence, ':' or ')' expected\")\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n\n p # return the new value of the data pointer\n end\n\n # Copy from ts to te from data as text\n def self.copy(data, range)\n data[range].pack('c*')\n end\n\n # Copy from ts to te from data as text, returning an array with the text\n # and the offsets used to copy it.\n def self.text(data, ts, te, soff = 0)\n [copy(data, ts-soff..te-1), ts-soff, te]\n end\n\n # Appends one or more characters to the literal buffer, to be emitted later\n # by a call to emit_literal. Contents can be a mix of ASCII and UTF-8.\n def self.append_literal(data, ts, te)\n @literal ||= []\n @literal << text(data, ts, te)\n end\n\n # Emits the literal run collected by calls to the append_literal method,\n # using the total start (ts) and end (te) offsets of the run.\n def self.emit_literal\n ts, te = @literal.first[1], @literal.last[2]\n text = @literal.map {|t| t[0]}.join\n\n text.force_encoding('utf-8') if text.respond_to?(:force_encoding)\n\n @literal = nil\n emit(:literal, :literal, text, ts, te)\n end\n\n # Emits an array with the details of the scanned pattern\n def self.emit(type, token, text, ts, te)\n #puts \"EMIT: type: #{type}, token: #{token}, text: #{text}, ts: #{ts}, te: #{te}\"\n\n emit_literal if @literal\n\n if @block\n @block.call type, token, text, ts, te\n end\n\n @tokens << [type, token, text, ts, te]\n end\n\n # Centralizes and unifies the handling of validation related\n # errors.\n def self.validation_error(type, what, reason)\n case type\n when :group\n error = InvalidGroupError.new(what, reason)\n when :backref\n error = InvalidBackrefError.new(what, reason)\n when :sequence\n error = InvalidSequenceError.new(what, reason)\n else\n error = ValidationError.new('expression')\n end\n\n # TODO: configuration option to treat scanner level validation\n # errors as warnings or ignore them\n if false # @@config.validation_warn\n $stderr.puts error.to_s # unless @@config.validation_ignore\n else\n raise error # unless @@config.validation_ignore\n end\n end\n\n # Used for references with an empty name or number\n def self.empty_backref_error(type, what)\n validation_error(:backref, what, 'ref ID is empty')\n end\n\n # Used for named expressions with an empty name\n def self.empty_name_error(type, what)\n validation_error(type, what, 'name is empty')\n end\n\nend # module Regexp::Scanner\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"a11b1e5a23798b7adeb7adfa7a383fcad79a76bb","subject":"Ragel: tis a module now","message":"Ragel: tis a module now\n","repos":"CuppenResearch\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,gusevfe\/bioruby-vcf,gusevfe\/bioruby-vcf,CuppenResearch\/bioruby-vcf,pjotrp\/bioruby-vcf,pjotrp\/bioruby-vcf,pjotrp\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Parser for VCF-header info and format fields\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action Stop {\n quoted_text = data[ts...p].pack('c*')\n # do something with the quoted text!\n emit.call('string',data,ts,p)\n }\n\n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %Stop squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %Stop dquote;\n\n # main := (ss | dd)*;\n\n integer = ('+'|'-')?[0-9]+ >mark %{ emit.call(\"integer\",data,ts,p) };\n float = ('+'|'-')?[0-9]+'.'[0-9]+ >mark %{ emit.call(\"float\",data,ts,p) };\n assignment = '=';\n identifier = ([a-zA-Z][a-zA-Z_0-9]+) >mark %{ emit.call(\"identifier\",data,ts,p) }; \n str = (ss|dd)* ; \n boolean = '.' >mark %{ emit.call(\"bool\",data,ts,p) };\n key_word = ( ('ID'|'Number'|'Type'|'Description') >mark %{ print \"*k:\"; emit.call(\"key_word\",data,ts,p) } );\n value = ( (integer|float|boolean|identifier|str) >mark %{ print \"*v:\" ; emit.call(\"value\",data,ts,p) } );\n\n key_value = ( key_word '=' value ) ;\n \n main := ('##FORMAT'|'##INFO') '=' (('<'|',') key_value )*;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\n \ndef self.run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\"\n }\n\n %% write init;\n %% write exec;\n\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| VcfHeader::RagelKeyValues.run_lexer(s) }\n\nend","old_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action Stop {\n quoted_text = data[ts...p].pack('c*')\n # do something with the quoted text!\n emit.call('string',data,ts,p)\n }\n\n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %Stop squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %Stop dquote;\n\n # main := (ss | dd)*;\n\n integer = ('+'|'-')?[0-9]+ >mark %{ emit.call(\"integer\",data,ts,p) };\n float = ('+'|'-')?[0-9]+'.'[0-9]+ >mark %{ emit.call(\"float\",data,ts,p) };\n assignment = '=';\n identifier = ([a-zA-Z][a-zA-Z_0-9]+) >mark %{ emit.call(\"identifier\",data,ts,p) }; \n str = (ss|dd)* ; \n boolean = '.' >mark %{ emit.call(\"bool\",data,ts,p) };\n key_word = ( ('ID'|'Number'|'Type'|'Description') >mark %{ print \"*k:\"; emit.call(\"key_word\",data,ts,p) } );\n value = ( (integer|float|boolean|identifier|str) >mark %{ print \"*v:\" ; emit.call(\"value\",data,ts,p) } );\n\n key_value = ( key_word '=' value ) ;\n \n main := ('##FORMAT'|'##INFO') '=' (('<'|',') key_value )*;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\n \ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\"\n }\n\n %% write init;\n %% write exec;\n\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"cd407ff2ea25d81ef4437f0f3a170d257b42ad29","subject":"Style \/ naming changes from codereview.","message":"Style \/ naming changes from codereview.\n","repos":"b1v1r\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee","old_file":"engine\/config-parser.rl","new_file":"engine\/config-parser.rl","new_contents":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee - Configuration File Parser\n *\n * @author Brian Rectanus \n *\/\n\n#include \"ironbee_config_auto.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"config-parser.h\"\n#include \"ironbee_private.h\"\n\ntypedef struct {\n char *p;\n char *pe;\n char *eof;\n char *ts;\n char *te;\n int cs;\n int top;\n int act;\n int stack[1024];\n} fsm_t;\n\nstatic char *dirname = NULL;\nstatic char *blkname = NULL;\nstatic char *pval = NULL;\n\n\/* Store the start of a string to act on.\n fpc - mark is the string length when processing after\n a mark action. *\/\nstatic char *mark = NULL;\n\n\/**\n * @brief Malloc and unescape into that buffer the marked string.\n * @param[in] fpc_mark The start of the string.\n * @param[in] fpc The current character from ragel.\n * @param[in,out] mp Temporary memory pool passed in by Ragel.\n * @return a buffer allocated from the tmpmp memory pool\n * available in ib_cfgparser_ragel_parse_chunk. This buffer may be\n * larger than the string stored in it if the length of the string is\n * reduced by Javascript unescaping.\n *\/\nstatic char* alloc_cpy_marked_string(char *fpc_mark,\n char *fpc,\n ib_mpool_t* mp)\n{\n char *afpc = fpc;\n size_t pvallen;\n \/* Adjust for quoted value. *\/\n if ((*fpc_mark == '\"') && (*(afpc-1) == '\"') && (fpc_mark+1 < afpc-2)) {\n fpc_mark++;\n afpc--;\n }\n pvallen = (size_t)(afpc - fpc_mark);\n pval = (char *)ib_mpool_alloc(mp, (pvallen + 1) * sizeof(*pval));\n\n ib_util_unescape_string(pval, &pvallen, fpc_mark, pvallen);\n\n \/* At this point the buffer i pvallen+1 in size, but we cannot shrink it. *\/\n \/* This is not considered a problem for configuration parsing and it is\n deallocated after parsing and configuration is complete. *\/\n return pval;\n}\n\n%%{\n machine ironbee_config;\n\n # Mark the start of a string.\n action mark { mark = fpc; }\n action error {\n ib_log_debug(ib, 4, \"ERROR: parser error before \\\"%.*s\\\"\", (int)(fpc - mark), mark);\n }\n\n # Parameter\n action push_param {\n pval = alloc_cpy_marked_string(mark, fpc, mpcfg);\n ib_list_push(plist, pval);\n }\n action push_blkparam {\n pval = alloc_cpy_marked_string(mark, fpc, mpcfg);\n ib_list_push(plist, pval);\n }\n\n # Directives\n action start_dir {\n size_t namelen = (size_t)(fpc - mark);\n dirname = (char *)calloc(namelen + 1, sizeof(*dirname));\n memcpy(dirname, mark, namelen);\n ib_list_clear(plist);\n }\n action push_dir {\n rc = ib_config_directive_process(cp, dirname, plist);\n if (rc != IB_OK) {\n ib_log_error(ib, 1, \"Failed to process directive \\\"%s\\\": %d\", dirname, rc);\n }\n if (dirname != NULL) {\n free(dirname);\n }\n }\n\n # Blocks\n action start_block {\n size_t namelen = (size_t)(fpc - mark);\n blkname = (char *)calloc(namelen + 1, sizeof(*blkname));\n memcpy(blkname, mark, namelen);\n ib_list_clear(plist);\n }\n action push_block {\n rc = ib_config_block_start(cp, blkname, plist);\n if (rc != IB_OK) {\n ib_log_error(ib, 1, \"Failed to start block \\\"%s\\\": %d\", blkname, rc);\n }\n }\n action pop_block {\n blkname = (char *)cp->cur_blkname;\n rc = ib_config_block_process(cp, blkname);\n if (rc != IB_OK) {\n ib_log_error(ib, 1, \"Failed to process block \\\"%s\\\": %d\", blkname, rc);\n }\n if (blkname != NULL) {\n free(blkname);\n }\n blkname = (char *)cp->cur_blkname;\n }\n\n WS = [ \\t];\n EOLSEQ = '\\r'? '\\n';\n EOL = WS* EOLSEQ;\n CONT = '\\\\' EOL;\n\n sep = WS+;\n qchar = '\\\\' any;\n qtoken = '\"' ( qchar | ( any - [\"\\\\] ) )* '\"';\n token = (qchar | (any - (WS | EOL | [<>#\"\\\\]))) (qchar | (any - ( WS | EOL | [<>\"\\\\])))*;\n param = qtoken | token;\n keyval = token '=' param;\n\n comment = '#' (any -- EOLSEQ)*;\n\n parameters := |*\n WS* param >mark %push_param $\/push_param $\/push_dir;\n EOL @push_dir { fret; };\n *|;\n\n block_parameters := |*\n WS* param >mark %push_blkparam;\n WS* \">\" @push_block { fret; };\n *|;\n\n newblock := |*\n WS* token >mark %start_block { fcall block_parameters; };\n EOL { fret; };\n *|;\n\n endblock := |*\n WS* token >mark %pop_block;\n WS* \">\" EOL { fret; };\n *|;\n\n main := |*\n WS* comment;\n WS* token >mark %start_dir { fcall parameters; };\n \"<\/\" { fcall endblock; };\n \"<\" { fcall newblock; };\n WS+;\n EOL;\n *|;\n}%%\n\n%% write data;\n\nib_status_t ib_cfgparser_ragel_parse_chunk(ib_cfgparser_t *cp,\n const char *buf,\n size_t blen,\n int is_last_chunk)\n{\n ib_engine_t *ib = cp->ib;\n ib_mpool_t *mptmp = ib_engine_pool_temp_get(ib);\n ib_mpool_t *mpcfg = ib_engine_pool_config_get(ib);\n ib_status_t rc;\n ib_list_t *plist;\n \/\/\/ @todo Which should be in cp???\n char *data = (char *)buf;\n fsm_t fsm;\n\n fsm.p = data;\n fsm.pe = data + blen;\n fsm.eof = (is_last_chunk ? fsm.pe : NULL);\n\n \/* Init *\/\n mark = fsm.p;\n memset(fsm.stack, 0, sizeof(fsm.stack));\n\n \/* Create a temporary list for storing parameter values. *\/\n ib_list_create(&plist, mptmp);\n if (plist == NULL) {\n return IB_EALLOC;\n }\n\n \/* Access all ragel state variables via structure. *\/\n %% access fsm.;\n %% variable p fsm.p;\n %% variable pe fsm.pe;\n %% variable eof fsm.eof;\n\n %% write init;\n %% write exec;\n\n return IB_OK;\n}\n\n","old_contents":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee - Configuration File Parser\n *\n * @author Brian Rectanus \n *\/\n\n#include \"ironbee_config_auto.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"config-parser.h\"\n#include \"ironbee_private.h\"\n\ntypedef struct {\n char *p;\n char *pe;\n char *eof;\n char *ts;\n char *te;\n int cs;\n int top;\n int act;\n int stack[1024];\n} fsm_t;\n\nstatic char *dirname = NULL;\nstatic char *blkname = NULL;\nstatic char *pval = NULL;\n\n\/* Store the start of a string to act on.\n fpc - mark is the string length when processing after\n a mark action. *\/\nstatic char *mark = NULL;\n\n\/**\n * @brief Malloc and unescape into that buffer the marked string.\n * @param[in] fpc_mark The start of the string.\n * @param[in] fpc The current character from ragel.\n * @param[in,out] mp Temporary memory pool passed in by Ragel.\n * @return a buffer allocated from the tmpmp memory pool\n * available in ib_cfgparser_ragel_parse_chunk. This buffer may be\n * larger than the string stored in it if the length of the string is\n * reduced by Javascript unescaping.\n *\/\nstatic char* alloc_cpy_marked_string(char *fpc_mark,\n char *fpc,\n ib_mpool_t* mp)\n{\n char *afpc = fpc;\n size_t pvallen;\n \/* Adjust for quoted value. *\/\n if ((*fpc_mark == '\"') && (*(afpc-1) == '\"') && (fpc_mark+1 < afpc-2)) {\n fpc_mark++;\n afpc--;\n }\n pvallen = (size_t)(afpc - fpc_mark);\n pval = (char *)ib_mpool_alloc(mp, (pvallen + 1) * sizeof(*pval));\n\n ib_util_unescape_string(pval, &pvallen, fpc_mark, pvallen);\n\n \/* At this point the buffer i pvallen+1 in size, but we cannot shrink it. *\/\n \/* This is not considered a problem for configuration parsing and it is\n deallocated after parsing and configuration is complete. *\/\n return pval;\n}\n\n%%{\n machine ironbee_config;\n\n # Mark the start of a string.\n action mark { mark = fpc; }\n action error {\n ib_log_debug(ib, 4, \"ERROR: parser error before \\\"%.*s\\\"\", (int)(fpc - mark), mark);\n }\n\n # Parameter\n action push_param {\n pval = alloc_cpy_marked_string(mark, fpc, mpcfg);\n ib_list_push(plist, pval);\n }\n action push_blkparam {\n pval = alloc_cpy_marked_string(mark, fpc, mpcfg);\n ib_list_push(plist, pval);\n }\n\n # Directives\n action start_dir {\n size_t namelen = (size_t)(fpc - mark);\n dirname = (char *)calloc(namelen + 1, sizeof(*dirname));\n memcpy(dirname, mark, namelen);\n ib_list_clear(plist);\n }\n action push_dir {\n rc = ib_config_directive_process(cp, dirname, plist);\n if (rc != IB_OK) {\n ib_log_error(ib, 1, \"Failed to process directive \\\"%s\\\": %d\", dirname, rc);\n }\n if (dirname != NULL) {\n free(dirname);\n }\n }\n\n # Blocks\n action start_block {\n size_t namelen = (size_t)(fpc - mark);\n blkname = (char *)calloc(namelen + 1, sizeof(*blkname));\n memcpy(blkname, mark, namelen);\n ib_list_clear(plist);\n }\n action push_block {\n rc = ib_config_block_start(cp, blkname, plist);\n if (rc != IB_OK) {\n ib_log_error(ib, 1, \"Failed to start block \\\"%s\\\": %d\", blkname, rc);\n }\n }\n action pop_block {\n blkname = (char *)cp->cur_blkname;\n rc = ib_config_block_process(cp, blkname);\n if (rc != IB_OK) {\n ib_log_error(ib, 1, \"Failed to process block \\\"%s\\\": %d\", blkname, rc);\n }\n if (blkname != NULL) {\n free(blkname);\n }\n blkname = (char *)cp->cur_blkname;\n }\n\n WS = [ \\t];\n EOLSEQ = '\\r'? '\\n';\n EOL = WS* EOLSEQ;\n CONT = '\\\\' EOL;\n\n sep = WS+;\n qchar = '\\\\' any;\n qtoken = '\"' ( qchar | ( any - [\"\\\\] ) )* '\"';\n token = (qchar | (any - (WS | EOL | [<>#\"\\\\]))) (qchar | (any - ( WS | EOL | [<>\"\\\\])))*;\n param = qtoken | token;\n keyval = token '=' param;\n\n comment = '#' (any -- EOLSEQ)*;\n\n parameters := |*\n WS* param >mark %push_param $\/push_param $\/push_dir;\n EOL @push_dir { fret; };\n *|;\n\n block_parameters := |*\n WS* param >mark %push_blkparam;\n WS* \">\" @push_block { fret; };\n *|;\n\n newblock := |*\n WS* token >mark %start_block { fcall block_parameters; };\n EOL { fret; };\n *|;\n\n endblock := |*\n WS* token >mark %pop_block;\n WS* \">\" EOL { fret; };\n *|;\n\n main := |*\n WS* comment;\n WS* token >mark %start_dir { fcall parameters; };\n \"<\/\" { fcall endblock; };\n \"<\" { fcall newblock; };\n WS+;\n EOL;\n *|;\n}%%\n\n%% write data;\n\nib_status_t ib_cfgparser_ragel_parse_chunk(ib_cfgparser_t *cp,\n const char *buf,\n size_t blen,\n int is_last_block)\n{\n ib_engine_t *ib = cp->ib;\n ib_mpool_t *mptmp = ib_engine_pool_temp_get(ib);\n ib_mpool_t *mpcfg = ib_engine_pool_config_get(ib);\n ib_status_t rc;\n ib_list_t *plist;\n \/\/\/ @todo Which should be in cp???\n char *data = (char *)buf;\n fsm_t fsm;\n\n fsm.p = data;\n fsm.pe = data + blen;\n fsm.eof = (is_last_block? fsm.pe : NULL);\n\n \/* Init *\/\n mark = fsm.p;\n memset(fsm.stack, 0, sizeof(fsm.stack));\n\n \/* Create a temporary list for storing parameter values. *\/\n ib_list_create(&plist, mptmp);\n if (plist == NULL) {\n return IB_EALLOC;\n }\n\n \/* Access all ragel state variables via structure. *\/\n %% access fsm.;\n %% variable p fsm.p;\n %% variable pe fsm.pe;\n %% variable eof fsm.eof;\n\n %% write init;\n %% write exec;\n\n return IB_OK;\n}\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"66ee4a0b4d202f7a67f7c0ba673c72bc916137ca","subject":"Remove trace level log message.","message":"Remove trace level log message.\n","repos":"ironbee\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,b1v1r\/ironbee,ironbee\/ironbee,b1v1r\/ironbee,ironbee\/ironbee","old_file":"engine\/config-parser.rl","new_file":"engine\/config-parser.rl","new_contents":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee --- Configuration File Parser\n *\n * @author Brian Rectanus \n *\/\n\n#include \"ironbee_config_auto.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"config-parser.h\"\n#include \"config_private.h\"\n\n\/* Caused by Ragel *\/\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wunreachable-code\"\n#endif\n\n\/**\n * Variables used by the finite state machine per-call.\n * Values here do not have to persist across calls to\n * ib_cfgparser_ragel_parse_chunk().\n *\/\ntypedef struct {\n const char *p; \/**< Pointer to the chunk being parsed. *\/\n const char *pe; \/**< Pointer past the end of p (p+length(p)). *\/\n const char *eof; \/**< eof==p==pe on last chunk. NULL otherwise. *\/\n} fsm_vars_t;\n\n\/**\n * Append @a c to the internal buffer of @a cp.\n * @param[in] cp Configuration parser.\n * @param[in] c Char to append.\n * @returns\n * - IB_OK\n * - IB_EALLOC if there is no space left in the buffer.\n *\/\nstatic ib_status_t cpbuf_append(ib_cfgparser_t *cp, char c)\n{\n assert(cp != NULL);\n assert(cp->buffer != NULL);\n\n \/* Protect against run-away token aggregation. 1k should be enough? *\/\n if (cp->buffer->len >= 1024) {\n ib_cfg_log_error(\n cp,\n \"Token size limit exceeded. Will not grow past %zu characters.\",\n cp->buffer->len);\n ib_cfg_log_trace(\n cp,\n \"Current buffer is [[[[%.*s]]]]\",\n (int) cp->buffer->len,\n (char *)cp->buffer->data);\n return IB_EALLOC;\n }\n\n return ib_vector_append(cp->buffer, &c, 1);\n}\n\n\/**\n * Clear the buffer in @a cp.\n * @param[in] cp Configuration parser.\n *\/\nstatic void cpbuf_clear(ib_cfgparser_t *cp) {\n assert(cp != NULL);\n assert(cp->buffer != NULL);\n ib_status_t rc;\n\n rc = ib_vector_truncate(cp->buffer, 0);\n if (rc != IB_OK) {\n ib_cfg_log_error(\n cp,\n \"Failed to truncate token buffer: %s\",\n ib_status_to_string(rc));\n }\n}\n\n\/**\n * Using the given mp, strdup the buffer in @a cp consiering quotes.\n *\n * If the buffer starts and ends with double quotes, remove them.\n *\n * @param[in] cp The configuration parser\n * @param[in,out] mp Pool to copy out of.\n *\n * @return a buffer allocated from the temp_mp memory pool\n * available in ib_cfgparser_ragel_parse_chunk. This buffer may be\n * larger than the string stored in it if the length of the string is\n * reduced by Javascript unescaping.\n *\/\nstatic char *qstrdup(ib_cfgparser_t *cp, ib_mpool_t* mp)\n{\n const char *start = (const char *)cp->buffer->data;\n const char *end = (const char *)(cp->buffer->data + cp->buffer->len - 1);\n size_t len = cp->buffer->len;\n\n \/* Adjust for quoted value. *\/\n if ((*start == '\"') && (*end == '\"') && (start < end)) {\n start++;\n len -= 2;\n }\n\n return ib_mpool_memdup_to_str(mp, start, len);\n}\n\n\/**\n * Callback function to handel parsing of parser directives.\n *\/\ntypedef ib_status_t(*parse_directive_fn_t)(\n ib_cfgparser_t *cp,\n ib_mpool_t* tmp_mp,\n ib_cfgparser_node_t *node);\n\n\/**\n * A table entry mapping a parse directive string to a handler function.\n *\/\nstruct parse_directive_entry_t {\n const char *directive; \/**< The directive. Case insensitive. *\/\n parse_directive_fn_t fn; \/**< The handler function. *\/\n};\ntypedef struct parse_directive_entry_t parse_directive_entry_t;\n\n\/**\n * Ensure that the node's file:line has not been encountered before.\n *\n * @param[in] cp Configuration parser.\n * @param[in] node The current parse node.\n * @returns\n * - IB_OK if the directive represented by @a node is new (not a dup).\n * - IB_EINVAL if we detect that @a node's file and line have been seen before.\n * - IB_EALLOC on allocation errors.\n * - Other if there is an internal IronBee error.\n *\/\nstatic ib_status_t detect_file_loop(\n ib_cfgparser_t *cp,\n ib_cfgparser_node_t *node\n) {\n assert(cp != NULL);\n assert(cp->mp != NULL);\n assert(node != NULL);\n assert(node->file != NULL);\n\n for (ib_cfgparser_node_t *node2 = node->parent;\n node2 != NULL;\n node2 = node2->parent)\n {\n \/* If a node is at the same file and line, it is clearly a duplciate. *\/\n if (node2->type == IB_CFGPARSER_NODE_PARSE_DIRECTIVE\n && node->line == node2->line\n && strcmp(node->file, node2->file) == 0)\n {\n ib_cfg_log_error(\n cp,\n \"File include cycle found at %s:%zu.\",\n node->file,\n node->line);\n\n for (ib_cfgparser_node_t *node3 = node->parent;\n node3 != NULL;\n node3 = node3->parent)\n {\n \/* Skip nodes that are not parse directives,\n * such as the root node and file nodes. *\/\n if (node3->type == IB_CFGPARSER_NODE_PARSE_DIRECTIVE) {\n ib_cfg_log_error(\n cp,\n \"\\t... %s included from %s:%zu.\",\n node3->directive,\n node3->file,\n node3->line);\n }\n }\n\n return IB_EINVAL;\n }\n }\n\n return IB_OK;\n}\n\n\/**\n * Implementation of \"Include\" and \"IncludeIfExists\" parse directives.\n * param[in] cp Configuration parser.\n * param[in] mp Memory pool to use.\n * param[in] node The parse node containing the directive.\n *\n * @returns\n * - IB_OK on success.\n * - Any other code causes a general failure to be repoted but the\n * parse continues.\n *\/\nstatic ib_status_t include_parse_directive_impl(\n ib_cfgparser_t *cp,\n ib_mpool_t *tmp_mp,\n ib_cfgparser_node_t *node,\n bool if_exists\n) {\n assert(cp != NULL);\n assert(cp->mp != NULL);\n assert(node != NULL);\n assert(node->directive != NULL);\n assert(node->params != NULL);\n assert(node->file != NULL);\n\n struct stat statbuf;\n ib_status_t rc;\n ib_mpool_t *mp = cp->mp;\n int statval;\n char *incfile;\n char *real;\n const char* pval;\n const ib_list_node_t *list_node;\n\n \/* A temporary local value to store the parser state in.\n * We allocate this from local_mp to avoid putting the very large\n * buffer variable in fsm on the stack. *\/\n ib_cfgparser_fsm_t *fsm;\n\n ib_cfgparser_node_t *current_node;\n ib_mpool_t *local_mp = NULL;\n\n rc = ib_mpool_create(&local_mp, \"local_mp\", tmp_mp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Failed to create local memory pool.\");\n goto cleanup;\n }\n\n if (ib_list_elements(node->params) != 1) {\n ib_cfg_log_error(\n cp,\n \"%s: %zu - Directive %s only takes 1 parameter not %zu.\",\n node->file,\n node->line,\n node->directive,\n ib_list_elements(node->params));\n rc = IB_EINVAL;\n goto cleanup;\n }\n\n \/* Grab the first parameter node. *\/\n list_node = ib_list_first_const(node->params);\n assert(list_node != NULL);\n\n \/* Grab the parameter value. *\/\n pval = (const char*) ib_list_node_data_const(list_node);\n assert(pval != NULL);\n\n if_exists = strcasecmp(\"IncludeIfExists\", node->directive) == 0;\n\n incfile = ib_util_relative_file(mp, node->file, pval);\n if (incfile == NULL) {\n ib_cfg_log_error(cp, \"Failed to resolve included file \\\"%s\\\": %s\",\n node->file, strerror(errno));\n ib_mpool_release(local_mp);\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n real = ib_mpool_alloc(local_mp, PATH_MAX);\n if (real == NULL) {\n ib_cfg_log_error(\n cp,\n \"Failed to allocate path buffer of size %d\",\n PATH_MAX);\n rc = IB_EALLOC;\n goto cleanup;\n }\n real = realpath(incfile, real);\n if (real == NULL) {\n if (!if_exists) {\n ib_cfg_log_error(cp,\n \"Failed to find real path of included file \"\n \"(using original \\\"%s\\\"): %s\",\n incfile, strerror(errno));\n }\n else {\n ib_cfg_log_warning(\n cp,\n \"Failed to normalize path. Using raw include path: %s\",\n incfile);\n }\n\n real = incfile;\n }\n else if (strcmp(real, incfile) != 0) {\n ib_cfg_log_info(\n cp,\n \"Real path of included file \\\"%s\\\" is \\\"%s\\\"\",\n incfile,\n real);\n }\n else {\n ib_cfg_log_info(\n cp,\n \"Including file \\\"%s\\\"\",\n incfile);\n }\n\n rc = detect_file_loop(cp, node);\n if (rc != IB_OK) {\n goto cleanup;\n }\n\n if (access(incfile, R_OK) != 0) {\n if (if_exists) {\n ib_cfg_log(\n cp, (errno == ENOENT) ? IB_LOG_DEBUG : IB_LOG_NOTICE,\n \"Ignoring include file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_error(\n cp,\n \"Cannot access included file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n statval = stat(incfile, &statbuf);\n if (statval != 0) {\n if (if_exists) {\n ib_cfg_log(\n cp, (errno == ENOENT) ? IB_LOG_DEBUG : IB_LOG_NOTICE,\n \"Ignoring include file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_error(\n cp,\n \"Failed to stat include file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n if (S_ISREG(statbuf.st_mode) == 0) {\n if (if_exists) {\n ib_cfg_log_info(\n cp,\n \"Ignoring include file \\\"%s\\\": Not a regular file\",\n incfile);\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_error(\n cp,\n\t \"Included file \\\"%s\\\" is not a regular file\",\n incfile);\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n ib_cfg_log_debug(cp, \"Including '%s'\", incfile);\n\n \/* Make the given node the current node for the file inclusion. *\/\n current_node = cp->curr;\n cp->curr = node;\n\n \/* Allocate fsm in the heap as it contains a very large buffer. *\/\n fsm = ib_mpool_alloc(local_mp, sizeof(*fsm));\n if (fsm == NULL) {\n rc = IB_EALLOC;\n goto cleanup;\n }\n\n \/* Store current fsm. *\/\n *fsm = cp->fsm;\n\n \/* Initialize new fsm in cp. *\/\n rc = ib_cfgparser_ragel_init(cp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Could not initialize new parser.\");\n return rc;\n }\n\n rc = ib_cfgparser_parse_private(cp, incfile, false);\n \/* Restore fsm. *\/\n cp->fsm = *fsm;\n cp->curr = current_node;\n if (rc != IB_OK) {\n ib_cfg_log_error(\n cp,\n \"Error parsing included file \\\"%s\\\": %s\",\n\t incfile,\n ib_status_to_string(rc));\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_debug(cp, \"Done processing include file \\\"%s\\\"\", incfile);\n\ncleanup:\n if (local_mp != NULL) {\n ib_mpool_release(local_mp);\n }\n return rc;\n}\n\n\/\/! Proxy to include_parse_directive_impl with if_exists = true.\nstatic ib_status_t include_if_exists_parse_directive(\n ib_cfgparser_t *cp,\n ib_mpool_t *tmp_mp,\n ib_cfgparser_node_t *node\n) {\n return include_parse_directive_impl(cp, tmp_mp, node, true);\n}\n\n\/\/! Proxy to include_parse_directive_impl with if_exists = false.\nstatic ib_status_t include_parse_directive(\n ib_cfgparser_t *cp,\n ib_mpool_t *tmp_mp,\n ib_cfgparser_node_t *node\n) {\n return include_parse_directive_impl(cp, tmp_mp, node, false);\n}\n\nstatic ib_status_t loglevel_parse_directive(\n ib_cfgparser_t *cp,\n ib_mpool_t* tmp_mp,\n ib_cfgparser_node_t *node\n) {\n assert(cp != NULL);\n assert(node != NULL);\n assert(node->directive != NULL);\n assert(node->params != NULL);\n\n ib_cfg_log_debug(cp, \"Applying new log level.\");\n\n return ib_config_directive_process(cp, node->directive, node->params);\n}\n\n\/**\n * Null-terminated table that maps parsing directives to handler functions.\n *\/\nstatic parse_directive_entry_t parse_directive_table[] = {\n { \"IncludeIfExists\", include_if_exists_parse_directive },\n { \"Include\", include_parse_directive },\n { \"LogLevel\", loglevel_parse_directive },\n { NULL, NULL } \/* Null termination. Do not remove. *\/\n};\n\n%%{\n machine ironbee_config;\n\n prepush {\n if (cp->fsm.top >= 1023) {\n ib_cfg_log_debug(cp, \"Recursion too deep during parse.\");\n return IB_EOTHER;\n }\n }\n\n postpop {\n }\n\n action error_action {\n rc = IB_EOTHER;\n ib_cfg_log_error(\n cp,\n \"parser error near %s:%zu.\",\n cp->curr->file,\n cp->curr->line);\n ib_cfg_log_debug(cp, \"Current buffer is [[[[%.*s]]]]\", (int)blen, buf);\n }\n\n # Parameter\n action push_param {\n tmp_str = qstrdup(cp, config_mp);\n if (tmp_str == NULL) {\n return IB_EALLOC;\n }\n ib_list_push(cp->fsm.plist, tmp_str);\n tmp_str = NULL;\n cpbuf_clear(cp);\n }\n action push_blkparam {\n tmp_str = qstrdup(cp, config_mp);\n if (tmp_str == NULL) {\n return IB_EALLOC;\n }\n ib_list_push(cp->fsm.plist, tmp_str);\n tmp_str = NULL;\n cpbuf_clear(cp);\n }\n\n action newline {\n cp->curr->line += 1;\n }\n\n # Directives\n action start_dir {\n if (cp->buffer->len == 0) {\n ib_cfg_log_error(cp, \"Directive name is 0 length.\");\n return IB_EOTHER;\n }\n cp->fsm.directive =\n ib_mpool_memdup_to_str(cp->mp, cp->buffer->data, cp->buffer->len);\n if (cp->fsm.directive == NULL) {\n return IB_EALLOC;\n }\n ib_list_clear(cp->fsm.plist);\n cpbuf_clear(cp);\n }\n action push_dir {\n ib_cfgparser_node_t *node = NULL;\n ib_cfgparser_node_create(&node, cp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot create node.\");\n return rc;\n }\n node->directive = cp->fsm.directive;\n cp->fsm.directive = NULL;\n node->file = ib_mpool_strdup(cp->mp, cp->curr->file);\n if (node->file == NULL) {\n return IB_EALLOC;\n }\n node->parent = cp->curr;\n node->line = cp->curr->line;\n node->type = IB_CFGPARSER_NODE_DIRECTIVE;\n ib_list_node_t *lst_node;\n IB_LIST_LOOP(cp->fsm.plist, lst_node) {\n ib_list_push(node->params, ib_list_node_data(lst_node));\n }\n ib_list_push(cp->curr->children, node);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Out of memory.\");\n }\n\n \/* Handle parse directives using the parse_directive_table. *\/\n for (int i = 0; parse_directive_table[i].directive != NULL; ++i) {\n if (\n strcasecmp(\n parse_directive_table[i].directive,\n node->directive) == 0\n ) {\n \/* Change the node type. This is an parse directive. *\/\n node->type = IB_CFGPARSER_NODE_PARSE_DIRECTIVE;\n \/* Process directive. *\/\n cpbuf_clear(cp);\n rc = (parse_directive_table[i].fn)(cp, temp_mp, node);\n if (rc != IB_OK) {\n ib_cfg_log_error(\n cp,\n \"Parse directive %s failed.\",\n node->directive);\n }\n else {\n ib_cfg_log_debug(\n cp,\n \"Parse directive %s succeeded.\",\n node->directive);\n }\n }\n }\n }\n\n action cpbuf_append {\n if (cpbuf_append(cp, *fpc) != IB_OK) {\n return IB_EALLOC;\n }\n }\n\n # Blocks\n action start_block {\n if (cp->buffer->len == 0) {\n ib_cfg_log_error(cp, \"Block name is 0 length.\");\n return IB_EOTHER;\n }\n cp->fsm.blkname =\n ib_mpool_memdup_to_str(cp->mp, cp->buffer->data, cp->buffer->len);\n if (cp->fsm.blkname == NULL) {\n return IB_EALLOC;\n }\n ib_list_clear(cp->fsm.plist);\n cpbuf_clear(cp);\n }\n action push_block {\n ib_cfgparser_node_t *node = NULL;\n rc = ib_cfgparser_node_create(&node, cp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot create node.\");\n return rc;\n }\n node->directive = cp->fsm.blkname;\n \/* NOTE: We do not clear blkname now. *\/\n node->file = ib_mpool_strdup(cp->mp, cp->curr->file);\n if (node->file == NULL) {\n return IB_EALLOC;\n }\n node->line = cp->curr->line;\n node->type = IB_CFGPARSER_NODE_BLOCK;\n ib_list_node_t *lst_node;\n IB_LIST_LOOP(cp->fsm.plist, lst_node) {\n ib_cfg_log_debug(\n cp,\n \"Adding param \\\"%s\\\" to SBLK1 %s (node = %p)\",\n (const char *)ib_list_node_data(lst_node),\n node->directive,\n node);\n rc = ib_list_push(node->params, ib_list_node_data(lst_node));\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot push directive.\");\n return rc;\n }\n }\n rc = ib_cfgparser_push_node(cp, node);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot push node.\");\n return rc;\n }\n }\n action pop_block {\n ib_cfgparser_pop_node(cp);\n cpbuf_clear(cp);\n cp->fsm.blkname = NULL;\n }\n\n # include file logic\n # Whitespace.\n WS = [ \\t];\n # End of line.\n EOL = '\\r'? '\\n';\n # Continuation.\n CONT = '\\\\' EOL;\n\n qchar = '\\\\' any;\n qtoken = '\"' ( qchar | ( any - [\"\\\\] ) )* '\"';\n token = (qchar | (any - (WS | '\\r' | '\\n' | [<>#\"\\\\])))\n (qchar | (any - (WS | '\\r' | '\\n' | [<>\"\\\\])))*;\n param = qtoken | token;\n\n # A comment is any string starting with # and not including a newline.\n comment = '#' (any - ('\\r' | '\\n'))*;\n\n # The parameters machine pull in parameter.\n parameters := |*\n WS;\n CONT $newline;\n EOL $newline\n @push_dir { fret; };\n param $cpbuf_append\n %push_param\n $\/push_param\n $\/push_dir\n $err{ fhold; fret; }\n $eof{ fhold; fret; };\n *|;\n\n block_parameters := |*\n WS;\n CONT $newline;\n \">\" @push_block\n { fret; };\n param $cpbuf_append\n %push_blkparam\n $err{ fhold; fret; };\n *|;\n\n newblock := |*\n WS;\n CONT $newline\n $!error_action { fhold; fret; };\n EOL $newline\n $!error_action { fhold; fret; };\n token $cpbuf_append\n %start_block\n $!error_action\n { fcall block_parameters; };\n *|;\n\n endblock := |*\n WS $eof(error_action);\n CONT $newline\n $eof(error_action);\n\tEOL $newline\n $eof(error_action);\n token $cpbuf_append\n $!error_action\n %pop_block\n $eof(error_action);\n \">\" $eof(error_action)\n { fret; };\n *|;\n\n main := |*\n comment;\n\n # A directive.\n token $cpbuf_append\n %start_dir\n { fcall parameters; };\n\n # Handle block configurations .\n \"<\" (any - \"\/\") { fhold; fcall newblock;};\n \"<\/\" { fcall endblock;};\n\n # Eat space.\n WS;\n CONT $newline;\n EOL $newline;\n \">\" {\n ib_cfg_log_error(\n cp,\n \"Character \\\">\\\" encountered outside a block tag.\");\n rc = IB_EOTHER;\n fbreak;\n };\n *|;\n}%%\n\n%% write data;\n\nib_status_t ib_cfgparser_ragel_init(ib_cfgparser_t *cp) {\n assert(cp != NULL);\n assert(cp->ib != NULL);\n assert(cp->mp != NULL);\n\n ib_status_t rc;\n\n ib_cfg_log_debug(cp, \"Initializing Ragel state machine.\");\n\n \/* Access all ragel state variables via structure. *\/\n %% access cp->fsm.;\n\n %% write init;\n\n ib_cfg_log_info(cp, \"Initializing IronBee parse values.\");\n\n rc = ib_list_create(&(cp->fsm.plist), cp->mp);\n if (rc != IB_OK) {\n return rc;\n }\n\n cp->fsm.directive = NULL;\n cp->fsm.blkname = NULL;\n\n rc = ib_vector_create(&(cp->fsm.ts_buffer), cp->mp, 0);\n if (rc != IB_OK) {\n return rc;\n }\n\n return IB_OK;\n}\n\n\/**\n * If Ragel has a partial match we must preserve the buffer\n * until next time to continue the match.\n * This effects how the machine is restarted on\n * the next call to ib_cfgparser_ragel_parse_chunk.\n *\/\nstatic ib_status_t cfgparser_partial_match_maintenance(\n ib_cfgparser_t *cp,\n const char *buf,\n const size_t blen\n)\n{\n ib_status_t rc;\n size_t buffer_remaining = buf + blen - cp->fsm.ts;\n\n \/* Distance that the ts and te pointers will be shifted when\n * copied into the vector. *\/\n ssize_t delta;\n\n rc = ib_vector_truncate(cp->fsm.ts_buffer, 0);\n if (rc != IB_OK) {\n return rc;\n }\n\n\n rc = ib_vector_append(cp->fsm.ts_buffer, cp->fsm.ts, buffer_remaining);\n if (rc != IB_OK) {\n return rc;\n }\n\n delta = (char *)cp->fsm.ts_buffer->data - cp->fsm.ts;\n\n \/* Relocate ts and te into the buffer. *\/\n cp->fsm.te += delta;\n cp->fsm.ts += delta;\n\n return IB_OK;\n}\n\n\/**\n * If Ragel has a partial match we must resume parsing in \n * a special buffer we are maintaining.\n * @param[in] cp Configuration parser. The cp->fsm structure is updated.\n * @param[in] buf Buffer to append to cp->fsm.ts_buffer.\n * @param[in] blen Length of the buffer to append to cp->fsm.ts_buffer.\n * @param[out] fsm_vars The p field is updated to point to \n * the new location of buffer.\n *\/\nstatic ib_status_t cfgparser_partial_match_resume(\n ib_cfgparser_t *cp,\n const char *buf,\n const size_t blen\n)\n{\n ib_status_t rc;\n\n \/* Store the previous data pointer so we can detect if it moves. *\/\n void *orig_data = cp->fsm.ts_buffer->data;\n\n \/* Append the input buffer. *\/\n rc = ib_vector_append(cp->fsm.ts_buffer, (uint8_t *)buf, blen);\n if (rc != IB_OK) {\n return rc;\n }\n\n if (orig_data != cp->fsm.ts_buffer->data) {\n \/* Update ts and te *\/\n ssize_t delta = cp->fsm.ts_buffer->data - orig_data;\n\n cp->fsm.ts += delta;\n cp->fsm.te += delta;\n }\n\n return IB_OK;\n}\n\nib_status_t ib_cfgparser_ragel_parse_chunk(\n ib_cfgparser_t *cp,\n const char *buf,\n const size_t blen,\n const int is_last_chunk)\n{\n assert(cp != NULL);\n assert(cp->ib != NULL);\n\n ib_engine_t *ib_engine = cp->ib;\n\n \/* Temporary memory pool. *\/\n ib_mpool_t *temp_mp = ib_engine_pool_temp_get(ib_engine);\n\n \/* Configuration memory pool. *\/\n ib_mpool_t *config_mp = ib_engine_pool_config_get(ib_engine);\n\n \/* Error actions will update this. *\/\n ib_status_t rc = IB_OK;\n\n \/* Create a finite state machine type. *\/\n fsm_vars_t fsm_vars = { buf, NULL, 0 };\n\n \/* A temporary string. This is used to fetch values, check them\n * for NULL, and then pass them on to an owning collection (list). *\/\n char *tmp_str = NULL;\n\n \/* Point the machine at the current buffer to parse.\n *\/\n if (cp->fsm.ts != NULL) {\n rc = cfgparser_partial_match_resume(cp, buf, blen);\n if (rc != IB_OK) {\n return rc;\n }\n\n \/* Buffer start = prev buffer end. *\/\n fsm_vars.p = cp->fsm.te;\n }\n else {\n fsm_vars.p = buf;\n }\n fsm_vars.pe = fsm_vars.p + blen;\n fsm_vars.eof = (is_last_chunk ? fsm_vars.pe : NULL);\n\n \/* Access all ragel state variables via structure. *\/\n %% access cp->fsm.;\n %% variable p fsm_vars.p;\n %% variable pe fsm_vars.pe;\n %% variable eof fsm_vars.eof;\n\n %% write exec;\n\n assert(tmp_str == NULL && \"tmp_str must be cleared after every use\");\n\n \/* Buffer maintenance code. *\/\n if (cp->fsm.ts != NULL) {\n rc = cfgparser_partial_match_maintenance(cp, buf, blen);\n if (rc != IB_OK) {\n return rc;\n }\n }\n\n \/* On the last chunk, sanity check things. *\/\n if (is_last_chunk) {\n if (cp->fsm.blkname != NULL) {\n ib_cfg_log_error(\n cp,\n \"Unpushed block \\\"%s\\\" at end of config input\",\n cp->fsm.blkname);\n return IB_EINVAL;\n }\n if (cp->fsm.directive != NULL) {\n ib_cfg_log_error(\n cp,\n \"Unpushed directive \\\"%s\\\" end of config input\",\n cp->fsm.directive);\n return IB_EINVAL;\n }\n }\n\n return rc;\n}\n","old_contents":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee --- Configuration File Parser\n *\n * @author Brian Rectanus \n *\/\n\n#include \"ironbee_config_auto.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"config-parser.h\"\n#include \"config_private.h\"\n\n\/* Caused by Ragel *\/\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wunreachable-code\"\n#endif\n\n\/**\n * Variables used by the finite state machine per-call.\n * Values here do not have to persist across calls to\n * ib_cfgparser_ragel_parse_chunk().\n *\/\ntypedef struct {\n const char *p; \/**< Pointer to the chunk being parsed. *\/\n const char *pe; \/**< Pointer past the end of p (p+length(p)). *\/\n const char *eof; \/**< eof==p==pe on last chunk. NULL otherwise. *\/\n} fsm_vars_t;\n\n\/**\n * Append @a c to the internal buffer of @a cp.\n * @param[in] cp Configuration parser.\n * @param[in] c Char to append.\n * @returns\n * - IB_OK\n * - IB_EALLOC if there is no space left in the buffer.\n *\/\nstatic ib_status_t cpbuf_append(ib_cfgparser_t *cp, char c)\n{\n assert(cp != NULL);\n assert(cp->buffer != NULL);\n\n \/* Protect against run-away token aggregation. 1k should be enough? *\/\n if (cp->buffer->len >= 1024) {\n ib_cfg_log_error(\n cp,\n \"Token size limit exceeded. Will not grow past %zu characters.\",\n cp->buffer->len);\n ib_cfg_log_trace(\n cp,\n \"Current buffer is [[[[%.*s]]]]\",\n (int) cp->buffer->len,\n (char *)cp->buffer->data);\n return IB_EALLOC;\n }\n\n return ib_vector_append(cp->buffer, &c, 1);\n}\n\n\/**\n * Clear the buffer in @a cp.\n * @param[in] cp Configuration parser.\n *\/\nstatic void cpbuf_clear(ib_cfgparser_t *cp) {\n assert(cp != NULL);\n assert(cp->buffer != NULL);\n ib_status_t rc;\n\n rc = ib_vector_truncate(cp->buffer, 0);\n if (rc != IB_OK) {\n ib_cfg_log_error(\n cp,\n \"Failed to truncate token buffer: %s\",\n ib_status_to_string(rc));\n }\n}\n\n\/**\n * Using the given mp, strdup the buffer in @a cp consiering quotes.\n *\n * If the buffer starts and ends with double quotes, remove them.\n *\n * @param[in] cp The configuration parser\n * @param[in,out] mp Pool to copy out of.\n *\n * @return a buffer allocated from the temp_mp memory pool\n * available in ib_cfgparser_ragel_parse_chunk. This buffer may be\n * larger than the string stored in it if the length of the string is\n * reduced by Javascript unescaping.\n *\/\nstatic char *qstrdup(ib_cfgparser_t *cp, ib_mpool_t* mp)\n{\n const char *start = (const char *)cp->buffer->data;\n const char *end = (const char *)(cp->buffer->data + cp->buffer->len - 1);\n size_t len = cp->buffer->len;\n\n \/* Adjust for quoted value. *\/\n if ((*start == '\"') && (*end == '\"') && (start < end)) {\n start++;\n len -= 2;\n }\n\n return ib_mpool_memdup_to_str(mp, start, len);\n}\n\n\/**\n * Callback function to handel parsing of parser directives.\n *\/\ntypedef ib_status_t(*parse_directive_fn_t)(\n ib_cfgparser_t *cp,\n ib_mpool_t* tmp_mp,\n ib_cfgparser_node_t *node);\n\n\/**\n * A table entry mapping a parse directive string to a handler function.\n *\/\nstruct parse_directive_entry_t {\n const char *directive; \/**< The directive. Case insensitive. *\/\n parse_directive_fn_t fn; \/**< The handler function. *\/\n};\ntypedef struct parse_directive_entry_t parse_directive_entry_t;\n\n\/**\n * Ensure that the node's file:line has not been encountered before.\n *\n * @param[in] cp Configuration parser.\n * @param[in] node The current parse node.\n * @returns\n * - IB_OK if the directive represented by @a node is new (not a dup).\n * - IB_EINVAL if we detect that @a node's file and line have been seen before.\n * - IB_EALLOC on allocation errors.\n * - Other if there is an internal IronBee error.\n *\/\nstatic ib_status_t detect_file_loop(\n ib_cfgparser_t *cp,\n ib_cfgparser_node_t *node\n) {\n assert(cp != NULL);\n assert(cp->mp != NULL);\n assert(node != NULL);\n assert(node->file != NULL);\n\n for (ib_cfgparser_node_t *node2 = node->parent;\n node2 != NULL;\n node2 = node2->parent)\n {\n \/* If a node is at the same file and line, it is clearly a duplciate. *\/\n if (node2->type == IB_CFGPARSER_NODE_PARSE_DIRECTIVE\n && node->line == node2->line\n && strcmp(node->file, node2->file) == 0)\n {\n ib_cfg_log_error(\n cp,\n \"File include cycle found at %s:%zu.\",\n node->file,\n node->line);\n\n for (ib_cfgparser_node_t *node3 = node->parent;\n node3 != NULL;\n node3 = node3->parent)\n {\n \/* Skip nodes that are not parse directives,\n * such as the root node and file nodes. *\/\n if (node3->type == IB_CFGPARSER_NODE_PARSE_DIRECTIVE) {\n ib_cfg_log_error(\n cp,\n \"\\t... %s included from %s:%zu.\",\n node3->directive,\n node3->file,\n node3->line);\n }\n }\n\n return IB_EINVAL;\n }\n }\n\n return IB_OK;\n}\n\n\/**\n * Implementation of \"Include\" and \"IncludeIfExists\" parse directives.\n * param[in] cp Configuration parser.\n * param[in] mp Memory pool to use.\n * param[in] node The parse node containing the directive.\n *\n * @returns\n * - IB_OK on success.\n * - Any other code causes a general failure to be repoted but the\n * parse continues.\n *\/\nstatic ib_status_t include_parse_directive_impl(\n ib_cfgparser_t *cp,\n ib_mpool_t *tmp_mp,\n ib_cfgparser_node_t *node,\n bool if_exists\n) {\n assert(cp != NULL);\n assert(cp->mp != NULL);\n assert(node != NULL);\n assert(node->directive != NULL);\n assert(node->params != NULL);\n assert(node->file != NULL);\n\n struct stat statbuf;\n ib_status_t rc;\n ib_mpool_t *mp = cp->mp;\n int statval;\n char *incfile;\n char *real;\n const char* pval;\n const ib_list_node_t *list_node;\n\n \/* A temporary local value to store the parser state in.\n * We allocate this from local_mp to avoid putting the very large\n * buffer variable in fsm on the stack. *\/\n ib_cfgparser_fsm_t *fsm;\n\n ib_cfgparser_node_t *current_node;\n ib_mpool_t *local_mp = NULL;\n\n rc = ib_mpool_create(&local_mp, \"local_mp\", tmp_mp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Failed to create local memory pool.\");\n goto cleanup;\n }\n\n if (ib_list_elements(node->params) != 1) {\n ib_cfg_log_error(\n cp,\n \"%s: %zu - Directive %s only takes 1 parameter not %zu.\",\n node->file,\n node->line,\n node->directive,\n ib_list_elements(node->params));\n rc = IB_EINVAL;\n goto cleanup;\n }\n\n \/* Grab the first parameter node. *\/\n list_node = ib_list_first_const(node->params);\n assert(list_node != NULL);\n\n \/* Grab the parameter value. *\/\n pval = (const char*) ib_list_node_data_const(list_node);\n assert(pval != NULL);\n\n if_exists = strcasecmp(\"IncludeIfExists\", node->directive) == 0;\n\n incfile = ib_util_relative_file(mp, node->file, pval);\n if (incfile == NULL) {\n ib_cfg_log_error(cp, \"Failed to resolve included file \\\"%s\\\": %s\",\n node->file, strerror(errno));\n ib_mpool_release(local_mp);\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n real = ib_mpool_alloc(local_mp, PATH_MAX);\n if (real == NULL) {\n ib_cfg_log_error(\n cp,\n \"Failed to allocate path buffer of size %d\",\n PATH_MAX);\n rc = IB_EALLOC;\n goto cleanup;\n }\n real = realpath(incfile, real);\n if (real == NULL) {\n if (!if_exists) {\n ib_cfg_log_error(cp,\n \"Failed to find real path of included file \"\n \"(using original \\\"%s\\\"): %s\",\n incfile, strerror(errno));\n }\n else {\n ib_cfg_log_warning(\n cp,\n \"Failed to normalize path. Using raw include path: %s\",\n incfile);\n }\n\n real = incfile;\n }\n else if (strcmp(real, incfile) != 0) {\n ib_cfg_log_info(\n cp,\n \"Real path of included file \\\"%s\\\" is \\\"%s\\\"\",\n incfile,\n real);\n }\n else {\n ib_cfg_log_info(\n cp,\n \"Including file \\\"%s\\\"\",\n incfile);\n }\n\n rc = detect_file_loop(cp, node);\n if (rc != IB_OK) {\n goto cleanup;\n }\n\n if (access(incfile, R_OK) != 0) {\n if (if_exists) {\n ib_cfg_log(\n cp, (errno == ENOENT) ? IB_LOG_DEBUG : IB_LOG_NOTICE,\n \"Ignoring include file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_error(\n cp,\n \"Cannot access included file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n statval = stat(incfile, &statbuf);\n if (statval != 0) {\n if (if_exists) {\n ib_cfg_log(\n cp, (errno == ENOENT) ? IB_LOG_DEBUG : IB_LOG_NOTICE,\n \"Ignoring include file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_error(\n cp,\n \"Failed to stat include file \\\"%s\\\": %s\",\n incfile,\n strerror(errno));\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n if (S_ISREG(statbuf.st_mode) == 0) {\n if (if_exists) {\n ib_cfg_log_info(\n cp,\n \"Ignoring include file \\\"%s\\\": Not a regular file\",\n incfile);\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_error(\n cp,\n\t \"Included file \\\"%s\\\" is not a regular file\",\n incfile);\n rc = IB_ENOENT;\n goto cleanup;\n }\n\n ib_cfg_log_debug(cp, \"Including '%s'\", incfile);\n\n \/* Make the given node the current node for the file inclusion. *\/\n current_node = cp->curr;\n cp->curr = node;\n\n \/* Allocate fsm in the heap as it contains a very large buffer. *\/\n fsm = ib_mpool_alloc(local_mp, sizeof(*fsm));\n if (fsm == NULL) {\n rc = IB_EALLOC;\n goto cleanup;\n }\n\n \/* Store current fsm. *\/\n *fsm = cp->fsm;\n\n \/* Initialize new fsm in cp. *\/\n rc = ib_cfgparser_ragel_init(cp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Could not initialize new parser.\");\n return rc;\n }\n\n rc = ib_cfgparser_parse_private(cp, incfile, false);\n \/* Restore fsm. *\/\n cp->fsm = *fsm;\n cp->curr = current_node;\n if (rc != IB_OK) {\n ib_cfg_log_error(\n cp,\n \"Error parsing included file \\\"%s\\\": %s\",\n\t incfile,\n ib_status_to_string(rc));\n rc = IB_OK;\n goto cleanup;\n }\n\n ib_cfg_log_debug(cp, \"Done processing include file \\\"%s\\\"\", incfile);\n\ncleanup:\n if (local_mp != NULL) {\n ib_mpool_release(local_mp);\n }\n return rc;\n}\n\n\/\/! Proxy to include_parse_directive_impl with if_exists = true.\nstatic ib_status_t include_if_exists_parse_directive(\n ib_cfgparser_t *cp,\n ib_mpool_t *tmp_mp,\n ib_cfgparser_node_t *node\n) {\n return include_parse_directive_impl(cp, tmp_mp, node, true);\n}\n\n\/\/! Proxy to include_parse_directive_impl with if_exists = false.\nstatic ib_status_t include_parse_directive(\n ib_cfgparser_t *cp,\n ib_mpool_t *tmp_mp,\n ib_cfgparser_node_t *node\n) {\n return include_parse_directive_impl(cp, tmp_mp, node, false);\n}\n\nstatic ib_status_t loglevel_parse_directive(\n ib_cfgparser_t *cp,\n ib_mpool_t* tmp_mp,\n ib_cfgparser_node_t *node\n) {\n assert(cp != NULL);\n assert(node != NULL);\n assert(node->directive != NULL);\n assert(node->params != NULL);\n\n ib_cfg_log_debug(cp, \"Applying new log level.\");\n\n return ib_config_directive_process(cp, node->directive, node->params);\n}\n\n\/**\n * Null-terminated table that maps parsing directives to handler functions.\n *\/\nstatic parse_directive_entry_t parse_directive_table[] = {\n { \"IncludeIfExists\", include_if_exists_parse_directive },\n { \"Include\", include_parse_directive },\n { \"LogLevel\", loglevel_parse_directive },\n { NULL, NULL } \/* Null termination. Do not remove. *\/\n};\n\n%%{\n machine ironbee_config;\n\n prepush {\n if (cp->fsm.top >= 1023) {\n ib_cfg_log_debug(cp, \"Recursion too deep during parse.\");\n return IB_EOTHER;\n }\n }\n\n postpop {\n }\n\n action error_action {\n rc = IB_EOTHER;\n ib_cfg_log_error(\n cp,\n \"parser error near %s:%zu.\",\n cp->curr->file,\n cp->curr->line);\n ib_cfg_log_debug(cp, \"Current buffer is [[[[%.*s]]]]\", (int)blen, buf);\n }\n\n # Parameter\n action push_param {\n tmp_str = qstrdup(cp, config_mp);\n if (tmp_str == NULL) {\n return IB_EALLOC;\n }\n ib_list_push(cp->fsm.plist, tmp_str);\n tmp_str = NULL;\n cpbuf_clear(cp);\n }\n action push_blkparam {\n tmp_str = qstrdup(cp, config_mp);\n if (tmp_str == NULL) {\n return IB_EALLOC;\n }\n ib_list_push(cp->fsm.plist, tmp_str);\n tmp_str = NULL;\n cpbuf_clear(cp);\n }\n\n action newline {\n cp->curr->line += 1;\n }\n\n # Directives\n action start_dir {\n if (cp->buffer->len == 0) {\n ib_cfg_log_error(cp, \"Directive name is 0 length.\");\n return IB_EOTHER;\n }\n cp->fsm.directive =\n ib_mpool_memdup_to_str(cp->mp, cp->buffer->data, cp->buffer->len);\n if (cp->fsm.directive == NULL) {\n return IB_EALLOC;\n }\n ib_list_clear(cp->fsm.plist);\n cpbuf_clear(cp);\n }\n action push_dir {\n ib_cfgparser_node_t *node = NULL;\n ib_cfgparser_node_create(&node, cp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot create node.\");\n return rc;\n }\n node->directive = cp->fsm.directive;\n cp->fsm.directive = NULL;\n node->file = ib_mpool_strdup(cp->mp, cp->curr->file);\n if (node->file == NULL) {\n return IB_EALLOC;\n }\n node->parent = cp->curr;\n node->line = cp->curr->line;\n node->type = IB_CFGPARSER_NODE_DIRECTIVE;\n ib_list_node_t *lst_node;\n IB_LIST_LOOP(cp->fsm.plist, lst_node) {\n ib_list_push(node->params, ib_list_node_data(lst_node));\n }\n ib_list_push(cp->curr->children, node);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Out of memory.\");\n }\n\n \/* Handle parse directives using the parse_directive_table. *\/\n for (int i = 0; parse_directive_table[i].directive != NULL; ++i) {\n if (\n strcasecmp(\n parse_directive_table[i].directive,\n node->directive) == 0\n ) {\n \/* Change the node type. This is an parse directive. *\/\n node->type = IB_CFGPARSER_NODE_PARSE_DIRECTIVE;\n \/* Process directive. *\/\n cpbuf_clear(cp);\n rc = (parse_directive_table[i].fn)(cp, temp_mp, node);\n if (rc != IB_OK) {\n ib_cfg_log_error(\n cp,\n \"Parse directive %s failed.\",\n node->directive);\n }\n else {\n ib_cfg_log_debug(\n cp,\n \"Parse directive %s succeeded.\",\n node->directive);\n }\n }\n }\n }\n\n action cpbuf_append {\n ib_cfg_log_trace(\n cp,\n \"Text buffer is (len=%zu) (offset=%d): [[[[%.*s]]]]\",\n blen,\n (int)(fsm_vars.p - buf),\n (int)blen,\n buf);\n if (cpbuf_append(cp, *fpc) != IB_OK) {\n return IB_EALLOC;\n }\n }\n\n # Blocks\n action start_block {\n if (cp->buffer->len == 0) {\n ib_cfg_log_error(cp, \"Block name is 0 length.\");\n return IB_EOTHER;\n }\n cp->fsm.blkname =\n ib_mpool_memdup_to_str(cp->mp, cp->buffer->data, cp->buffer->len);\n if (cp->fsm.blkname == NULL) {\n return IB_EALLOC;\n }\n ib_list_clear(cp->fsm.plist);\n cpbuf_clear(cp);\n }\n action push_block {\n ib_cfgparser_node_t *node = NULL;\n rc = ib_cfgparser_node_create(&node, cp);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot create node.\");\n return rc;\n }\n node->directive = cp->fsm.blkname;\n \/* NOTE: We do not clear blkname now. *\/\n node->file = ib_mpool_strdup(cp->mp, cp->curr->file);\n if (node->file == NULL) {\n return IB_EALLOC;\n }\n node->line = cp->curr->line;\n node->type = IB_CFGPARSER_NODE_BLOCK;\n ib_list_node_t *lst_node;\n IB_LIST_LOOP(cp->fsm.plist, lst_node) {\n ib_cfg_log_debug(\n cp,\n \"Adding param \\\"%s\\\" to SBLK1 %s (node = %p)\",\n (const char *)ib_list_node_data(lst_node),\n node->directive,\n node);\n rc = ib_list_push(node->params, ib_list_node_data(lst_node));\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot push directive.\");\n return rc;\n }\n }\n rc = ib_cfgparser_push_node(cp, node);\n if (rc != IB_OK) {\n ib_cfg_log_error(cp, \"Cannot push node.\");\n return rc;\n }\n }\n action pop_block {\n ib_cfgparser_pop_node(cp);\n cpbuf_clear(cp);\n cp->fsm.blkname = NULL;\n }\n\n # include file logic\n # Whitespace.\n WS = [ \\t];\n # End of line.\n EOL = '\\r'? '\\n';\n # Continuation.\n CONT = '\\\\' EOL;\n\n qchar = '\\\\' any;\n qtoken = '\"' ( qchar | ( any - [\"\\\\] ) )* '\"';\n token = (qchar | (any - (WS | '\\r' | '\\n' | [<>#\"\\\\])))\n (qchar | (any - (WS | '\\r' | '\\n' | [<>\"\\\\])))*;\n param = qtoken | token;\n\n # A comment is any string starting with # and not including a newline.\n comment = '#' (any - ('\\r' | '\\n'))*;\n\n # The parameters machine pull in parameter.\n parameters := |*\n WS;\n CONT $newline;\n EOL $newline\n @push_dir { fret; };\n param $cpbuf_append\n %push_param\n $\/push_param\n $\/push_dir\n $err{ fhold; fret; }\n $eof{ fhold; fret; };\n *|;\n\n block_parameters := |*\n WS;\n CONT $newline;\n \">\" @push_block\n { fret; };\n param $cpbuf_append\n %push_blkparam\n $err{ fhold; fret; };\n *|;\n\n newblock := |*\n WS;\n CONT $newline\n $!error_action { fhold; fret; };\n EOL $newline\n $!error_action { fhold; fret; };\n token $cpbuf_append\n %start_block\n $!error_action\n { fcall block_parameters; };\n *|;\n\n endblock := |*\n WS $eof(error_action);\n CONT $newline\n $eof(error_action);\n\tEOL $newline\n $eof(error_action);\n token $cpbuf_append\n $!error_action\n %pop_block\n $eof(error_action);\n \">\" $eof(error_action)\n { fret; };\n *|;\n\n main := |*\n comment;\n\n # A directive.\n token $cpbuf_append\n %start_dir\n { fcall parameters; };\n\n # Handle block configurations .\n \"<\" (any - \"\/\") { fhold; fcall newblock;};\n \"<\/\" { fcall endblock;};\n\n # Eat space.\n WS;\n CONT $newline;\n EOL $newline;\n \">\" {\n ib_cfg_log_error(\n cp,\n \"Character \\\">\\\" encountered outside a block tag.\");\n rc = IB_EOTHER;\n fbreak;\n };\n *|;\n}%%\n\n%% write data;\n\nib_status_t ib_cfgparser_ragel_init(ib_cfgparser_t *cp) {\n assert(cp != NULL);\n assert(cp->ib != NULL);\n assert(cp->mp != NULL);\n\n ib_status_t rc;\n\n ib_cfg_log_debug(cp, \"Initializing Ragel state machine.\");\n\n \/* Access all ragel state variables via structure. *\/\n %% access cp->fsm.;\n\n %% write init;\n\n ib_cfg_log_info(cp, \"Initializing IronBee parse values.\");\n\n rc = ib_list_create(&(cp->fsm.plist), cp->mp);\n if (rc != IB_OK) {\n return rc;\n }\n\n cp->fsm.directive = NULL;\n cp->fsm.blkname = NULL;\n\n rc = ib_vector_create(&(cp->fsm.ts_buffer), cp->mp, 0);\n if (rc != IB_OK) {\n return rc;\n }\n\n return IB_OK;\n}\n\n\/**\n * If Ragel has a partial match we must preserve the buffer\n * until next time to continue the match.\n * This effects how the machine is restarted on\n * the next call to ib_cfgparser_ragel_parse_chunk.\n *\/\nstatic ib_status_t cfgparser_partial_match_maintenance(\n ib_cfgparser_t *cp,\n const char *buf,\n const size_t blen\n)\n{\n ib_status_t rc;\n size_t buffer_remaining = buf + blen - cp->fsm.ts;\n\n \/* Distance that the ts and te pointers will be shifted when\n * copied into the vector. *\/\n ssize_t delta;\n\n rc = ib_vector_truncate(cp->fsm.ts_buffer, 0);\n if (rc != IB_OK) {\n return rc;\n }\n\n\n rc = ib_vector_append(cp->fsm.ts_buffer, cp->fsm.ts, buffer_remaining);\n if (rc != IB_OK) {\n return rc;\n }\n\n delta = (char *)cp->fsm.ts_buffer->data - cp->fsm.ts;\n\n \/* Relocate ts and te into the buffer. *\/\n cp->fsm.te += delta;\n cp->fsm.ts += delta;\n\n return IB_OK;\n}\n\n\/**\n * If Ragel has a partial match we must resume parsing in \n * a special buffer we are maintaining.\n * @param[in] cp Configuration parser. The cp->fsm structure is updated.\n * @param[in] buf Buffer to append to cp->fsm.ts_buffer.\n * @param[in] blen Length of the buffer to append to cp->fsm.ts_buffer.\n * @param[out] fsm_vars The p field is updated to point to \n * the new location of buffer.\n *\/\nstatic ib_status_t cfgparser_partial_match_resume(\n ib_cfgparser_t *cp,\n const char *buf,\n const size_t blen\n)\n{\n ib_status_t rc;\n\n \/* Store the previous data pointer so we can detect if it moves. *\/\n void *orig_data = cp->fsm.ts_buffer->data;\n\n \/* Append the input buffer. *\/\n rc = ib_vector_append(cp->fsm.ts_buffer, (uint8_t *)buf, blen);\n if (rc != IB_OK) {\n return rc;\n }\n\n if (orig_data != cp->fsm.ts_buffer->data) {\n \/* Update ts and te *\/\n ssize_t delta = cp->fsm.ts_buffer->data - orig_data;\n\n cp->fsm.ts += delta;\n cp->fsm.te += delta;\n }\n\n return IB_OK;\n}\n\nib_status_t ib_cfgparser_ragel_parse_chunk(\n ib_cfgparser_t *cp,\n const char *buf,\n const size_t blen,\n const int is_last_chunk)\n{\n assert(cp != NULL);\n assert(cp->ib != NULL);\n\n ib_engine_t *ib_engine = cp->ib;\n\n \/* Temporary memory pool. *\/\n ib_mpool_t *temp_mp = ib_engine_pool_temp_get(ib_engine);\n\n \/* Configuration memory pool. *\/\n ib_mpool_t *config_mp = ib_engine_pool_config_get(ib_engine);\n\n \/* Error actions will update this. *\/\n ib_status_t rc = IB_OK;\n\n \/* Create a finite state machine type. *\/\n fsm_vars_t fsm_vars = { buf, NULL, 0 };\n\n \/* A temporary string. This is used to fetch values, check them\n * for NULL, and then pass them on to an owning collection (list). *\/\n char *tmp_str = NULL;\n\n \/* Point the machine at the current buffer to parse.\n *\/\n if (cp->fsm.ts != NULL) {\n rc = cfgparser_partial_match_resume(cp, buf, blen);\n if (rc != IB_OK) {\n return rc;\n }\n\n \/* Buffer start = prev buffer end. *\/\n fsm_vars.p = cp->fsm.te;\n }\n else {\n fsm_vars.p = buf;\n }\n fsm_vars.pe = fsm_vars.p + blen;\n fsm_vars.eof = (is_last_chunk ? fsm_vars.pe : NULL);\n\n \/* Access all ragel state variables via structure. *\/\n %% access cp->fsm.;\n %% variable p fsm_vars.p;\n %% variable pe fsm_vars.pe;\n %% variable eof fsm_vars.eof;\n\n %% write exec;\n\n assert(tmp_str == NULL && \"tmp_str must be cleared after every use\");\n\n \/* Buffer maintenance code. *\/\n if (cp->fsm.ts != NULL) {\n rc = cfgparser_partial_match_maintenance(cp, buf, blen);\n if (rc != IB_OK) {\n return rc;\n }\n }\n\n \/* On the last chunk, sanity check things. *\/\n if (is_last_chunk) {\n if (cp->fsm.blkname != NULL) {\n ib_cfg_log_error(\n cp,\n \"Unpushed block \\\"%s\\\" at end of config input\",\n cp->fsm.blkname);\n return IB_EINVAL;\n }\n if (cp->fsm.directive != NULL) {\n ib_cfg_log_error(\n cp,\n \"Unpushed directive \\\"%s\\\" end of config input\",\n cp->fsm.directive);\n return IB_EINVAL;\n }\n }\n\n return rc;\n}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"20b077df2d1f591f4f4185f41cf20134a586f4fc","subject":"Fix typo in block labels","message":"Fix typo in block labels\n","repos":"metaparadigm\/latypus,metaparadigm\/latypus,metaparadigm\/latypus,metaparadigm\/latypus","old_file":"src\/config_parser.rl","new_file":"src\/config_parser.rl","new_contents":"\/\/\n\/\/ config_parser.rl\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"config_parser.h\"\n\n%%{\n \n machine config_parser;\n\n action mark { mark = fpc; }\n action w_start_block { start_block(); }\n action w_end_block { end_block(); }\n action w_symbol { symbol(mark, fpc - mark); }\n action w_end_statement { end_statement(); }\n\n action done { \n config_done();\n fbreak;\n }\n\n Eol = ';' %w_end_statement;\n newline = ('\\r' | '\\n' ) | '\\n';\n ws = (' ' | '\\t' | '\\r' | '\\n' )+;\n comment = '\/*' ( any* - ( any* '*\/' any* ) ) '*\/';\n symbol = ( ( any - ';' - ws - '{' - '}' )+ - ('\/*') ) >mark %w_symbol;\n statement = ( symbol ( ws symbol)* ) ws* Eol;\n start_block = symbol ws+ '{' %w_start_block;\n end_block = '}' ws* ';' %w_end_block;\n config = ( comment | start_block | end_block | statement | ws )* %done;\n\n main := config;\n\n}%%\n\n%% write data;\n\nbool config_parser::parse(const char *buffer, size_t len)\n{\n int cs = config_parser_en_main;\n \n const char *mark = NULL;\n const char *p = buffer;\n const char *pe = buffer + strlen(buffer);\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n return (cs != config_parser_error && cs == config_parser_first_final);\n}\n","old_contents":"\/\/\n\/\/ config_parser.rl\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"config_parser.h\"\n\n%%{\n \n machine config_parser;\n\n action mark { mark = fpc; }\n action w_start_block { start_block(); }\n action w_end_block { end_block(); }\n action w_symbol { symbol(mark, fpc - mark); }\n action w_end_statement { end_statement(); }\n\n action done { \n config_done();\n fbreak;\n }\n\n Eol = ';' %w_end_statement;\n newline = ('\\r' | '\\n' ) | '\\n';\n ws = (' ' | '\\t' | '\\r' | '\\n' )+;\n comment = '\/*' ( any* - ( any* '*\/' any* ) ) '*\/';\n symbol = ( ( any - ';' - ws - '{' - '}' )+ - ('\/*') ) >mark %w_symbol;\n statement = ( symbol ( ws symbol)* ) ws* Eol;\n end_block = symbol ws+ '{' %w_start_block;\n start_block = '}' ws* ';' %w_end_block;\n config = ( comment | start_block | end_block | statement | ws )* %done;\n\n main := config;\n\n}%%\n\n%% write data;\n\nbool config_parser::parse(const char *buffer, size_t len)\n{\n int cs = config_parser_en_main;\n \n const char *mark = NULL;\n const char *p = buffer;\n const char *pe = buffer + strlen(buffer);\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n return (cs != config_parser_error && cs == config_parser_first_final);\n}\n","returncode":0,"stderr":"","license":"isc","lang":"Ragel in Ruby Host"} {"commit":"850f06b73f3b79fea3e31512a82986ad646bc756","subject":"prefer calloc over malloc: mult-overflow detection, zeroing","message":"prefer calloc over malloc: mult-overflow detection, zeroing\n","repos":"hoytech\/libqstruct,hoytech\/libqstruct","old_file":"parser.rl","new_file":"parser.rl","new_contents":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qstruct\/compiler.h\"\n\nint calculate_qstruct_packing(struct qstruct_definition *);\n\n\n%%{\n machine qstruct;\n write data;\n}%%\n\nstruct qstruct_definition *parse_qstructs(char *schema, size_t schema_size, char *err_buf, size_t err_buf_size) {\n char *p = schema, *pe = schema + schema_size, *eof = 0;\n int cs = -1;\n\n int curr_line = 1;\n ssize_t i;\n size_t j;\n int err = 0;\n\n struct qstruct_definition *def = NULL, *new_def, *curr_def, *temp_def;\n struct qstruct_item curr_item;\n ssize_t curr_item_index;\n struct qstruct_definition *def_hash_by_name = NULL, *def_lookup;\n\n struct qstruct_item *new_items;\n ssize_t items_allocated;\n ssize_t largest_item;\n struct qstruct_item *item_hash_by_name = NULL, *item_lookup;\n\n char err_ctx_buf[256];\n char err_desc_buf[512];\n char *err_ctx_start, *err_ctx_end;\n\n\n \/\/ Parsing phase\n\n\n \/\/ our ragel machine will initialise these variables, assignments here are just to silence compiler warnings\n curr_item_index = 0;\n memset(&curr_item, '\\0', sizeof(curr_item));\n items_allocated = 0;\n largest_item = -1;\n\n\n #define PARSE_ERROR(...) do { \\\n snprintf(err_desc_buf, sizeof(err_desc_buf), __VA_ARGS__); \\\n if (!err) err = 1; \\\n goto err_bail; \\\n } while(0)\n\n %%{\n action init_qstruct {\n new_def = calloc(sizeof(struct qstruct_definition), 1);\n if (new_def == NULL)\n PARSE_ERROR(\"out of memory\");\n\n new_def->next = def;\n def = new_def;\n new_def = NULL;\n\n items_allocated = 64;\n def->items = calloc(items_allocated, sizeof(struct qstruct_item));\n if (def->items == NULL)\n PARSE_ERROR(\"out of memory\");\n\n largest_item = -1;\n for (i=0; iitems[i].occupied = 0;\n }\n\n action handle_item {\n if (curr_item_index < 0 || curr_item_index > 1000000)\n PARSE_ERROR(\"@id way out of range\");\n\n if (curr_item_index >= items_allocated) {\n new_items = realloc(def->items, curr_item_index*2 * sizeof(struct qstruct_item));\n if (new_items == NULL) \n PARSE_ERROR(\"out of memory\");\n\n def->items = new_items;\n new_items = NULL;\n\n for(i=items_allocated; iitems[i].occupied = 0;\n items_allocated = curr_item_index*2;\n }\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BOOL && (curr_item.type & (QSTRUCT_TYPE_MOD_ARRAY_FIX | QSTRUCT_TYPE_MOD_ARRAY_DYN)))\n PARSE_ERROR(\"bools can't be arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_STRING && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"strings can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BLOB && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"blobs can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_NESTED && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"nested qstructs can't be fixed-size arrays\");\n\n if (def->items[curr_item_index].occupied)\n PARSE_ERROR(\"duplicated index %ld\", curr_item_index);\n\n def->items[curr_item_index].name = curr_item.name;\n def->items[curr_item_index].name_len = curr_item.name_len;\n def->items[curr_item_index].type = curr_item.type;\n def->items[curr_item_index].fixed_array_size = curr_item.fixed_array_size;\n def->items[curr_item_index].nested_name = curr_item.nested_name;\n def->items[curr_item_index].nested_name_len = curr_item.nested_name_len;\n def->items[curr_item_index].occupied = 1;\n\n if (curr_item_index > largest_item) largest_item = curr_item_index;\n }\n\n action handle_qstruct {\n assert(!item_hash_by_name);\n\n for(i=0; i<=largest_item; i++) {\n if (!def->items[i].occupied)\n PARSE_ERROR(\"missing item %ld\", i);\n\n HASH_FIND(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, item_lookup);\n if (item_lookup)\n PARSE_ERROR(\"duplicate item name '%.*s'\", (int) def->items[i].name_len, def->items[i].name);\n\n HASH_ADD_KEYPTR(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, &def->items[i]);\n }\n\n HASH_CLEAR(hh, item_hash_by_name);\n\n def[0].num_items = largest_item+1;\n }\n\n\n newline = '\\n' @{ curr_line++; };\n any_count_line = any | newline;\n whitespace_char = any_count_line - 0x21..0x7e;\n\n alnum_u = alnum | '_';\n lc_alpha_u = [a-z] | '_';\n uc_alpha_u = [A-Z] | '_';\n identifier = lc_alpha_u $!{ PARSE_ERROR(\"qstruct item names must start with lowercase letters\"); }\n alnum_u*;\n identifier_with_package = uc_alpha_u $!{ PARSE_ERROR(\"qstruct names must start with uppercase letters\"); }\n alnum_u* ('::' uc_alpha_u alnum_u*)*;\n integer = digit+;\n\n ws = whitespace_char |\n '#' [^\\n]* newline |\n '\/*' (any_count_line* - (any_count_line* '*\/' any_count_line*)) '*\/'\n ;\n\n type = 'string' %{ curr_item.type = QSTRUCT_TYPE_STRING; } |\n 'blob' %{ curr_item.type = QSTRUCT_TYPE_BLOB; } |\n 'bool' %{ curr_item.type = QSTRUCT_TYPE_BOOL; } |\n 'float' %{ curr_item.type = QSTRUCT_TYPE_FLOAT; } |\n 'double' %{ curr_item.type = QSTRUCT_TYPE_DOUBLE; } |\n 'int8' %{ curr_item.type = QSTRUCT_TYPE_INT8; } |\n 'uint8' %{ curr_item.type = QSTRUCT_TYPE_INT8 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int16' %{ curr_item.type = QSTRUCT_TYPE_INT16; } |\n 'uint16' %{ curr_item.type = QSTRUCT_TYPE_INT16 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int32' %{ curr_item.type = QSTRUCT_TYPE_INT32; } |\n 'uint32' %{ curr_item.type = QSTRUCT_TYPE_INT32 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int64' %{ curr_item.type = QSTRUCT_TYPE_INT64; } |\n 'uint64' %{ curr_item.type = QSTRUCT_TYPE_INT64 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n identifier_with_package >{ curr_item.nested_name = p; curr_item.type = QSTRUCT_TYPE_NESTED; }\n %{ curr_item.nested_name_len = p - curr_item.nested_name; }\n ;\n\n array_spec = '['\n ws*\n integer >{ curr_item.fixed_array_size = 0; }\n @{ curr_item.fixed_array_size = curr_item.fixed_array_size * 10 + (fc - '0'); }\n ws*\n ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_FIX; }\n\n |\n\n '[' ws* ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_DYN; }\n ;\n\n item = identifier >{ curr_item.name = p; curr_item.fixed_array_size = 1; }\n %{ curr_item.name_len = p - curr_item.name; }\n $!{ PARSE_ERROR(\"invalid identifier\"); }\n ws+\n '@' $!{ PARSE_ERROR(\"expected @ id\"); }\n integer >{ curr_item_index = 0; }\n @{ curr_item_index = curr_item_index * 10 + (fc - '0'); }\n ws+\n type $!{ PARSE_ERROR(\"unrecognized type\"); }\n ws*\n array_spec? $!{ PARSE_ERROR(\"invalid array specifier\"); }\n ws* ';' $!{ PARSE_ERROR(\"missing semi-colon\"); }\n ;\n\n qstruct = ws*\n ( [qQ] 'struct' ) >init_qstruct\n $!{ PARSE_ERROR(\"expected qstruct definition\"); }\n ws+\n identifier_with_package >{ def[0].name = p; }\n %{ def[0].name_len = p - def[0].name; }\n ws*\n '{'\n ws* (item @handle_item ws*)*\n '}' @handle_qstruct\n (ws* ';')?\n ;\n\n main := qstruct* ws*;\n\n write init;\n write exec;\n }%%\n\n if (cs < qstruct_first_final)\n PARSE_ERROR(\"general parse error\");\n\n\n\n\n \/\/ Compilation phase\n\n \/\/ reverse def list\n for (curr_def = NULL; def;) {\n temp_def = def->next;\n def->next = curr_def;\n curr_def = def;\n def = temp_def;\n }\n def = curr_def;\n\n assert(!def_hash_by_name);\n\n for(curr_def = def; curr_def; curr_def = curr_def->next) {\n for(j=0; jnum_items; j++) {\n if ((def->items[j].type & 0xFFFF) == QSTRUCT_TYPE_NESTED) {\n HASH_FIND(hh, def_hash_by_name, def->items[j].nested_name, def->items[j].nested_name_len, def_lookup);\n if (!def_lookup)\n PARSE_ERROR(\"type '%.*s' referred to before being defined\", (int) def->items[j].nested_name_len, def->items[j].nested_name);\n\n def->items[j].nested_def = def_lookup;\n }\n }\n\n HASH_FIND(hh, def_hash_by_name, curr_def->name, curr_def->name_len, def_lookup);\n if (def_lookup)\n PARSE_ERROR(\"duplicate def name '%.*s'\", (int) curr_def->name_len, curr_def->name);\n\n HASH_ADD_KEYPTR(hh, def_hash_by_name, curr_def->name, curr_def->name_len, curr_def);\n\n if (calculate_qstruct_packing(curr_def) < 0)\n PARSE_ERROR(\"memory error in packing\");\n }\n\n\n \/\/ Success!\n goto cleanup;\n\n #undef PARSE_ERROR\n err_bail:\n\n for(err_ctx_start=p; err_ctx_start>schema && *err_ctx_start != '\\n' && (p-err_ctx_start) < 20; err_ctx_start--) {}\n while (isspace(*err_ctx_start) && err_ctx_start < p) err_ctx_start++;\n for(err_ctx_end=p; err_ctx_end<(pe-1) && *err_ctx_end != '\\n' && (err_ctx_end-p) < 20; err_ctx_end++) {}\n memcpy(err_ctx_buf, err_ctx_start, err_ctx_end - err_ctx_start);\n *(err_ctx_buf + (err_ctx_end - err_ctx_start)) = '\\0';\n snprintf(err_buf, err_buf_size, \"\\n------------------------------------------------------------\\nQstruct schema parse error (line %d, character %d)\\n\\n %s\\n %*s^\\n %*s|--%s\\n\\n------------------------------------------------------------\\n\", curr_line, (int)(p-schema), err_ctx_buf, (int)(p-err_ctx_start), \" \", (int)(p-err_ctx_start), \" \", err_desc_buf);\n\n if (def) {\n free_qstruct_definitions(def);\n def = NULL;\n }\n\n\n cleanup:\n\n HASH_CLEAR(hh, item_hash_by_name);\n HASH_CLEAR(hh, def_hash_by_name);\n\n return def;\n}\n\n\nvoid free_qstruct_definitions(struct qstruct_definition *def) {\n struct qstruct_definition *temp;\n\n while (def) {\n if (def->items) free(def->items);\n temp = def->next;\n free(def);\n def = temp;\n }\n}\n","old_contents":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qstruct\/compiler.h\"\n\nint calculate_qstruct_packing(struct qstruct_definition *);\n\n\n%%{\n machine qstruct;\n write data;\n}%%\n\nstruct qstruct_definition *parse_qstructs(char *schema, size_t schema_size, char *err_buf, size_t err_buf_size) {\n char *p = schema, *pe = schema + schema_size, *eof = 0;\n int cs = -1;\n\n int curr_line = 1;\n ssize_t i;\n size_t j;\n int err = 0;\n\n struct qstruct_definition *def = NULL, *new_def, *curr_def, *temp_def;\n struct qstruct_item curr_item;\n ssize_t curr_item_index;\n struct qstruct_definition *def_hash_by_name = NULL, *def_lookup;\n\n struct qstruct_item *new_items;\n ssize_t items_allocated;\n ssize_t largest_item;\n struct qstruct_item *item_hash_by_name = NULL, *item_lookup;\n\n char err_ctx_buf[256];\n char err_desc_buf[512];\n char *err_ctx_start, *err_ctx_end;\n\n\n \/\/ Parsing phase\n\n\n \/\/ our ragel machine will initialise these variables, assignments here are just to silence compiler warnings\n curr_item_index = 0;\n memset(&curr_item, '\\0', sizeof(curr_item));\n items_allocated = 0;\n largest_item = -1;\n\n\n #define PARSE_ERROR(...) do { \\\n snprintf(err_desc_buf, sizeof(err_desc_buf), __VA_ARGS__); \\\n if (!err) err = 1; \\\n goto err_bail; \\\n } while(0)\n\n %%{\n action init_qstruct {\n new_def = malloc(sizeof(struct qstruct_definition));\n if (new_def == NULL)\n PARSE_ERROR(\"out of memory\");\n\n new_def->next = def;\n def = new_def;\n new_def = NULL;\n\n items_allocated = 64;\n def->items = malloc(items_allocated * sizeof(struct qstruct_item));\n if (def->items == NULL)\n PARSE_ERROR(\"out of memory\");\n\n largest_item = -1;\n for (i=0; iitems[i].occupied = 0;\n }\n\n action handle_item {\n if (curr_item_index < 0 || curr_item_index > 1000000)\n PARSE_ERROR(\"@id way out of range\");\n\n if (curr_item_index >= items_allocated) {\n new_items = realloc(def->items, curr_item_index*2 * sizeof(struct qstruct_item));\n if (new_items == NULL) \n PARSE_ERROR(\"out of memory\");\n\n def->items = new_items;\n new_items = NULL;\n\n for(i=items_allocated; iitems[i].occupied = 0;\n items_allocated = curr_item_index*2;\n }\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BOOL && (curr_item.type & (QSTRUCT_TYPE_MOD_ARRAY_FIX | QSTRUCT_TYPE_MOD_ARRAY_DYN)))\n PARSE_ERROR(\"bools can't be arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_STRING && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"strings can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_BLOB && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"blobs can't be fixed-size arrays\");\n\n if ((curr_item.type & 0xFFFF) == QSTRUCT_TYPE_NESTED && (curr_item.type & QSTRUCT_TYPE_MOD_ARRAY_FIX))\n PARSE_ERROR(\"nested qstructs can't be fixed-size arrays\");\n\n if (def->items[curr_item_index].occupied)\n PARSE_ERROR(\"duplicated index %ld\", curr_item_index);\n\n def->items[curr_item_index].name = curr_item.name;\n def->items[curr_item_index].name_len = curr_item.name_len;\n def->items[curr_item_index].type = curr_item.type;\n def->items[curr_item_index].fixed_array_size = curr_item.fixed_array_size;\n def->items[curr_item_index].nested_name = curr_item.nested_name;\n def->items[curr_item_index].nested_name_len = curr_item.nested_name_len;\n def->items[curr_item_index].occupied = 1;\n\n if (curr_item_index > largest_item) largest_item = curr_item_index;\n }\n\n action handle_qstruct {\n assert(!item_hash_by_name);\n\n for(i=0; i<=largest_item; i++) {\n if (!def->items[i].occupied)\n PARSE_ERROR(\"missing item %ld\", i);\n\n HASH_FIND(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, item_lookup);\n if (item_lookup)\n PARSE_ERROR(\"duplicate item name '%.*s'\", (int) def->items[i].name_len, def->items[i].name);\n\n HASH_ADD_KEYPTR(hh, item_hash_by_name, def->items[i].name, def->items[i].name_len, &def->items[i]);\n }\n\n HASH_CLEAR(hh, item_hash_by_name);\n\n def[0].num_items = largest_item+1;\n }\n\n\n newline = '\\n' @{ curr_line++; };\n any_count_line = any | newline;\n whitespace_char = any_count_line - 0x21..0x7e;\n\n alnum_u = alnum | '_';\n lc_alpha_u = [a-z] | '_';\n uc_alpha_u = [A-Z] | '_';\n identifier = lc_alpha_u $!{ PARSE_ERROR(\"qstruct item names must start with lowercase letters\"); }\n alnum_u*;\n identifier_with_package = uc_alpha_u $!{ PARSE_ERROR(\"qstruct names must start with uppercase letters\"); }\n alnum_u* ('::' uc_alpha_u alnum_u*)*;\n integer = digit+;\n\n ws = whitespace_char |\n '#' [^\\n]* newline |\n '\/*' (any_count_line* - (any_count_line* '*\/' any_count_line*)) '*\/'\n ;\n\n type = 'string' %{ curr_item.type = QSTRUCT_TYPE_STRING; } |\n 'blob' %{ curr_item.type = QSTRUCT_TYPE_BLOB; } |\n 'bool' %{ curr_item.type = QSTRUCT_TYPE_BOOL; } |\n 'float' %{ curr_item.type = QSTRUCT_TYPE_FLOAT; } |\n 'double' %{ curr_item.type = QSTRUCT_TYPE_DOUBLE; } |\n 'int8' %{ curr_item.type = QSTRUCT_TYPE_INT8; } |\n 'uint8' %{ curr_item.type = QSTRUCT_TYPE_INT8 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int16' %{ curr_item.type = QSTRUCT_TYPE_INT16; } |\n 'uint16' %{ curr_item.type = QSTRUCT_TYPE_INT16 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int32' %{ curr_item.type = QSTRUCT_TYPE_INT32; } |\n 'uint32' %{ curr_item.type = QSTRUCT_TYPE_INT32 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n 'int64' %{ curr_item.type = QSTRUCT_TYPE_INT64; } |\n 'uint64' %{ curr_item.type = QSTRUCT_TYPE_INT64 | QSTRUCT_TYPE_MOD_UNSIGNED; } |\n identifier_with_package >{ curr_item.nested_name = p; curr_item.type = QSTRUCT_TYPE_NESTED; }\n %{ curr_item.nested_name_len = p - curr_item.nested_name; }\n ;\n\n array_spec = '['\n ws*\n integer >{ curr_item.fixed_array_size = 0; }\n @{ curr_item.fixed_array_size = curr_item.fixed_array_size * 10 + (fc - '0'); }\n ws*\n ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_FIX; }\n\n |\n\n '[' ws* ']' >{ curr_item.type |= QSTRUCT_TYPE_MOD_ARRAY_DYN; }\n ;\n\n item = identifier >{ curr_item.name = p; curr_item.fixed_array_size = 1; }\n %{ curr_item.name_len = p - curr_item.name; }\n $!{ PARSE_ERROR(\"invalid identifier\"); }\n ws+\n '@' $!{ PARSE_ERROR(\"expected @ id\"); }\n integer >{ curr_item_index = 0; }\n @{ curr_item_index = curr_item_index * 10 + (fc - '0'); }\n ws+\n type $!{ PARSE_ERROR(\"unrecognized type\"); }\n ws*\n array_spec? $!{ PARSE_ERROR(\"invalid array specifier\"); }\n ws* ';' $!{ PARSE_ERROR(\"missing semi-colon\"); }\n ;\n\n qstruct = ws*\n ( [qQ] 'struct' ) >init_qstruct\n $!{ PARSE_ERROR(\"expected qstruct definition\"); }\n ws+\n identifier_with_package >{ def[0].name = p; }\n %{ def[0].name_len = p - def[0].name; }\n ws*\n '{'\n ws* (item @handle_item ws*)*\n '}' @handle_qstruct\n (ws* ';')?\n ;\n\n main := qstruct* ws*;\n\n write init;\n write exec;\n }%%\n\n if (cs < qstruct_first_final)\n PARSE_ERROR(\"general parse error\");\n\n\n\n\n \/\/ Compilation phase\n\n \/\/ reverse def list\n for (curr_def = NULL; def;) {\n temp_def = def->next;\n def->next = curr_def;\n curr_def = def;\n def = temp_def;\n }\n def = curr_def;\n\n assert(!def_hash_by_name);\n\n for(curr_def = def; curr_def; curr_def = curr_def->next) {\n for(j=0; jnum_items; j++) {\n if ((def->items[j].type & 0xFFFF) == QSTRUCT_TYPE_NESTED) {\n HASH_FIND(hh, def_hash_by_name, def->items[j].nested_name, def->items[j].nested_name_len, def_lookup);\n if (!def_lookup)\n PARSE_ERROR(\"type '%.*s' referred to before being defined\", (int) def->items[j].nested_name_len, def->items[j].nested_name);\n\n def->items[j].nested_def = def_lookup;\n }\n }\n\n HASH_FIND(hh, def_hash_by_name, curr_def->name, curr_def->name_len, def_lookup);\n if (def_lookup)\n PARSE_ERROR(\"duplicate def name '%.*s'\", (int) curr_def->name_len, curr_def->name);\n\n HASH_ADD_KEYPTR(hh, def_hash_by_name, curr_def->name, curr_def->name_len, curr_def);\n\n if (calculate_qstruct_packing(curr_def) < 0)\n PARSE_ERROR(\"memory error in packing\");\n }\n\n\n \/\/ Success!\n goto cleanup;\n\n #undef PARSE_ERROR\n err_bail:\n\n for(err_ctx_start=p; err_ctx_start>schema && *err_ctx_start != '\\n' && (p-err_ctx_start) < 20; err_ctx_start--) {}\n while (isspace(*err_ctx_start) && err_ctx_start < p) err_ctx_start++;\n for(err_ctx_end=p; err_ctx_end<(pe-1) && *err_ctx_end != '\\n' && (err_ctx_end-p) < 20; err_ctx_end++) {}\n memcpy(err_ctx_buf, err_ctx_start, err_ctx_end - err_ctx_start);\n *(err_ctx_buf + (err_ctx_end - err_ctx_start)) = '\\0';\n snprintf(err_buf, err_buf_size, \"\\n------------------------------------------------------------\\nQstruct schema parse error (line %d, character %d)\\n\\n %s\\n %*s^\\n %*s|--%s\\n\\n------------------------------------------------------------\\n\", curr_line, (int)(p-schema), err_ctx_buf, (int)(p-err_ctx_start), \" \", (int)(p-err_ctx_start), \" \", err_desc_buf);\n\n if (def) {\n free_qstruct_definitions(def);\n def = NULL;\n }\n\n\n cleanup:\n\n HASH_CLEAR(hh, item_hash_by_name);\n HASH_CLEAR(hh, def_hash_by_name);\n\n return def;\n}\n\n\nvoid free_qstruct_definitions(struct qstruct_definition *def) {\n struct qstruct_definition *temp;\n\n while (def) {\n if (def->items) free(def->items);\n temp = def->next;\n free(def);\n def = temp;\n }\n}\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"55b7ee6d76eee2976b7c40ba9e8df6f3e50a2022","subject":"Start filling in data structure in parser actions, make tariff variable","message":"Start filling in data structure in parser actions, make tariff variable\n","repos":"lvzon\/dsmr-p1-parser,lvzon\/dsmr-p1-parser","old_file":"p1-parser.rl","new_file":"p1-parser.rl","new_contents":"\/*\n File: p1-parser.rl\n\n \t Ragel state-machine definition and supporting functions\n \t to parse Dutch Smart Meter P1-telegrams.\n \t \n \t (c)2017, Levien van Zon (levien at zonnetjes.net, https:\/\/github.com\/lvzon)\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"logmsg.h\"\n\n#include \"p1-parser.h\"\n\n\nlong long int TST_to_time (struct parser *fsm, int arg_idx) {\n\t\n\t\/\/ Get TST timestamp fields from stack and create a UNIX timestamp\n\t\/\/ The TST fields are: YYMMDDhhmmssX, with X = W for winter time or X = S for summer time\n\t\t\n\tstruct tm tm;\n\ttime_t time;\n\t\n\ttm.tm_year = fsm->arg[arg_idx] + 100;\t\/\/ Years since 1900, our value was years since 2000\n\ttm.tm_mon = fsm->arg[arg_idx + 1] - 1;\t\/\/ Months since start of year, starts at 0 (for January)\n\ttm.tm_mday = fsm->arg[arg_idx + 2];\t\t\/\/ Ordinal day of the month\n\ttm.tm_hour = fsm->arg[arg_idx + 3];\t\t\/\/ Hours past midnight, starts at 0\n\ttm.tm_min = fsm->arg[arg_idx + 4];\t\t\/\/ Minutes past the hour\n\ttm.tm_sec = fsm->arg[arg_idx + 5];\t\t\/\/ Seconds past the minute\n\t\n\tif (fsm->arg[arg_idx + 6] == 'S')\t\t\/\/ Daylight saving time flag\n\t\ttm.tm_isdst = 1;\t\t\t\t\t\t\/\/ Positive for daylight saving time (summer time)\n\telse if (fsm->arg[arg_idx + 6] == 'W')\n\t\ttm.tm_isdst = 0;\t\t\t\t\t\t\/\/ Zero if DST is not in effect (winter time)\n\telse\n\t\ttm.tm_isdst = -1;\t\t\t\t\t\t\/\/ Negative if DST information is not available\n\t\n\tlogmsg(LL_DEBUG, \"Time: %d %d %d %d %d %d %d\\n\", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_isdst);\n\t\n\tif (!fsm->meter_timezone)\n\t\tfsm->meter_timezone = METER_TIMEZONE;\n\t\n\tconst char *TZ = \"TZ\";\n\tchar *oldval_TZ = getenv(TZ);\n\tsetenv(TZ, fsm->meter_timezone, 1);\t\t\/\/ Set TZ timezone environment variable to meter timezone\n\t\t\n\ttime = mktime(&tm);\n\t\n\tif (oldval_TZ)\n\t\tsetenv(TZ, oldval_TZ, 1);\t\t\t\/\/ Restore TZ timezone environment variable\n\t\n\treturn time;\n}\n\n\n\/* Ragel state-machine definition *\/\n\n%%{\n\tmachine parser;\n\taccess fsm->;\n\n\tinclude parser \"parser-tools.rl\";\n\n\trest_of_line := [^\\r^\\n]* [\\r\\n]{2} @clearargs @{ fgoto main; };\t# Helper machine to parse the rest of the line in case of errors\n\t\t\n\t# Actions associated with commands\n\t\n\taction header { \n\t\tlogmsg(LL_VERBOSE, \"Header: %s\\n\", fsm->strarg[0]); \n\t\tstrncpy((char *)(fsm->data.header), fsm->strarg[0], LEN_HEADER); \n\t}\n\t\n\taction crc { \n\t\tlogmsg(LL_VERBOSE, \"CRC: 0x%x\\n\", (unsigned int)fsm->arg[0]); \n\t\tfsm->crc16 = fsm->arg[0]; \n\t}\n\t\n\taction P1_version { \n\t\tfsm->data.P1_version_major = fsm->arg[0] >> 4;\n\t\tfsm->data.P1_version_minor = fsm->arg[0] & 0xf;\n\t\tlogmsg(LL_VERBOSE, \"P1 version: %d.%d\\n\", (int)(fsm->data.P1_version_major), (int)(fsm->data.P1_version_minor)); \n\t}\n\t\n\taction timestamp {\n\t\tfsm->data.timestamp = TST_to_time(fsm, 0);\n\t\tlogmsg(LL_VERBOSE, \"Timestamp: %lu\\n\", (unsigned long)(fsm->data.timestamp));\n\t}\n\t\n\taction equipment_id { \n\t\tlogmsg(LL_VERBOSE, \"Equipment ID: %s\\n\", fsm->strarg[0]);\n\t\tstrncpy((char *)(fsm->data.equipment_id), fsm->strarg[0], LEN_EQUIPMENT_ID); \n\t}\n\t\n\taction tariff { \n\t\tfsm->data.tariff = fsm->arg[0];\n\t\tlogmsg(LL_VERBOSE, \"Tariff: %u\\n\", (unsigned int)(fsm->data.tariff));\n\t}\n\t\n\taction switchpos { \n\t\tfsm->data.switchpos = fsm->arg[0];\n\t\tlogmsg(LL_VERBOSE, \"Switch position: %d\\n\", (int)(fsm->data.switchpos));\n\t}\t\n\t\n\taction E_in {\n\t\tunsigned int tariff = fsm->arg[0];\n\t\tdouble value = (double)fsm->arg[1] \/ (double)fsm->arg[2];\n\t\tif (tariff > MAX_TARIFFS) {\n\t\t\tlogmsg(LL_ERROR, \"Tariff %u out of range, max. %u, E_in %f %s\\n\", tariff, MAX_TARIFFS, value, fsm->strarg[0]);\n\t\t} else {\n\t\t\tfsm->data.E_in[tariff] = value;\n\t\t\tstrncpy((char *)(fsm->unit_E_in[tariff]), fsm->strarg[0], LEN_UNIT + 1);\n\t\t\tlogmsg(LL_VERBOSE, \"Energy in, tariff %u: %f %s\\n\", value, fsm->strarg[0]); \n\t\t}\n\t}\n\t\n\taction E_out {\n\t\tunsigned int tariff = fsm->arg[0];\n\t\tdouble value = (double)fsm->arg[1] \/ (double)fsm->arg[2];\n\t\tif (tariff > MAX_TARIFFS) {\n\t\t\tlogmsg(LL_ERROR, \"Tariff %u out of range, max. %u, E_out %f %s\\n\", tariff, MAX_TARIFFS, value, fsm->strarg[0]);\n\t\t} else {\n\t\t\tfsm->data.E_out[tariff] = value;\n\t\t\tstrncpy((char *)(fsm->unit_E_out[tariff]), fsm->strarg[0], LEN_UNIT + 1);\n\t\t\tlogmsg(LL_VERBOSE, \"Energy out, tariff %u: %f %s\\n\", value, fsm->strarg[0]); \n\t\t}\n\t}\n\t\n\taction E_in_t1 { logmsg(LL_VERBOSE, \"Energy in, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_in_t2 { logmsg(LL_VERBOSE, \"Energy in, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t1 { logmsg(LL_VERBOSE, \"Energy out, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t2 { logmsg(LL_VERBOSE, \"Energy out, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\t\n\taction P_in { logmsg(LL_VERBOSE, \"Power in: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out { logmsg(LL_VERBOSE, \"Power out: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_threshold { logmsg(LL_VERBOSE, \"Power threshold: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction I_L1 { logmsg(LL_VERBOSE, \"Current L1: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L2 { logmsg(LL_VERBOSE, \"Current L2: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L3 { logmsg(LL_VERBOSE, \"Current L3: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_threshold { logmsg(LL_VERBOSE, \"Current threshold: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction V_L1 { logmsg(LL_VERBOSE, \"Voltage L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L2 { logmsg(LL_VERBOSE, \"Voltage L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L3 { logmsg(LL_VERBOSE, \"Voltage L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L1 { logmsg(LL_VERBOSE, \"Power in L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L2 { logmsg(LL_VERBOSE, \"Power in L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L3 { logmsg(LL_VERBOSE, \"Power in L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L1 { logmsg(LL_VERBOSE, \"Power out L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L2 { logmsg(LL_VERBOSE, \"Power out L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L3 { logmsg(LL_VERBOSE, \"Power out L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\t\n\taction pfail { logmsg(LL_VERBOSE, \"Power failures: %lld\\n\", fsm->arg[0]);}\n\taction longpfail { logmsg(LL_VERBOSE, \"Long power failures: %lld\\n\", fsm->arg[0]);}\n\taction pfailevent { logmsg(LL_VERBOSE, \"Power failure event at %lld, %lld %s\\n\", TST_to_time(fsm, 0), fsm->arg[7], fsm->strarg[0]);}\n\taction pfailevents { logmsg(LL_VERBOSE, \"Power failure events: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L1 { logmsg(LL_VERBOSE, \"Voltage sags L1: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L2 { logmsg(LL_VERBOSE, \"Voltage sags L2: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L3 { logmsg(LL_VERBOSE, \"Voltage sags L3: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L1 { logmsg(LL_VERBOSE, \"Voltage swells L1: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L2 { logmsg(LL_VERBOSE, \"Voltage swells L2: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L3 { logmsg(LL_VERBOSE, \"Voltage swells L3: %lld\\n\", fsm->arg[0]);}\n\taction textmsgcodes { logmsg(LL_VERBOSE, \"Text message codes: %s\\n\", fsm->strarg[0]);}\n\taction textmsg { logmsg(LL_VERBOSE, \"Text message: %s\\n\", fsm->strarg[0]); }\n\taction dev_type { logmsg(LL_VERBOSE, \"Device %lld type: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\n\taction dev_id { logmsg(LL_VERBOSE, \"Device %lld ID: %s\\n\", fsm->arg[0], fsm->strarg[0]);}\n\taction dev_counter { logmsg(LL_VERBOSE, \"Device %lld counter at %lld: %f %s\\n\", fsm->arg[0], TST_to_time(fsm, 1), (double)fsm->arg[8] \/ (double)fsm->arg[9], fsm->strarg[0]); }\n\taction dev_valve { logmsg(LL_VERBOSE, \"Device %lld valve position: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\t\n\taction dev_timeseries_head { logmsg(LL_VERBOSE, \"Device %lld timeseries, starting time %lld, status %lld, period %lld, values %lld:\\n\", fsm->arg[0], TST_to_time(fsm, 1), fsm->arg[7], fsm->arg[8], fsm->arg[9]); }\n\taction dev_timeseries_counter_head { logmsg(LL_VERBOSE, \"counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counter_cold_head { logmsg(LL_VERBOSE, \"cold counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counterval { logmsg(LL_VERBOSE, \"counter value: %f\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1]); }\n\taction gas_id_old { logmsg(LL_VERBOSE, \"Gas meter ID: %s\\n\", fsm->strarg[0]);}\n\taction gas_count_old { logmsg(LL_VERBOSE, \"Gas meter counter: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction gas_valve_old { logmsg(LL_VERBOSE, \"Gas meter valve position: %lld\\n\", fsm->arg[0]);}\t\n\taction error {logmsg(LL_VERBOSE, \"Error while parsing\\n\"); fsm->parse_errors++ ; fhold ; fgoto rest_of_line; } \n\t\n\t\n\taction unknown { logmsg(LL_VERBOSE, \"Unknown: %s\\n\", fsm->strarg[0]); fsm->strargc = 0 ; fsm->buflen = 0; }\n\n\t# Helpers that collect arguments\n\t\n\tdigitpair = (digit @add_digit){2} >cleararg %addarg;\t# Parse and store two digits\n\tdst = ([SW] >cleararg @addchar);\t# Parse and store daylight saving time character\n\t\n\tmbusid = ( [1234] @add_digit ) >cleararg %addarg;\t# We can have 4 additional MBUS devices: gas meter, water meter, thermal meter, slave meter \n\n\n\t# Definitions of statements and parts of statements\n\n\tcrlf = '\\r\\n';\t# Lines are terminated by carriage return + line feed\n\t#crlf = [\\r\\n]{2};\t# Lines are terminated by carriage return + line feed, but we'll also match some converted line ends\n\t\n\tfixedpoint = fpval;\t\t\t# Fixed point value, stored as an integer value and an integer divider \n\t\n\tTST = digitpair{6} dst;\n\tTST_old = digitpair{6};\n\tunit = [* ] ([^)]+ >addstr $str_append %str_term);\t\t# Unit separator is '*', but some meters use ' '\n\ttimeseries_unit = [^)]+ >addstr $str_append %str_term;\n\t\n\theaderstr = ([^\\r^\\n]+ >addstr $str_append %str_term);\n\t#msgstr = ([^)]* >addstr $str_append %str_term);\n\tmsgstr = hexstring;\n\tidstr = hexstring;\n\t\n\theader = '\/' headerstr crlf crlf @header @clearargs;\t\n\tend = '!' hexint? crlf @crc @clearargs;\t\t# Telegram end with optional CRC\n\t\n\tfixedpointval = '(' fixedpoint unit ')';\n\ttstval = '(' TST ')';\n\ttstval_old = '(' TST_old ')';\n\t\n\t# DSMR COSEM-objects\n\t\n\tP1_version = '1-3:0.2.8(' hexint ')' crlf @P1_version;\t\t# P1 version\n\ttimestamp = '0-0:1.0.0' tstval crlf @timestamp;\t\t\t# Telegram timestamp\n\t\n\tequipment_id = '0-0:96.1.1(' idstr ')' crlf @equipment_id;\t# Equipment ID\n\t\n\tE_in = '1-0:1.8.' uinteger fixedpointval crlf @E_in;\t# Electricity delivered to client\n\tE_out = '1-0:2.8.' uinteger fixedpointval crlf @E_out;\t# Electricity delivered by client\n\t\n\t# 1-0:1.8.0*255(0091158 kWh)\n\t\n\tE_in_t1 = '1-0:1.8.1' fixedpointval crlf @E_in_t1;\t# Electricity delivered to client in tariff 1\n\tE_in_t2 = '1-0:1.8.2' fixedpointval crlf @E_in_t2;\t# Electricity delivered to client in tariff 2\n\tE_out_t1 = '1-0:2.8.1' fixedpointval crlf @E_out_t1;\t# Electricity delivered by client in tariff 1\n\tE_out_t2 = '1-0:2.8.2' fixedpointval crlf @E_out_t2;\t# Electricity delivered by client in tariff 2\n\n\ttariff = '0-0:96.14.0(' uinteger ')' crlf @tariff;\t\t# TODO: can be non-integer, in theory?\n\tswitchpos = '0-0:' ('96.3.10' | '24.4.0') '(' uinteger ')' crlf @switchpos;\t# Switch position electricity (in\/out\/enabled), absent from DSMR>=4.0.7\n\n\tP_in = '1-0:1.7.0' fixedpointval crlf @P_in;\t# Actual power delivered to client\n\tP_out = '1-0:2.7.0' fixedpointval crlf @P_out;\t# Actual power delivered by client\n\tP_threshold = '0-0:17.0.0' fixedpointval crlf @P_threshold;\n\t\n\tpfail = '0-0:96.7.21(' uinteger ')' crlf @pfail; \n\tlongpfail = '0-0:96.7.9(' uinteger ')' crlf @longpfail; \n\t\n\tpfailevents = '1-0:99.97.0(' uinteger ')' @pfailevents @clearargs;\t# Power failure events\n\tpfailevent = tstval '(' uinteger unit ')' @pfailevent @clearargs;\t\t# Single power failure event\n\tpfaileventlog = pfailevents '(0-0:96.7.19)'? pfailevent* crlf;\t# Power failure event log, with zero or more events\n\t\n\tV_sags_L1 = '1-0:32.32.0(' uinteger ')' crlf @V_sags_L1;\n\tV_sags_L2 = '1-0:52.32.0(' uinteger ')' crlf @V_sags_L2;\n\tV_sags_L3 = '1-0:72.32.0(' uinteger ')' crlf @V_sags_L3;\n\t\n\tV_swells_L1 = '1-0:32.36.0(' uinteger ')' crlf @V_swells_L1;\t\n\tV_swells_L2 = '1-0:52.36.0(' uinteger ')' crlf @V_swells_L2;\n\tV_swells_L3 = '1-0:72.36.0(' uinteger ')' crlf @V_swells_L3;\n\t\n\ttextmsgcodes = '0-0:96.13.1(' msgstr ')' crlf @textmsgcodes;\n\ttextmsgcodes_empty = '0-0:96.13.1()' crlf;\n\ttextmsg = '0-0:96.13.0(' msgstr ')' crlf @textmsg;\n\ttextmsg_empty = '0-0:96.13.0()' crlf;\n\n\tV_L1 = '1-0:32.7.0' fixedpointval crlf @V_L1;\n\tV_L2 = '1-0:52.7.0' fixedpointval crlf @V_L2;\n\tV_L3 = '1-0:72.7.0' fixedpointval crlf @V_L3;\n\t\n\tI_L1 = '1-0:31.7.0(' uinteger unit ')' crlf @I_L1;\n\tI_L2 = '1-0:51.7.0(' uinteger unit ')' crlf @I_L2;\n\tI_L3 = '1-0:71.7.0(' uinteger unit ')' crlf @I_L3;\n\n\tI_threshold = '0-0:17.0.0(' uinteger unit ')' crlf @I_threshold;\n\t\n\tP_in_L1 = '1-0:21.7.0' fixedpointval crlf @P_in_L1;\n\tP_in_L2 = '1-0:41.7.0' fixedpointval crlf @P_in_L2;\n\tP_in_L3 = '1-0:61.7.0' fixedpointval crlf @P_in_L3;\n\t\n\tP_out_L1 = '1-0:22.7.0' fixedpointval crlf @P_out_L1;\n\tP_out_L2 = '1-0:42.7.0' fixedpointval crlf @P_out_L2;\n\tP_out_L3 = '1-0:62.7.0' fixedpointval crlf @P_out_L3;\n\t\n\tdev_type = '0-' mbusid ':24.1.0(' uinteger ')' crlf @dev_type;\n\tdev_id = '0-' mbusid ':96.1.0(' idstr ')' crlf @dev_id;\n\tdev_counter = '0-' mbusid ':24.2.1' tstval fixedpointval crlf @dev_counter;\t\n\tdev_valve = '0-' mbusid ':24.4.0(' uinteger ')' crlf @dev_valve;\t# Valve position (on\/off\/released), absent from DSMR>=4.0.7\n\t\n\t# This describes the rather horrible \"profile generic dataset\" representation used in DSMR 3.x\t\n\tdev_timeseries_head = '0-' mbusid ':24.3.0' tstval_old '(' uinteger ')' '(' uinteger ')' '(' uinteger ')' @dev_timeseries_head @clearargs;\n\tdev_timeseries_counter_head = '(0-' digit+ ':24.2.1)(' timeseries_unit ')' @dev_timeseries_counter_head @clearargs;\n\tdev_timeseries_counter_cold_head = '(0-' digit+ ':24.3.1)(' timeseries_unit ')' @dev_timeseries_counter_cold_head @clearargs;\n\tdev_timeseries_counterval = '(' fixedpoint ')' @dev_timeseries_counterval @clearargs;\n\tdev_counter_timeseries = dev_timeseries_head dev_timeseries_counter_head dev_timeseries_counterval+ crlf;\n\tdev_counter_cold_timeseries = dev_timeseries_head dev_timeseries_counter_cold_head dev_timeseries_counterval+ crlf;\n\t\n\tgas_id_old = '7-0:0.0.0(' idstr ')' crlf @gas_id_old;\n\tgas_count_old = '7-0:23.1.0' tstval fixedpointval crlf @gas_count_old;\n\t#gas_count_Tcomp_old = '7-0:23.2.0' tstval fixedpointval crlf @gas_count_Tcomp_old;\n\t#gas_valve_old = '7-0:24.4.0(' uinteger ')' crlf @gas_valve_old;\t\n\t#heat_id_old = '5-0:0.0.0(' idstr ')' crlf @heat_id_old;\n\t#cold_id_old = '6-0:0.0.0(' idstr ')' crlf @cold_id_old;\n\t#water_id_old = '8-0:0.0.0(' idstr ')' crlf @water_id_old;\n\t#heat_count_old = '5-0:1.0.0' tstval fixedpointval crlf @heat_count_old;\n\t#cold_count_old = '6-0:1.0.0' tstval fixedpointval crlf @cold_count_old;\n\t#water_count_old = '8-0:1.0.0' tstval fixedpointval crlf @water_count_old;\n\t\n\t# P1 Telegram components\n\t\n\tmetadata_object = P1_version | timestamp;\n\temeter_object = equipment_id | tariff | switchpos | E_in_t1 | E_in_t2 | E_out_t1 | E_out_t2;\n\tpower_object = P_in | P_out | P_in_L1 | P_out_L1 | P_in_L2 | P_out_L2 | P_in_L3 | P_out_L3 | P_threshold;\n\tcurrent_object = I_L1 | I_L2 | I_L3 | I_threshold;\n\tvoltage_object = V_L1 | V_L2 | V_L3;\n\tpower_quality_object = pfail | longpfail | pfaileventlog | V_sags_L1 | V_swells_L1 | V_sags_L2 | V_swells_L2 | V_sags_L3 | V_swells_L3;\n\tmbusdev_object = dev_type | dev_id | dev_counter | dev_valve | dev_counter_timeseries | dev_counter_cold_timeseries;\n\tslavedev_legacy_object = gas_id_old | gas_count_old;\n\tmessage_object = textmsgcodes | textmsg | textmsgcodes_empty | textmsg_empty;\n\t\n\tobject = \tmetadata_object | emeter_object | power_object | current_object | voltage_object | power_quality_object |\n\t\t\t\tmessage_object | mbusdev_object | slavedev_legacy_object;\n\t\n\tline = object $err(error) @clearargs;\t# Clear argument stacks at the end of each line, handle parsing errors\n\t\n\ttelegram = header? line* end;\t# Make header optional, so we can recover from errors in the middle of a telegram\n\t\n\tmain := telegram* $err(error);\t\t# Parse zero or more telegrams\n\t\n}%%\n\n%% write data;\n\n\nvoid parser_init( struct parser *fsm )\n{\n\tint arg;\n\t\n\tfsm->buflen = 0;\n\tfsm->argc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->arg[arg] = 0;\n\tfsm->multiplier = 1;\n\tfsm->bitcount = 0;\n\tfsm->strargc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->strarg[arg] = NULL;\n\tfsm->parse_errors = 0;\n\t\n\t%% write init;\n}\n\nvoid parser_execute(struct parser *fsm, const char *data, int len, int eofflag)\n{\n\tconst char *p = data;\n\tconst char *pe = data + len;\n\tconst char *eof = 0;\n\n\tif (eofflag)\n\t\teof = pe;\n\t\n\t%% write exec;\n\t\n\tfsm->pe = pe;\n}\n\nint parser_finish(struct parser *fsm)\n{\n\tif ( fsm->cs == parser_error )\t\t\t\/\/ Machine failed before matching\n\t\treturn -1;\n\tif ( fsm->cs >= parser_first_final )\t\/\/ Final state reached\n\t\treturn 1;\n\treturn 0;\t\t\t\t\t\t\t\t\/\/ Final state not reached\n}\n\n","old_contents":"\/*\n File: p1-parser.rl\n\n \t Ragel state-machine definition and supporting functions\n \t to parse Dutch Smart Meter P1-telegrams.\n \t \n \t (c)2017, Levien van Zon (levien at zonnetjes.net, https:\/\/github.com\/lvzon)\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"logmsg.h\"\n\n#include \"p1-parser.h\"\n\n\nlong long int TST_to_time (struct parser *fsm, int arg_idx) {\n\t\n\t\/\/ Get TST timestamp fields from stack and create a UNIX timestamp\n\t\/\/ The TST fields are: YYMMDDhhmmssX, with X = W for winter time or X = S for summer time\n\t\t\n\tstruct tm tm;\n\ttime_t time;\n\t\n\ttm.tm_year = fsm->arg[arg_idx] + 100;\t\/\/ Years since 1900, our value was years since 2000\n\ttm.tm_mon = fsm->arg[arg_idx + 1] - 1;\t\/\/ Months since start of year, starts at 0 (for January)\n\ttm.tm_mday = fsm->arg[arg_idx + 2];\t\t\/\/ Ordinal day of the month\n\ttm.tm_hour = fsm->arg[arg_idx + 3];\t\t\/\/ Hours past midnight, starts at 0\n\ttm.tm_min = fsm->arg[arg_idx + 4];\t\t\/\/ Minutes past the hour\n\ttm.tm_sec = fsm->arg[arg_idx + 5];\t\t\/\/ Seconds past the minute\n\t\n\tif (fsm->arg[arg_idx + 6] == 'S')\t\t\/\/ Daylight saving time flag\n\t\ttm.tm_isdst = 1;\t\t\t\t\t\t\/\/ Positive for daylight saving time (summer time)\n\telse if (fsm->arg[arg_idx + 6] == 'W')\n\t\ttm.tm_isdst = 0;\t\t\t\t\t\t\/\/ Zero if DST is not in effect (winter time)\n\telse\n\t\ttm.tm_isdst = -1;\t\t\t\t\t\t\/\/ Negative if DST information is not available\n\t\n\tlogmsg(LL_DEBUG, \"Time: %d %d %d %d %d %d %d\\n\", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_isdst);\n\t\n\tif (!fsm->meter_timezone)\n\t\tfsm->meter_timezone = METER_TIMEZONE;\n\t\n\tconst char *TZ = \"TZ\";\n\tchar *oldval_TZ = getenv(TZ);\n\tsetenv(TZ, fsm->meter_timezone, 1);\t\t\/\/ Set TZ timezone environment variable to meter timezone\n\t\t\n\ttime = mktime(&tm);\n\t\n\tif (oldval_TZ)\n\t\tsetenv(TZ, oldval_TZ, 1);\t\t\t\/\/ Restore TZ timezone environment variable\n\t\n\treturn time;\n}\n\n\n\/* Ragel state-machine definition *\/\n\n%%{\n\tmachine parser;\n\taccess fsm->;\n\n\tinclude parser \"parser-tools.rl\";\n\n\trest_of_line := [^\\r^\\n]* [\\r\\n]{2} @clearargs @{ fgoto main; };\t# Helper machine to parse the rest of the line in case of errors\n\t\t\n\t# Actions associated with commands\n\t\n\taction header { logmsg(LL_VERBOSE, \"Header: %s\\n\", fsm->strarg[0]); }\n\taction crc { logmsg(LL_VERBOSE, \"CRC: 0x%x\\n\", (unsigned int)fsm->arg[0]); fsm->crc16 = fsm->arg[0]; }\n\taction P1_version { logmsg(LL_VERBOSE, \"P1 version: %lld.%lld\\n\", fsm->arg[0] >> 4, fsm->arg[0] & 0xf); }\n\taction timestamp { logmsg(LL_VERBOSE, \"Timestamp: %lld\\n\", TST_to_time(fsm, 0));}\n\taction equipment_id { logmsg(LL_VERBOSE, \"Equipment ID: %s\\n\", fsm->strarg[0]);}\n\taction tariff { logmsg(LL_VERBOSE, \"Tariff: %lld\\n\", fsm->arg[0]);}\n\taction switchpos { logmsg(LL_VERBOSE, \"Switch position: %lld\\n\", fsm->arg[0]);}\t\n\taction E_in_t1 { logmsg(LL_VERBOSE, \"Energy in, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_in_t2 { logmsg(LL_VERBOSE, \"Energy in, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t1 { logmsg(LL_VERBOSE, \"Energy out, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t2 { logmsg(LL_VERBOSE, \"Energy out, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in { logmsg(LL_VERBOSE, \"Power in: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out { logmsg(LL_VERBOSE, \"Power out: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_threshold { logmsg(LL_VERBOSE, \"Power threshold: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction I_L1 { logmsg(LL_VERBOSE, \"Current L1: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L2 { logmsg(LL_VERBOSE, \"Current L2: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L3 { logmsg(LL_VERBOSE, \"Current L3: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_threshold { logmsg(LL_VERBOSE, \"Current threshold: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction V_L1 { logmsg(LL_VERBOSE, \"Voltage L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L2 { logmsg(LL_VERBOSE, \"Voltage L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L3 { logmsg(LL_VERBOSE, \"Voltage L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L1 { logmsg(LL_VERBOSE, \"Power in L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L2 { logmsg(LL_VERBOSE, \"Power in L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L3 { logmsg(LL_VERBOSE, \"Power in L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L1 { logmsg(LL_VERBOSE, \"Power out L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L2 { logmsg(LL_VERBOSE, \"Power out L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L3 { logmsg(LL_VERBOSE, \"Power out L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\t\n\taction pfail { logmsg(LL_VERBOSE, \"Power failures: %lld\\n\", fsm->arg[0]);}\n\taction longpfail { logmsg(LL_VERBOSE, \"Long power failures: %lld\\n\", fsm->arg[0]);}\n\taction pfailevent { logmsg(LL_VERBOSE, \"Power failure event at %lld, %lld %s\\n\", TST_to_time(fsm, 0), fsm->arg[7], fsm->strarg[0]);}\n\taction pfailevents { logmsg(LL_VERBOSE, \"Power failure events: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L1 { logmsg(LL_VERBOSE, \"Voltage sags L1: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L2 { logmsg(LL_VERBOSE, \"Voltage sags L2: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L3 { logmsg(LL_VERBOSE, \"Voltage sags L3: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L1 { logmsg(LL_VERBOSE, \"Voltage swells L1: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L2 { logmsg(LL_VERBOSE, \"Voltage swells L2: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L3 { logmsg(LL_VERBOSE, \"Voltage swells L3: %lld\\n\", fsm->arg[0]);}\n\taction textmsgcodes { logmsg(LL_VERBOSE, \"Text message codes: %s\\n\", fsm->strarg[0]);}\n\taction textmsg { logmsg(LL_VERBOSE, \"Text message: %s\\n\", fsm->strarg[0]); }\n\taction dev_type { logmsg(LL_VERBOSE, \"Device %lld type: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\n\taction dev_id { logmsg(LL_VERBOSE, \"Device %lld ID: %s\\n\", fsm->arg[0], fsm->strarg[0]);}\n\taction dev_counter { logmsg(LL_VERBOSE, \"Device %lld counter at %lld: %f %s\\n\", fsm->arg[0], TST_to_time(fsm, 1), (double)fsm->arg[8] \/ (double)fsm->arg[9], fsm->strarg[0]); }\n\taction dev_valve { logmsg(LL_VERBOSE, \"Device %lld valve position: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\t\n\taction dev_timeseries_head { logmsg(LL_VERBOSE, \"Device %lld timeseries, starting time %lld, status %lld, period %lld, values %lld:\\n\", fsm->arg[0], TST_to_time(fsm, 1), fsm->arg[7], fsm->arg[8], fsm->arg[9]); }\n\taction dev_timeseries_counter_head { logmsg(LL_VERBOSE, \"counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counter_cold_head { logmsg(LL_VERBOSE, \"cold counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counterval { logmsg(LL_VERBOSE, \"counter value: %f\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1]); }\n\taction gas_id_old { logmsg(LL_VERBOSE, \"Gas meter ID: %s\\n\", fsm->strarg[0]);}\n\taction gas_count_old { logmsg(LL_VERBOSE, \"Gas meter counter: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction gas_valve_old { logmsg(LL_VERBOSE, \"Gas meter valve position: %lld\\n\", fsm->arg[0]);}\t\n\taction error {logmsg(LL_VERBOSE, \"Error while parsing\\n\"); fsm->parse_errors++ ; fhold ; fgoto rest_of_line; } \n\t\n\t\n\taction unknown { logmsg(LL_VERBOSE, \"Unknown: %s\\n\", fsm->strarg[0]); fsm->strargc = 0 ; fsm->buflen = 0; }\n\n\t# Helpers that collect arguments\n\t\n\tdigitpair = (digit @add_digit){2} >cleararg %addarg;\t# Parse and store two digits\n\tdst = ([SW] >cleararg @addchar);\t# Parse and store daylight saving time character\n\t\n\tmbusid = ( [1234] @add_digit ) >cleararg %addarg;\t# We can have 4 additional MBUS devices: gas meter, water meter, thermal meter, slave meter \n\n\n\t# Definitions of statements and parts of statements\n\n\tcrlf = '\\r\\n';\t# Lines are terminated by carriage return + line feed\n\t#crlf = [\\r\\n]{2};\t# Lines are terminated by carriage return + line feed, but we'll also match some converted line ends\n\t\n\tfixedpoint = fpval;\t\t\t# Fixed point value, stored as an integer value and an integer divider \n\t\n\tTST = digitpair{6} dst;\n\tTST_old = digitpair{6};\n\tunit = '*' ([^)]+ >addstr $str_append %str_term);\n\ttimeseries_unit = [^)]+ >addstr $str_append %str_term;\n\t\n\theaderstr = ([^\\r^\\n]+ >addstr $str_append %str_term);\n\t#msgstr = ([^)]* >addstr $str_append %str_term);\n\tmsgstr = hexstring;\n\tidstr = hexstring;\n\t\n\theader = '\/' headerstr crlf crlf @header @clearargs;\t\n\tend = '!' hexint? crlf @crc @clearargs;\t\t# Telegram end with optional CRC\n\t\n\tfixedpointval = '(' fixedpoint unit ')';\n\ttstval = '(' TST ')';\n\ttstval_old = '(' TST_old ')';\n\t\n\t# DSMR COSEM-objects\n\t\n\tP1_version = '1-3:0.2.8(' hexint ')' crlf @P1_version;\t\t# P1 version\n\ttimestamp = '0-0:1.0.0' tstval crlf @timestamp;\t\t\t# Telegram timestamp\n\t\n\tequipment_id = '0-0:96.1.1(' idstr ')' crlf @equipment_id;\t# Equipment ID\n\t\n\tE_in_t1 = '1-0:1.8.1' fixedpointval crlf @E_in_t1;\t# Electricity delivered to client in tariff 1\n\tE_in_t2 = '1-0:1.8.2' fixedpointval crlf @E_in_t2;\t# Electricity delivered to client in tariff 2\n\tE_out_t1 = '1-0:2.8.1' fixedpointval crlf @E_out_t1;\t# Electricity delivered by client in tariff 1\n\tE_out_t2 = '1-0:2.8.2' fixedpointval crlf @E_out_t2;\t# Electricity delivered by client in tariff 2\n\ttariff = '0-0:96.14.0(' uinteger ')' crlf @tariff;\t\t# TODO: can be non-integer, in theory?\n\tswitchpos = '0-0:' ('96.3.10' | '24.4.0') '(' uinteger ')' crlf @switchpos;\t# Switch position electricity (in\/out\/enabled), absent from DSMR>=4.0.7\n\n\tP_in = '1-0:1.7.0' fixedpointval crlf @P_in;\t# Actual power delivered to client\n\tP_out = '1-0:2.7.0' fixedpointval crlf @P_out;\t# Actual power delivered by client\n\tP_threshold = '0-0:17.0.0' fixedpointval crlf @P_threshold;\n\t\n\tpfail = '0-0:96.7.21(' uinteger ')' crlf @pfail; \n\tlongpfail = '0-0:96.7.9(' uinteger ')' crlf @longpfail; \n\t\n\tpfailevents = '1-0:99.97.0(' uinteger ')' @pfailevents @clearargs;\t# Power failure events\n\tpfailevent = tstval '(' uinteger unit ')' @pfailevent @clearargs;\t\t# Single power failure event\n\tpfaileventlog = pfailevents '(0-0:96.7.19)'? pfailevent* crlf;\t# Power failure event log, with zero or more events\n\t\n\tV_sags_L1 = '1-0:32.32.0(' uinteger ')' crlf @V_sags_L1;\n\tV_sags_L2 = '1-0:52.32.0(' uinteger ')' crlf @V_sags_L2;\n\tV_sags_L3 = '1-0:72.32.0(' uinteger ')' crlf @V_sags_L3;\n\t\n\tV_swells_L1 = '1-0:32.36.0(' uinteger ')' crlf @V_swells_L1;\t\n\tV_swells_L2 = '1-0:52.36.0(' uinteger ')' crlf @V_swells_L2;\n\tV_swells_L3 = '1-0:72.36.0(' uinteger ')' crlf @V_swells_L3;\n\t\n\ttextmsgcodes = '0-0:96.13.1(' msgstr ')' crlf @textmsgcodes;\n\ttextmsgcodes_empty = '0-0:96.13.1()' crlf;\n\ttextmsg = '0-0:96.13.0(' msgstr ')' crlf @textmsg;\n\ttextmsg_empty = '0-0:96.13.0()' crlf;\n\n\tV_L1 = '1-0:32.7.0' fixedpointval crlf @V_L1;\n\tV_L2 = '1-0:52.7.0' fixedpointval crlf @V_L2;\n\tV_L3 = '1-0:72.7.0' fixedpointval crlf @V_L3;\n\t\n\tI_L1 = '1-0:31.7.0(' uinteger unit ')' crlf @I_L1;\n\tI_L2 = '1-0:51.7.0(' uinteger unit ')' crlf @I_L2;\n\tI_L3 = '1-0:71.7.0(' uinteger unit ')' crlf @I_L3;\n\n\tI_threshold = '0-0:17.0.0(' uinteger unit ')' crlf @I_threshold;\n\t\n\tP_in_L1 = '1-0:21.7.0' fixedpointval crlf @P_in_L1;\n\tP_in_L2 = '1-0:41.7.0' fixedpointval crlf @P_in_L2;\n\tP_in_L3 = '1-0:61.7.0' fixedpointval crlf @P_in_L3;\n\t\n\tP_out_L1 = '1-0:22.7.0' fixedpointval crlf @P_out_L1;\n\tP_out_L2 = '1-0:42.7.0' fixedpointval crlf @P_out_L2;\n\tP_out_L3 = '1-0:62.7.0' fixedpointval crlf @P_out_L3;\n\t\n\tdev_type = '0-' mbusid ':24.1.0(' uinteger ')' crlf @dev_type;\n\tdev_id = '0-' mbusid ':96.1.0(' idstr ')' crlf @dev_id;\n\tdev_counter = '0-' mbusid ':24.2.1' tstval fixedpointval crlf @dev_counter;\t\n\tdev_valve = '0-' mbusid ':24.4.0(' uinteger ')' crlf @dev_valve;\t# Valve position (on\/off\/released), absent from DSMR>=4.0.7\n\t\n\t# This describes the rather horrible \"profile generic dataset\" representation used in DSMR 3.x\t\n\tdev_timeseries_head = '0-' mbusid ':24.3.0' tstval_old '(' uinteger ')' '(' uinteger ')' '(' uinteger ')' @dev_timeseries_head @clearargs;\n\tdev_timeseries_counter_head = '(0-' digit+ ':24.2.1)(' timeseries_unit ')' @dev_timeseries_counter_head @clearargs;\n\tdev_timeseries_counter_cold_head = '(0-' digit+ ':24.3.1)(' timeseries_unit ')' @dev_timeseries_counter_cold_head @clearargs;\n\tdev_timeseries_counterval = '(' fixedpoint ')' @dev_timeseries_counterval @clearargs;\n\tdev_counter_timeseries = dev_timeseries_head dev_timeseries_counter_head dev_timeseries_counterval+ crlf;\n\tdev_counter_cold_timeseries = dev_timeseries_head dev_timeseries_counter_cold_head dev_timeseries_counterval+ crlf;\n\t\n\tgas_id_old = '7-0:0.0.0(' idstr ')' crlf @gas_id_old;\n\tgas_count_old = '7-0:23.1.0' tstval fixedpointval crlf @gas_count_old;\n\t#gas_count_Tcomp_old = '7-0:23.2.0' tstval fixedpointval crlf @gas_count_Tcomp_old;\n\t#gas_valve_old = '7-0:24.4.0(' uinteger ')' crlf @gas_valve_old;\t\n\t#heat_id_old = '5-0:0.0.0(' idstr ')' crlf @heat_id_old;\n\t#cold_id_old = '6-0:0.0.0(' idstr ')' crlf @cold_id_old;\n\t#water_id_old = '8-0:0.0.0(' idstr ')' crlf @water_id_old;\n\t#heat_count_old = '5-0:1.0.0' tstval fixedpointval crlf @heat_count_old;\n\t#cold_count_old = '6-0:1.0.0' tstval fixedpointval crlf @cold_count_old;\n\t#water_count_old = '8-0:1.0.0' tstval fixedpointval crlf @water_count_old;\n\t\n\t# P1 Telegram components\n\t\n\tmetadata_object = P1_version | timestamp;\n\temeter_object = equipment_id | tariff | switchpos | E_in_t1 | E_in_t2 | E_out_t1 | E_out_t2;\n\tpower_object = P_in | P_out | P_in_L1 | P_out_L1 | P_in_L2 | P_out_L2 | P_in_L3 | P_out_L3 | P_threshold;\n\tcurrent_object = I_L1 | I_L2 | I_L3 | I_threshold;\n\tvoltage_object = V_L1 | V_L2 | V_L3;\n\tpower_quality_object = pfail | longpfail | pfaileventlog | V_sags_L1 | V_swells_L1 | V_sags_L2 | V_swells_L2 | V_sags_L3 | V_swells_L3;\n\tmbusdev_object = dev_type | dev_id | dev_counter | dev_valve | dev_counter_timeseries | dev_counter_cold_timeseries;\n\tslavedev_legacy_object = gas_id_old | gas_count_old;\n\tmessage_object = textmsgcodes | textmsg | textmsgcodes_empty | textmsg_empty;\n\t\n\tobject = \tmetadata_object | emeter_object | power_object | current_object | voltage_object | power_quality_object |\n\t\t\t\tmessage_object | mbusdev_object | slavedev_legacy_object;\n\t\n\tline = object $err(error) @clearargs;\t# Clear argument stacks at the end of each line, handle parsing errors\n\t\n\ttelegram = header? line* end;\t# Make header optional, so we can recover from errors in the middle of a telegram\n\t\n\tmain := telegram* $err(error);\t\t# Parse zero or more telegrams\n\t\n}%%\n\n%% write data;\n\n\nvoid parser_init( struct parser *fsm )\n{\n\tint arg;\n\t\n\tfsm->buflen = 0;\n\tfsm->argc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->arg[arg] = 0;\n\tfsm->multiplier = 1;\n\tfsm->bitcount = 0;\n\tfsm->strargc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->strarg[arg] = NULL;\n\tfsm->parse_errors = 0;\n\t\n\t%% write init;\n}\n\nvoid parser_execute(struct parser *fsm, const char *data, int len, int eofflag)\n{\n\tconst char *p = data;\n\tconst char *pe = data + len;\n\tconst char *eof = 0;\n\n\tif (eofflag)\n\t\teof = pe;\n\t\n\t%% write exec;\n\t\n\tfsm->pe = pe;\n}\n\nint parser_finish(struct parser *fsm)\n{\n\tif ( fsm->cs == parser_error )\t\t\t\/\/ Machine failed before matching\n\t\treturn -1;\n\tif ( fsm->cs >= parser_first_final )\t\/\/ Final state reached\n\t\treturn 1;\n\treturn 0;\t\t\t\t\t\t\t\t\/\/ Final state not reached\n}\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"513ed0ed831477367d6ee0ff89231846ee6ed855","subject":"Modify parser to process a slightly more general subset of IEC 62056-21","message":"Modify parser to process a slightly more general subset of IEC 62056-21\n\n- Allow IEC 62056-21 billing period specifier in equipment ID and energy\ncounter values\n- Allow space as unit separator (used in some non-conforming IEC\n62056-21 Iskra-meters)\n- Allow IEC 62056-21 equipment ID (0.0.0)\n","repos":"lvzon\/dsmr-p1-parser,lvzon\/dsmr-p1-parser","old_file":"p1-parser.rl","new_file":"p1-parser.rl","new_contents":"\/*\n File: p1-parser.rl\n\n \t Ragel state-machine definition and supporting functions\n \t to parse Dutch Smart Meter P1-telegrams (and a subset of generic IEC 62056-21 smart meter telegrams).\n \t \n \t (c)2017-2018, Levien van Zon (levien at zonnetjes.net, https:\/\/github.com\/lvzon)\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"logmsg.h\"\n\n#include \"p1-parser.h\"\n\n\nlong long int TST_to_time (struct parser *fsm, int arg_idx) {\n\t\n\t\/\/ Get TST timestamp fields from stack and create a UNIX timestamp\n\t\/\/ The TST fields are: YYMMDDhhmmssX, with X = W for winter time or X = S for summer time\n\t\t\n\tstruct tm tm;\n\ttime_t time;\n\t\n\ttm.tm_year = fsm->arg[arg_idx] + 100;\t\/\/ Years since 1900, our value was years since 2000\n\ttm.tm_mon = fsm->arg[arg_idx + 1] - 1;\t\/\/ Months since start of year, starts at 0 (for January)\n\ttm.tm_mday = fsm->arg[arg_idx + 2];\t\t\/\/ Ordinal day of the month\n\ttm.tm_hour = fsm->arg[arg_idx + 3];\t\t\/\/ Hours past midnight, starts at 0\n\ttm.tm_min = fsm->arg[arg_idx + 4];\t\t\/\/ Minutes past the hour\n\ttm.tm_sec = fsm->arg[arg_idx + 5];\t\t\/\/ Seconds past the minute\n\t\n\tif (fsm->arg[arg_idx + 6] == 'S')\t\t\/\/ Daylight saving time flag\n\t\ttm.tm_isdst = 1;\t\t\t\t\t\t\/\/ Positive for daylight saving time (summer time)\n\telse if (fsm->arg[arg_idx + 6] == 'W')\n\t\ttm.tm_isdst = 0;\t\t\t\t\t\t\/\/ Zero if DST is not in effect (winter time)\n\telse\n\t\ttm.tm_isdst = -1;\t\t\t\t\t\t\/\/ Negative if DST information is not available\n\t\n\tlogmsg(LL_DEBUG, \"Time: %d %d %d %d %d %d %d\\n\", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_isdst);\n\t\n\tif (!fsm->meter_timezone)\n\t\tfsm->meter_timezone = METER_TIMEZONE;\n\t\n\tconst char *TZ = \"TZ\";\n\tchar *oldval_TZ = getenv(TZ);\n\tsetenv(TZ, fsm->meter_timezone, 1);\t\t\/\/ Set TZ timezone environment variable to meter timezone\n\t\t\n\ttime = mktime(&tm);\n\t\n\tif (oldval_TZ)\n\t\tsetenv(TZ, oldval_TZ, 1);\t\t\t\/\/ Restore TZ timezone environment variable\n\t\n\treturn time;\n}\n\n\n\/* Ragel state-machine definition *\/\n\n%%{\n\tmachine parser;\n\taccess fsm->;\n\n\tinclude parser \"parser-tools.rl\";\n\n\trest_of_line := [^\\r^\\n]* [\\r\\n]{2} @clearargs @{ fgoto main; };\t# Helper machine to parse the rest of the line in case of errors\n\t\t\n\t# Actions associated with commands\n\t\n\taction header { logmsg(LL_VERBOSE, \"Header: %s\\n\", fsm->strarg[0]); }\n\taction crc { logmsg(LL_VERBOSE, \"CRC: 0x%x\\n\", (unsigned int)fsm->arg[0]); fsm->crc16 = fsm->arg[0]; }\n\taction P1_version { logmsg(LL_VERBOSE, \"P1 version: %lld.%lld\\n\", fsm->arg[0] >> 4, fsm->arg[0] & 0xf); }\n\taction timestamp { logmsg(LL_VERBOSE, \"Timestamp: %lld\\n\", TST_to_time(fsm, 0));}\n\taction equipment_id { logmsg(LL_VERBOSE, \"Equipment ID: %s\\n\", fsm->strarg[0]);}\n\taction tariff { logmsg(LL_VERBOSE, \"Tariff: %lld\\n\", fsm->arg[0]);}\n\taction switchpos { logmsg(LL_VERBOSE, \"Switch position: %lld\\n\", fsm->arg[0]);}\t\n\taction E_in_t1 { logmsg(LL_VERBOSE, \"Energy in, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_in_t2 { logmsg(LL_VERBOSE, \"Energy in, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t1 { logmsg(LL_VERBOSE, \"Energy out, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t2 { logmsg(LL_VERBOSE, \"Energy out, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in { logmsg(LL_VERBOSE, \"Power in: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out { logmsg(LL_VERBOSE, \"Power out: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_threshold { logmsg(LL_VERBOSE, \"Power threshold: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction I_L1 { logmsg(LL_VERBOSE, \"Current L1: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L2 { logmsg(LL_VERBOSE, \"Current L2: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L3 { logmsg(LL_VERBOSE, \"Current L3: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_threshold { logmsg(LL_VERBOSE, \"Current threshold: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction V_L1 { logmsg(LL_VERBOSE, \"Voltage L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L2 { logmsg(LL_VERBOSE, \"Voltage L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L3 { logmsg(LL_VERBOSE, \"Voltage L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L1 { logmsg(LL_VERBOSE, \"Power in L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L2 { logmsg(LL_VERBOSE, \"Power in L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L3 { logmsg(LL_VERBOSE, \"Power in L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L1 { logmsg(LL_VERBOSE, \"Power out L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L2 { logmsg(LL_VERBOSE, \"Power out L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L3 { logmsg(LL_VERBOSE, \"Power out L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\t\n\taction pfail { logmsg(LL_VERBOSE, \"Power failures: %lld\\n\", fsm->arg[0]);}\n\taction longpfail { logmsg(LL_VERBOSE, \"Long power failures: %lld\\n\", fsm->arg[0]);}\n\taction pfailevent { logmsg(LL_VERBOSE, \"Power failure event at %lld, %lld %s\\n\", TST_to_time(fsm, 0), fsm->arg[7], fsm->strarg[0]);}\n\taction pfailevents { logmsg(LL_VERBOSE, \"Power failure events: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L1 { logmsg(LL_VERBOSE, \"Voltage sags L1: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L2 { logmsg(LL_VERBOSE, \"Voltage sags L2: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L3 { logmsg(LL_VERBOSE, \"Voltage sags L3: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L1 { logmsg(LL_VERBOSE, \"Voltage swells L1: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L2 { logmsg(LL_VERBOSE, \"Voltage swells L2: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L3 { logmsg(LL_VERBOSE, \"Voltage swells L3: %lld\\n\", fsm->arg[0]);}\n\taction textmsgcodes { logmsg(LL_VERBOSE, \"Text message codes: %s\\n\", fsm->strarg[0]);}\n\taction textmsg { logmsg(LL_VERBOSE, \"Text message: %s\\n\", fsm->strarg[0]); }\n\taction dev_type { logmsg(LL_VERBOSE, \"Device %lld type: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\n\taction dev_id { logmsg(LL_VERBOSE, \"Device %lld ID: %s\\n\", fsm->arg[0], fsm->strarg[0]);}\n\taction dev_counter { logmsg(LL_VERBOSE, \"Device %lld counter at %lld: %f %s\\n\", fsm->arg[0], TST_to_time(fsm, 1), (double)fsm->arg[8] \/ (double)fsm->arg[9], fsm->strarg[0]); }\n\taction dev_valve { logmsg(LL_VERBOSE, \"Device %lld valve position: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\t\n\taction dev_timeseries_head { logmsg(LL_VERBOSE, \"Device %lld timeseries, starting time %lld, status %lld, period %lld, values %lld:\\n\", fsm->arg[0], TST_to_time(fsm, 1), fsm->arg[7], fsm->arg[8], fsm->arg[9]); }\n\taction dev_timeseries_counter_head { logmsg(LL_VERBOSE, \"counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counter_cold_head { logmsg(LL_VERBOSE, \"cold counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counterval { logmsg(LL_VERBOSE, \"counter value: %f\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1]); }\n\taction gas_id_old { logmsg(LL_VERBOSE, \"Gas meter ID: %s\\n\", fsm->strarg[0]);}\n\taction gas_count_old { logmsg(LL_VERBOSE, \"Gas meter counter: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction gas_valve_old { logmsg(LL_VERBOSE, \"Gas meter valve position: %lld\\n\", fsm->arg[0]);}\t\n\taction error {logmsg(LL_VERBOSE, \"Error while parsing\\n\"); fsm->parse_errors++ ; fhold ; fgoto rest_of_line; } \n\t\n\t\n\taction unknown { logmsg(LL_VERBOSE, \"Unknown: %s\\n\", fsm->strarg[0]); fsm->strargc = 0 ; fsm->buflen = 0; }\n\n\t# Helpers that collect arguments\n\t\n\tdigitpair = (digit @add_digit){2} >cleararg %addarg;\t# Parse and store two digits\n\tdst = ([SW] >cleararg @addchar);\t# Parse and store daylight saving time character\n\t\n\tmbusid = ( [1234] @add_digit ) >cleararg %addarg;\t# We can have 4 additional MBUS devices: gas meter, water meter, thermal meter, slave meter \n\n\n\t# Definitions of statements and parts of statements\n\n\tcrlf = '\\r\\n';\t# Lines are terminated by carriage return + line feed\n\t#crlf = [\\r\\n]{2};\t# Lines are terminated by carriage return + line feed, but we'll also match some converted line ends\n\t\n\tfixedpoint = fpval;\t\t\t# Fixed point value, stored as an integer value and an integer divider \n\t\n\tTST = digitpair{6} dst;\n\tTST_old = digitpair{6};\n\tunit = [* ] ([^)]+ >addstr $str_append %str_term);\t# Formally only '*' is a valid unit separator, but some meters use a space (and thus put the unit in the value string)\n\ttimeseries_unit = [^)]+ >addstr $str_append %str_term;\n\t\n\tbilling_period = ('*' digit+)?;\t\t# The billing period specifier is part of IEC 62056-21, but currently isn't present in DSMR telegrams, so we make it optional\n\t\n\theaderstr = ([^\\r^\\n]+ >addstr $str_append %str_term);\n\t#msgstr = ([^)]* >addstr $str_append %str_term);\n\tmsgstr = hexstring;\n\tidstr = hexstring;\n\t\n\theader = '\/' headerstr crlf crlf @header @clearargs;\t\n\tend = '!' hexint? crlf @crc @clearargs;\t\t# Telegram end with optional CRC\n\t\n\tfixedpointval = '(' fixedpoint unit ')';\t# The value can be either integer or non-integer\n\ttstval = '(' TST ')';\n\ttstval_old = '(' TST_old ')';\n\t\n\t# COSEM-objects supported by DSMR\n\t\n\tP1_version = '1-3:0.2.8(' hexint ')' crlf @P1_version;\t\t# P1 version\n\ttimestamp = '0-0:1.0.0' tstval crlf @timestamp;\t\t\t# Telegram timestamp\n\t\n\tequipment_id_p1 = '0-0:96.1.1' billing_period '(' idstr ')' crlf @equipment_id;\t# Equipment ID in P1-meters\n\tequipment_id_iec = digit '-0:0.0.0' billing_period '(' uinteger ')' crlf @equipment_id;\t# Equipment ID in IEC 62056-21 meters\n\t\n\tE_in_t1 = '1-0:1.8.1' billing_period fixedpointval crlf @E_in_t1;\t# Electricity delivered to client in tariff 1\n\tE_in_t2 = '1-0:1.8.2' billing_period fixedpointval crlf @E_in_t2;\t# Electricity delivered to client in tariff 2\n\tE_out_t1 = '1-0:2.8.1' billing_period fixedpointval crlf @E_out_t1;\t# Electricity delivered by client in tariff 1\n\tE_out_t2 = '1-0:2.8.2' billing_period fixedpointval crlf @E_out_t2;\t# Electricity delivered by client in tariff 2\n\ttariff = '0-0:96.14.0(' uinteger ')' crlf @tariff;\t\t# TODO: can be non-integer, in theory?\n\tswitchpos = '0-0:' ('96.3.10' | '24.4.0') '(' uinteger ')' crlf @switchpos;\t# Switch position electricity (in\/out\/enabled), absent from DSMR>=4.0.7\n\n\tP_in = '1-0:1.7.0' fixedpointval crlf @P_in;\t# Actual power delivered to client\n\tP_out = '1-0:2.7.0' fixedpointval crlf @P_out;\t# Actual power delivered by client\n\tP_threshold = '0-0:17.0.0' fixedpointval crlf @P_threshold;\n\t\n\tpfail = '0-0:96.7.21(' uinteger ')' crlf @pfail; \n\tlongpfail = '0-0:96.7.9(' uinteger ')' crlf @longpfail; \n\t\n\tpfailevents = '1-0:99.97.0(' uinteger ')' @pfailevents @clearargs;\t# Power failure events\n\tpfailevent = tstval '(' uinteger unit ')' @pfailevent @clearargs;\t\t# Single power failure event\n\tpfaileventlog = pfailevents '(0-0:96.7.19)'? pfailevent* crlf;\t# Power failure event log, with zero or more events\n\t\n\tV_sags_L1 = '1-0:32.32.0(' uinteger ')' crlf @V_sags_L1;\n\tV_sags_L2 = '1-0:52.32.0(' uinteger ')' crlf @V_sags_L2;\n\tV_sags_L3 = '1-0:72.32.0(' uinteger ')' crlf @V_sags_L3;\n\t\n\tV_swells_L1 = '1-0:32.36.0(' uinteger ')' crlf @V_swells_L1;\t\n\tV_swells_L2 = '1-0:52.36.0(' uinteger ')' crlf @V_swells_L2;\n\tV_swells_L3 = '1-0:72.36.0(' uinteger ')' crlf @V_swells_L3;\n\t\n\ttextmsgcodes = '0-0:96.13.1(' msgstr ')' crlf @textmsgcodes;\n\ttextmsgcodes_empty = '0-0:96.13.1()' crlf;\n\ttextmsg = '0-0:96.13.0(' msgstr ')' crlf @textmsg;\n\ttextmsg_empty = '0-0:96.13.0()' crlf;\n\n\tV_L1 = '1-0:32.7.0' fixedpointval crlf @V_L1;\n\tV_L2 = '1-0:52.7.0' fixedpointval crlf @V_L2;\n\tV_L3 = '1-0:72.7.0' fixedpointval crlf @V_L3;\n\t\n\tI_L1 = '1-0:31.7.0(' uinteger unit ')' crlf @I_L1;\n\tI_L2 = '1-0:51.7.0(' uinteger unit ')' crlf @I_L2;\n\tI_L3 = '1-0:71.7.0(' uinteger unit ')' crlf @I_L3;\n\n\tI_threshold = '0-0:17.0.0(' uinteger unit ')' crlf @I_threshold;\n\t\n\tP_in_L1 = '1-0:21.7.0' fixedpointval crlf @P_in_L1;\n\tP_in_L2 = '1-0:41.7.0' fixedpointval crlf @P_in_L2;\n\tP_in_L3 = '1-0:61.7.0' fixedpointval crlf @P_in_L3;\n\t\n\tP_out_L1 = '1-0:22.7.0' fixedpointval crlf @P_out_L1;\n\tP_out_L2 = '1-0:42.7.0' fixedpointval crlf @P_out_L2;\n\tP_out_L3 = '1-0:62.7.0' fixedpointval crlf @P_out_L3;\n\t\n\tdev_type = '0-' mbusid ':24.1.0(' uinteger ')' crlf @dev_type;\n\tdev_id = '0-' mbusid ':96.1.0(' idstr ')' crlf @dev_id;\n\tdev_counter = '0-' mbusid ':24.2.1' tstval fixedpointval crlf @dev_counter;\t\n\tdev_valve = '0-' mbusid ':24.4.0(' uinteger ')' crlf @dev_valve;\t# Valve position (on\/off\/released), absent from DSMR>=4.0.7\n\t\n\t# This describes the rather horrible \"profile generic dataset\" representation used in DSMR 3.x\t\n\tdev_timeseries_head = '0-' mbusid ':24.3.0' tstval_old '(' uinteger ')' '(' uinteger ')' '(' uinteger ')' @dev_timeseries_head @clearargs;\n\tdev_timeseries_counter_head = '(0-' digit+ ':24.2.1)(' timeseries_unit ')' @dev_timeseries_counter_head @clearargs;\n\tdev_timeseries_counter_cold_head = '(0-' digit+ ':24.3.1)(' timeseries_unit ')' @dev_timeseries_counter_cold_head @clearargs;\n\tdev_timeseries_counterval = '(' fixedpoint ')' @dev_timeseries_counterval @clearargs;\n\tdev_counter_timeseries = dev_timeseries_head dev_timeseries_counter_head dev_timeseries_counterval+ crlf;\n\tdev_counter_cold_timeseries = dev_timeseries_head dev_timeseries_counter_cold_head dev_timeseries_counterval+ crlf;\n\t\n\tgas_id_old = '7-0:0.0.0(' idstr ')' crlf @gas_id_old;\n\tgas_count_old = '7-0:23.1.0' tstval fixedpointval crlf @gas_count_old;\n\t#gas_count_Tcomp_old = '7-0:23.2.0' tstval fixedpointval crlf @gas_count_Tcomp_old;\n\t#gas_valve_old = '7-0:24.4.0(' uinteger ')' crlf @gas_valve_old;\t\n\t#heat_id_old = '5-0:0.0.0(' idstr ')' crlf @heat_id_old;\n\t#cold_id_old = '6-0:0.0.0(' idstr ')' crlf @cold_id_old;\n\t#water_id_old = '8-0:0.0.0(' idstr ')' crlf @water_id_old;\n\t#heat_count_old = '5-0:1.0.0' tstval fixedpointval crlf @heat_count_old;\n\t#cold_count_old = '6-0:1.0.0' tstval fixedpointval crlf @cold_count_old;\n\t#water_count_old = '8-0:1.0.0' tstval fixedpointval crlf @water_count_old;\n\t\n\t# P1 Telegram components\n\t\n\tequipment_id = equipment_id_p1 | equipment_id_iec;\n\tmetadata_object = P1_version | timestamp;\n\temeter_object = equipment_id | tariff | switchpos | E_in_t1 | E_in_t2 | E_out_t1 | E_out_t2;\n\tpower_object = P_in | P_out | P_in_L1 | P_out_L1 | P_in_L2 | P_out_L2 | P_in_L3 | P_out_L3 | P_threshold;\n\tcurrent_object = I_L1 | I_L2 | I_L3 | I_threshold;\n\tvoltage_object = V_L1 | V_L2 | V_L3;\n\tpower_quality_object = pfail | longpfail | pfaileventlog | V_sags_L1 | V_swells_L1 | V_sags_L2 | V_swells_L2 | V_sags_L3 | V_swells_L3;\n\tmbusdev_object = dev_type | dev_id | dev_counter | dev_valve | dev_counter_timeseries | dev_counter_cold_timeseries;\n\tslavedev_legacy_object = gas_id_old | gas_count_old;\n\tmessage_object = textmsgcodes | textmsg | textmsgcodes_empty | textmsg_empty;\n\t\n\tobject = \tmetadata_object | emeter_object | power_object | current_object | voltage_object | power_quality_object |\n\t\t\t\tmessage_object | mbusdev_object | slavedev_legacy_object;\n\t\n\tline = object $err(error) @clearargs;\t# Clear argument stacks at the end of each line, handle parsing errors\n\t\n\ttelegram = header? line* end;\t# Make header optional, so we can recover from errors in the middle of a telegram\n\t\n\tmain := telegram* $err(error);\t\t# Parse zero or more telegrams\n\t\n}%%\n\n%% write data;\n\n\nvoid parser_init( struct parser *fsm )\n{\n\tint arg;\n\t\n\tfsm->buflen = 0;\n\tfsm->argc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->arg[arg] = 0;\n\tfsm->multiplier = 1;\n\tfsm->bitcount = 0;\n\tfsm->strargc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->strarg[arg] = NULL;\n\tfsm->parse_errors = 0;\n\t\n\t%% write init;\n}\n\nvoid parser_execute(struct parser *fsm, const char *data, int len, int eofflag)\n{\n\tconst char *p = data;\n\tconst char *pe = data + len;\n\tconst char *eof = 0;\n\n\tif (eofflag)\n\t\teof = pe;\n\t\n\t%% write exec;\n\t\n\tfsm->pe = pe;\n}\n\nint parser_finish(struct parser *fsm)\n{\n\tif ( fsm->cs == parser_error )\t\t\t\/\/ Machine failed before matching\n\t\treturn -1;\n\tif ( fsm->cs >= parser_first_final )\t\/\/ Final state reached\n\t\treturn 1;\n\treturn 0;\t\t\t\t\t\t\t\t\/\/ Final state not reached\n}\n\n","old_contents":"\/*\n File: p1-parser.rl\n\n \t Ragel state-machine definition and supporting functions\n \t to parse Dutch Smart Meter P1-telegrams.\n \t \n \t (c)2017, Levien van Zon (levien at zonnetjes.net, https:\/\/github.com\/lvzon)\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"logmsg.h\"\n\n#include \"p1-parser.h\"\n\n\nlong long int TST_to_time (struct parser *fsm, int arg_idx) {\n\t\n\t\/\/ Get TST timestamp fields from stack and create a UNIX timestamp\n\t\/\/ The TST fields are: YYMMDDhhmmssX, with X = W for winter time or X = S for summer time\n\t\t\n\tstruct tm tm;\n\ttime_t time;\n\t\n\ttm.tm_year = fsm->arg[arg_idx] + 100;\t\/\/ Years since 1900, our value was years since 2000\n\ttm.tm_mon = fsm->arg[arg_idx + 1] - 1;\t\/\/ Months since start of year, starts at 0 (for January)\n\ttm.tm_mday = fsm->arg[arg_idx + 2];\t\t\/\/ Ordinal day of the month\n\ttm.tm_hour = fsm->arg[arg_idx + 3];\t\t\/\/ Hours past midnight, starts at 0\n\ttm.tm_min = fsm->arg[arg_idx + 4];\t\t\/\/ Minutes past the hour\n\ttm.tm_sec = fsm->arg[arg_idx + 5];\t\t\/\/ Seconds past the minute\n\t\n\tif (fsm->arg[arg_idx + 6] == 'S')\t\t\/\/ Daylight saving time flag\n\t\ttm.tm_isdst = 1;\t\t\t\t\t\t\/\/ Positive for daylight saving time (summer time)\n\telse if (fsm->arg[arg_idx + 6] == 'W')\n\t\ttm.tm_isdst = 0;\t\t\t\t\t\t\/\/ Zero if DST is not in effect (winter time)\n\telse\n\t\ttm.tm_isdst = -1;\t\t\t\t\t\t\/\/ Negative if DST information is not available\n\t\n\tlogmsg(LL_DEBUG, \"Time: %d %d %d %d %d %d %d\\n\", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_isdst);\n\t\n\tif (!fsm->meter_timezone)\n\t\tfsm->meter_timezone = METER_TIMEZONE;\n\t\n\tconst char *TZ = \"TZ\";\n\tchar *oldval_TZ = getenv(TZ);\n\tsetenv(TZ, fsm->meter_timezone, 1);\t\t\/\/ Set TZ timezone environment variable to meter timezone\n\t\t\n\ttime = mktime(&tm);\n\t\n\tif (oldval_TZ)\n\t\tsetenv(TZ, oldval_TZ, 1);\t\t\t\/\/ Restore TZ timezone environment variable\n\t\n\treturn time;\n}\n\n\n\/* Ragel state-machine definition *\/\n\n%%{\n\tmachine parser;\n\taccess fsm->;\n\n\tinclude parser \"parser-tools.rl\";\n\n\trest_of_line := [^\\r^\\n]* [\\r\\n]{2} @clearargs @{ fgoto main; };\t# Helper machine to parse the rest of the line in case of errors\n\t\t\n\t# Actions associated with commands\n\t\n\taction header { logmsg(LL_VERBOSE, \"Header: %s\\n\", fsm->strarg[0]); }\n\taction crc { logmsg(LL_VERBOSE, \"CRC: 0x%x\\n\", (unsigned int)fsm->arg[0]); fsm->crc16 = fsm->arg[0]; }\n\taction P1_version { logmsg(LL_VERBOSE, \"P1 version: %lld.%lld\\n\", fsm->arg[0] >> 4, fsm->arg[0] & 0xf); }\n\taction timestamp { logmsg(LL_VERBOSE, \"Timestamp: %lld\\n\", TST_to_time(fsm, 0));}\n\taction equipment_id { logmsg(LL_VERBOSE, \"Equipment ID: %s\\n\", fsm->strarg[0]);}\n\taction tariff { logmsg(LL_VERBOSE, \"Tariff: %lld\\n\", fsm->arg[0]);}\n\taction switchpos { logmsg(LL_VERBOSE, \"Switch position: %lld\\n\", fsm->arg[0]);}\t\n\taction E_in_t1 { logmsg(LL_VERBOSE, \"Energy in, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_in_t2 { logmsg(LL_VERBOSE, \"Energy in, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t1 { logmsg(LL_VERBOSE, \"Energy out, tariff 1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction E_out_t2 { logmsg(LL_VERBOSE, \"Energy out, tariff 2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in { logmsg(LL_VERBOSE, \"Power in: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out { logmsg(LL_VERBOSE, \"Power out: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_threshold { logmsg(LL_VERBOSE, \"Power threshold: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction I_L1 { logmsg(LL_VERBOSE, \"Current L1: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L2 { logmsg(LL_VERBOSE, \"Current L2: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_L3 { logmsg(LL_VERBOSE, \"Current L3: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction I_threshold { logmsg(LL_VERBOSE, \"Current threshold: %lld %s\\n\", fsm->arg[0], fsm->strarg[0]); }\n\taction V_L1 { logmsg(LL_VERBOSE, \"Voltage L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L2 { logmsg(LL_VERBOSE, \"Voltage L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction V_L3 { logmsg(LL_VERBOSE, \"Voltage L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L1 { logmsg(LL_VERBOSE, \"Power in L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L2 { logmsg(LL_VERBOSE, \"Power in L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_in_L3 { logmsg(LL_VERBOSE, \"Power in L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L1 { logmsg(LL_VERBOSE, \"Power out L1: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L2 { logmsg(LL_VERBOSE, \"Power out L2: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction P_out_L3 { logmsg(LL_VERBOSE, \"Power out L3: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\t\n\taction pfail { logmsg(LL_VERBOSE, \"Power failures: %lld\\n\", fsm->arg[0]);}\n\taction longpfail { logmsg(LL_VERBOSE, \"Long power failures: %lld\\n\", fsm->arg[0]);}\n\taction pfailevent { logmsg(LL_VERBOSE, \"Power failure event at %lld, %lld %s\\n\", TST_to_time(fsm, 0), fsm->arg[7], fsm->strarg[0]);}\n\taction pfailevents { logmsg(LL_VERBOSE, \"Power failure events: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L1 { logmsg(LL_VERBOSE, \"Voltage sags L1: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L2 { logmsg(LL_VERBOSE, \"Voltage sags L2: %lld\\n\", fsm->arg[0]);}\n\taction V_sags_L3 { logmsg(LL_VERBOSE, \"Voltage sags L3: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L1 { logmsg(LL_VERBOSE, \"Voltage swells L1: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L2 { logmsg(LL_VERBOSE, \"Voltage swells L2: %lld\\n\", fsm->arg[0]);}\n\taction V_swells_L3 { logmsg(LL_VERBOSE, \"Voltage swells L3: %lld\\n\", fsm->arg[0]);}\n\taction textmsgcodes { logmsg(LL_VERBOSE, \"Text message codes: %s\\n\", fsm->strarg[0]);}\n\taction textmsg { logmsg(LL_VERBOSE, \"Text message: %s\\n\", fsm->strarg[0]); }\n\taction dev_type { logmsg(LL_VERBOSE, \"Device %lld type: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\n\taction dev_id { logmsg(LL_VERBOSE, \"Device %lld ID: %s\\n\", fsm->arg[0], fsm->strarg[0]);}\n\taction dev_counter { logmsg(LL_VERBOSE, \"Device %lld counter at %lld: %f %s\\n\", fsm->arg[0], TST_to_time(fsm, 1), (double)fsm->arg[8] \/ (double)fsm->arg[9], fsm->strarg[0]); }\n\taction dev_valve { logmsg(LL_VERBOSE, \"Device %lld valve position: %lld\\n\", fsm->arg[0], fsm->arg[1]);}\t\n\taction dev_timeseries_head { logmsg(LL_VERBOSE, \"Device %lld timeseries, starting time %lld, status %lld, period %lld, values %lld:\\n\", fsm->arg[0], TST_to_time(fsm, 1), fsm->arg[7], fsm->arg[8], fsm->arg[9]); }\n\taction dev_timeseries_counter_head { logmsg(LL_VERBOSE, \"counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counter_cold_head { logmsg(LL_VERBOSE, \"cold counter values, unit %s\\n\", fsm->strarg[0]); } \n\taction dev_timeseries_counterval { logmsg(LL_VERBOSE, \"counter value: %f\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1]); }\n\taction gas_id_old { logmsg(LL_VERBOSE, \"Gas meter ID: %s\\n\", fsm->strarg[0]);}\n\taction gas_count_old { logmsg(LL_VERBOSE, \"Gas meter counter: %f %s\\n\", (double)fsm->arg[0] \/ (double)fsm->arg[1], fsm->strarg[0]); }\n\taction gas_valve_old { logmsg(LL_VERBOSE, \"Gas meter valve position: %lld\\n\", fsm->arg[0]);}\t\n\taction error {logmsg(LL_VERBOSE, \"Error while parsing\\n\"); fsm->parse_errors++ ; fhold ; fgoto rest_of_line; } \n\t\n\t\n\taction unknown { logmsg(LL_VERBOSE, \"Unknown: %s\\n\", fsm->strarg[0]); fsm->strargc = 0 ; fsm->buflen = 0; }\n\n\t# Helpers that collect arguments\n\t\n\tdigitpair = (digit @add_digit){2} >cleararg %addarg;\t# Parse and store two digits\n\tdst = ([SW] >cleararg @addchar);\t# Parse and store daylight saving time character\n\t\n\tmbusid = ( [1234] @add_digit ) >cleararg %addarg;\t# We can have 4 additional MBUS devices: gas meter, water meter, thermal meter, slave meter \n\n\n\t# Definitions of statements and parts of statements\n\n\tcrlf = '\\r\\n';\t# Lines are terminated by carriage return + line feed\n\t#crlf = [\\r\\n]{2};\t# Lines are terminated by carriage return + line feed, but we'll also match some converted line ends\n\t\n\tfixedpoint = fpval;\t\t\t# Fixed point value, stored as an integer value and an integer divider \n\t\n\tTST = digitpair{6} dst;\n\tTST_old = digitpair{6};\n\tunit = '*' ([^)]+ >addstr $str_append %str_term);\n\ttimeseries_unit = [^)]+ >addstr $str_append %str_term;\n\t\n\theaderstr = ([^\\r^\\n]+ >addstr $str_append %str_term);\n\t#msgstr = ([^)]* >addstr $str_append %str_term);\n\tmsgstr = hexstring;\n\tidstr = hexstring;\n\t\n\theader = '\/' headerstr crlf crlf @header @clearargs;\t\n\tend = '!' hexint? crlf @crc @clearargs;\t\t# Telegram end with optional CRC\n\t\n\tfixedpointval = '(' fixedpoint unit ')';\n\ttstval = '(' TST ')';\n\ttstval_old = '(' TST_old ')';\n\t\n\t# DSMR COSEM-objects\n\t\n\tP1_version = '1-3:0.2.8(' hexint ')' crlf @P1_version;\t\t# P1 version\n\ttimestamp = '0-0:1.0.0' tstval crlf @timestamp;\t\t\t# Telegram timestamp\n\t\n\tequipment_id = '0-0:96.1.1(' idstr ')' crlf @equipment_id;\t# Equipment ID\n\t\n\tE_in_t1 = '1-0:1.8.1' fixedpointval crlf @E_in_t1;\t# Electricity delivered to client in tariff 1\n\tE_in_t2 = '1-0:1.8.2' fixedpointval crlf @E_in_t2;\t# Electricity delivered to client in tariff 2\n\tE_out_t1 = '1-0:2.8.1' fixedpointval crlf @E_out_t1;\t# Electricity delivered by client in tariff 1\n\tE_out_t2 = '1-0:2.8.2' fixedpointval crlf @E_out_t2;\t# Electricity delivered by client in tariff 2\n\ttariff = '0-0:96.14.0(' uinteger ')' crlf @tariff;\t\t# TODO: can be non-integer, in theory?\n\tswitchpos = '0-0:' ('96.3.10' | '24.4.0') '(' uinteger ')' crlf @switchpos;\t# Switch position electricity (in\/out\/enabled), absent from DSMR>=4.0.7\n\n\tP_in = '1-0:1.7.0' fixedpointval crlf @P_in;\t# Actual power delivered to client\n\tP_out = '1-0:2.7.0' fixedpointval crlf @P_out;\t# Actual power delivered by client\n\tP_threshold = '0-0:17.0.0' fixedpointval crlf @P_threshold;\n\t\n\tpfail = '0-0:96.7.21(' uinteger ')' crlf @pfail; \n\tlongpfail = '0-0:96.7.9(' uinteger ')' crlf @longpfail; \n\t\n\tpfailevents = '1-0:99.97.0(' uinteger ')' @pfailevents @clearargs;\t# Power failure events\n\tpfailevent = tstval '(' uinteger unit ')' @pfailevent @clearargs;\t\t# Single power failure event\n\tpfaileventlog = pfailevents '(0-0:96.7.19)'? pfailevent* crlf;\t# Power failure event log, with zero or more events\n\t\n\tV_sags_L1 = '1-0:32.32.0(' uinteger ')' crlf @V_sags_L1;\n\tV_sags_L2 = '1-0:52.32.0(' uinteger ')' crlf @V_sags_L2;\n\tV_sags_L3 = '1-0:72.32.0(' uinteger ')' crlf @V_sags_L3;\n\t\n\tV_swells_L1 = '1-0:32.36.0(' uinteger ')' crlf @V_swells_L1;\t\n\tV_swells_L2 = '1-0:52.36.0(' uinteger ')' crlf @V_swells_L2;\n\tV_swells_L3 = '1-0:72.36.0(' uinteger ')' crlf @V_swells_L3;\n\t\n\ttextmsgcodes = '0-0:96.13.1(' msgstr ')' crlf @textmsgcodes;\n\ttextmsgcodes_empty = '0-0:96.13.1()' crlf;\n\ttextmsg = '0-0:96.13.0(' msgstr ')' crlf @textmsg;\n\ttextmsg_empty = '0-0:96.13.0()' crlf;\n\n\tV_L1 = '1-0:32.7.0' fixedpointval crlf @V_L1;\n\tV_L2 = '1-0:52.7.0' fixedpointval crlf @V_L2;\n\tV_L3 = '1-0:72.7.0' fixedpointval crlf @V_L3;\n\t\n\tI_L1 = '1-0:31.7.0(' uinteger unit ')' crlf @I_L1;\n\tI_L2 = '1-0:51.7.0(' uinteger unit ')' crlf @I_L2;\n\tI_L3 = '1-0:71.7.0(' uinteger unit ')' crlf @I_L3;\n\n\tI_threshold = '0-0:17.0.0(' uinteger unit ')' crlf @I_threshold;\n\t\n\tP_in_L1 = '1-0:21.7.0' fixedpointval crlf @P_in_L1;\n\tP_in_L2 = '1-0:41.7.0' fixedpointval crlf @P_in_L2;\n\tP_in_L3 = '1-0:61.7.0' fixedpointval crlf @P_in_L3;\n\t\n\tP_out_L1 = '1-0:22.7.0' fixedpointval crlf @P_out_L1;\n\tP_out_L2 = '1-0:42.7.0' fixedpointval crlf @P_out_L2;\n\tP_out_L3 = '1-0:62.7.0' fixedpointval crlf @P_out_L3;\n\t\n\tdev_type = '0-' mbusid ':24.1.0(' uinteger ')' crlf @dev_type;\n\tdev_id = '0-' mbusid ':96.1.0(' idstr ')' crlf @dev_id;\n\tdev_counter = '0-' mbusid ':24.2.1' tstval fixedpointval crlf @dev_counter;\t\n\tdev_valve = '0-' mbusid ':24.4.0(' uinteger ')' crlf @dev_valve;\t# Valve position (on\/off\/released), absent from DSMR>=4.0.7\n\t\n\t# This describes the rather horrible \"profile generic dataset\" representation used in DSMR 3.x\t\n\tdev_timeseries_head = '0-' mbusid ':24.3.0' tstval_old '(' uinteger ')' '(' uinteger ')' '(' uinteger ')' @dev_timeseries_head @clearargs;\n\tdev_timeseries_counter_head = '(0-' digit+ ':24.2.1)(' timeseries_unit ')' @dev_timeseries_counter_head @clearargs;\n\tdev_timeseries_counter_cold_head = '(0-' digit+ ':24.3.1)(' timeseries_unit ')' @dev_timeseries_counter_cold_head @clearargs;\n\tdev_timeseries_counterval = '(' fixedpoint ')' @dev_timeseries_counterval @clearargs;\n\tdev_counter_timeseries = dev_timeseries_head dev_timeseries_counter_head dev_timeseries_counterval+ crlf;\n\tdev_counter_cold_timeseries = dev_timeseries_head dev_timeseries_counter_cold_head dev_timeseries_counterval+ crlf;\n\t\n\tgas_id_old = '7-0:0.0.0(' idstr ')' crlf @gas_id_old;\n\tgas_count_old = '7-0:23.1.0' tstval fixedpointval crlf @gas_count_old;\n\t#gas_count_Tcomp_old = '7-0:23.2.0' tstval fixedpointval crlf @gas_count_Tcomp_old;\n\t#gas_valve_old = '7-0:24.4.0(' uinteger ')' crlf @gas_valve_old;\t\n\t#heat_id_old = '5-0:0.0.0(' idstr ')' crlf @heat_id_old;\n\t#cold_id_old = '6-0:0.0.0(' idstr ')' crlf @cold_id_old;\n\t#water_id_old = '8-0:0.0.0(' idstr ')' crlf @water_id_old;\n\t#heat_count_old = '5-0:1.0.0' tstval fixedpointval crlf @heat_count_old;\n\t#cold_count_old = '6-0:1.0.0' tstval fixedpointval crlf @cold_count_old;\n\t#water_count_old = '8-0:1.0.0' tstval fixedpointval crlf @water_count_old;\n\t\n\t# P1 Telegram components\n\t\n\tmetadata_object = P1_version | timestamp;\n\temeter_object = equipment_id | tariff | switchpos | E_in_t1 | E_in_t2 | E_out_t1 | E_out_t2;\n\tpower_object = P_in | P_out | P_in_L1 | P_out_L1 | P_in_L2 | P_out_L2 | P_in_L3 | P_out_L3 | P_threshold;\n\tcurrent_object = I_L1 | I_L2 | I_L3 | I_threshold;\n\tvoltage_object = V_L1 | V_L2 | V_L3;\n\tpower_quality_object = pfail | longpfail | pfaileventlog | V_sags_L1 | V_swells_L1 | V_sags_L2 | V_swells_L2 | V_sags_L3 | V_swells_L3;\n\tmbusdev_object = dev_type | dev_id | dev_counter | dev_valve | dev_counter_timeseries | dev_counter_cold_timeseries;\n\tslavedev_legacy_object = gas_id_old | gas_count_old;\n\tmessage_object = textmsgcodes | textmsg | textmsgcodes_empty | textmsg_empty;\n\t\n\tobject = \tmetadata_object | emeter_object | power_object | current_object | voltage_object | power_quality_object |\n\t\t\t\tmessage_object | mbusdev_object | slavedev_legacy_object;\n\t\n\tline = object $err(error) @clearargs;\t# Clear argument stacks at the end of each line, handle parsing errors\n\t\n\ttelegram = header? line* end;\t# Make header optional, so we can recover from errors in the middle of a telegram\n\t\n\tmain := telegram* $err(error);\t\t# Parse zero or more telegrams\n\t\n}%%\n\n%% write data;\n\n\nvoid parser_init( struct parser *fsm )\n{\n\tint arg;\n\t\n\tfsm->buflen = 0;\n\tfsm->argc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->arg[arg] = 0;\n\tfsm->multiplier = 1;\n\tfsm->bitcount = 0;\n\tfsm->strargc = 0;\n\tfor (arg = 0 ; arg < PARSER_MAXARGS ; arg++)\n\t\tfsm->strarg[arg] = NULL;\n\tfsm->parse_errors = 0;\n\t\n\t%% write init;\n}\n\nvoid parser_execute(struct parser *fsm, const char *data, int len, int eofflag)\n{\n\tconst char *p = data;\n\tconst char *pe = data + len;\n\tconst char *eof = 0;\n\n\tif (eofflag)\n\t\teof = pe;\n\t\n\t%% write exec;\n\t\n\tfsm->pe = pe;\n}\n\nint parser_finish(struct parser *fsm)\n{\n\tif ( fsm->cs == parser_error )\t\t\t\/\/ Machine failed before matching\n\t\treturn -1;\n\tif ( fsm->cs >= parser_first_final )\t\/\/ Final state reached\n\t\treturn 1;\n\treturn 0;\t\t\t\t\t\t\t\t\/\/ Final state not reached\n}\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"9b9f51844d9012b87a01ebeac9fb3b1b207e3226","subject":"* fix a bug (eval_appmacro)","message":"* fix a bug (eval_appmacro)\n","repos":"nineties\/amber","old_file":"rlc1\/eval.rl","new_file":"rlc1\/eval.rl","new_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: eval.rl 2010-05-26 01:10:04 nineties $\n %);\n\ninclude(stddef,code);\nexport(init_evaluator, assign, deref, check_arity, eval_sexp);\n\nsymbol_map: NULL; (% (symbol name, scope id) -> symbol object %);\n\nscopeid: 0;\nscopeid_stack: NULL;\n\n(% p0: (symbol name, scope id) %);\nsymbol_hash: (p0) {\n return strhash(p0[0])*3 + p0[1];\n};\n\nsymbol_equal: (p0, p1) {\n if (p0[1] != p1[1]) { return FALSE; };\n return streq(p0[0], p1[0]);\n};\n\nscope_push: () {\n scopeid = scopeid + 1;\n vec_pushback(scopeid_stack, scopeid);\n};\n\nscope_pop: () {\n vec_popback(scopeid_stack);\n};\n\n\n(% p0: symbol name, p1: value %);\nassign: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(symbol_map, mktup2(p0, x0), p1);\n};\n\n(% p0: symbol object %);\nderef: (p0) {\n allocate(4);\n x0 = vec_size(scopeid_stack)-1;\n x3 = sym_name(p0);\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(symbol_map, mktup2(x3, x1));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return p0;\n};\n\ncheck_arity: (p0, p1, p2) {\n if (length(p0) != p1) {\n fputs(stderr, \"ERROR '\");\n fputs(stderr, p2);\n fputs(stderr, \"': required \");\n fputi(stderr, p1);\n fputs(stderr, \" arguments\");\n exit(1);\n }\n};\n\neval_args: (p0) {\n if (p0 == nil_sym) { return nil_sym; };\n return mkcons(eval_sexp(car(p0)), eval_args(cdr(p0)));\n};\n\neval_cons: (p0) {\n allocate(2);\n x0 = car(p0);\n if (sym_p(x0) == nil_sym) { goto &eval_cons_error; };\n x1 = eval_sexp(x0);\n if (x1 == var_sym) { return eval_var(cdr(p0)); };\n if (x1 == set_sym) { return eval_set(cdr(p0)); };\n if (x1 == quote_sym) { return eval_quote(cdr(p0)); };\n if (x1 == if_sym) { return eval_if(cdr(p0)); };\n if (x1 == cond_sym) { return eval_cond(cdr(p0)); };\n if (x1 == while_sym) { return eval_while(cdr(p0)); };\n if (x1 == do_sym) { return eval_do(cdr(p0)); };\n if (x1 == lambda_sym) { return eval_lambda(cdr(p0)); };\n if (x1 == macro_sym) { return eval_macro(cdr(p0)); };\n if (prim_p(x1) != nil_sym) { return (prim_funptr(x1))(eval_args(cdr(p0))); };\n if (lambda_p(x1) != nil_sym) { return eval_applambda(x1, eval_args(cdr(p0))); };\n if (macro_p(x1) != nil_sym) { return eval_appmacro(x1, cdr(p0)); };\nlabel eval_cons_error;\n fputs(stderr, \"ERROR: invalid application of '\");\n pp_sexp(stderr, car(p0));\n fputs(stderr, \"'\\n\");\n exit(1);\n};\n\n(% (var ) %);\neval_var: (p0) {\n allocate(2);\n check_arity(p0, 2, \"var\");\n x0 = car(p0);\n x1 = eval_sexp(cadr(p0));\n sym_set(x0, x1);\n assign(sym_name(x0), x0);\n return x0;\n};\n\neval_set: (p0) {\n allocate(2);\n check_arity(p0, 2, \"set\");\n x0 = deref(car(p0));\n x1 = eval_sexp(cadr(p0));\n if (sym_value(x0) == NULL) {\n fputs(stderr, \"ERROR 'eval_set': undefined variable '\");\n fputs(stderr, sym_name(x0));\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n sym_set(x0, x1);\n return x0;\n};\n\neval_quote: (p0) {\n check_arity(p0, 1, \"quote\");\n return car(p0);\n};\n\n(% p0 : (cond ifthen ifelse) %);\neval_if: (p0) {\n allocate(2);\n check_arity(p0, 3, \"if\");\n scope_push();\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n if (x0 != nil_sym) {\n x1 = eval_sexp(car(p0));\n scope_pop();\n return x1;\n };\n x1 = eval_sexp(cadr(p0));\n scope_pop();\n return x1;\n};\n\neval_cond: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = car(p0);\n check_arity(x0, 2, \"cond\");\n if (eval_sexp(car(x0)) != nil_sym) {\n scope_pop();\n return eval_sexp(cadr(x0));\n };\n p0 = cdr(p0);\n };\n fputs(stderr, \"ERROR 'eval_cond': any condition was not met\\n\");\n exit(1);\n};\n\n(% p0: (cond body) %);\neval_while: (p0) {\n allocate(3);\n check_arity(p0, 2, \"while\");\n scope_push();\n x0 = car(p0); (% condition %);\n x1 = cadr(p0); (% body %);\n x2 = eval_sexp(x0);\n while (x2 != nil_sym) {\n eval_sexp(x1);\n x2 = eval_sexp(x0);\n };\n scope_pop();\n if (x2 != nil_sym) {\n fputs(stderr, \"ERROR 'while': conditional expression could not evaluated to true\/false\\n\");\n exit(1);\n };\n return nil_sym;\n};\n\neval_do: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n };\n scope_pop();\n return x0;\n};\n\n(% (lambda (params) body) %);\neval_lambda: (p0) {\n allocate(2);\n check_arity(p0, 2, \"lambda\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mklambda(x0, x1);\n};\n\n(% (macro (params) body) %);\neval_macro: (p0) {\n allocate(2);\n check_arity(p0, 2, \"macro\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mkmacro(x0, x1);\n};\n\n(% p0: lambda, p1: params %);\neval_applambda: (p0, p1) {\n allocate(3);\n x0 = lambda_params(p0);\n if (length(x0) != length(p1)) {\n fputs(stderr, \"ERROR: invalid number of argument (must be \");\n fputi(stderr, length(x0));\n fputi(stderr, \")\\n\");\n exit(1);\n };\n p1 = eval_args(p1);\n\n scope_push();\n while (x0 != nil_sym) {\n x1 = mksym(sym_name(car(x0)));\n sym_set(x1, car(p1));\n assign(sym_name(x1), x1);\n x0 = cdr(x0);\n p1 = cdr(p1);\n };\n x2 = eval_sexp(lambda_body(p0));\n scope_pop();\n return x2;\n};\n\n(% p0: macro, p1: params %);\neval_appmacro: (p0, p1) {\n allocate(3);\n x0 = macro_params(p0);\n if (length(x0) != length(p1)) {\n fputs(stderr, \"ERROR: invalid number of argument (must be \");\n fputi(stderr, length(x0));\n fputi(stderr, \")\\n\");\n exit(1);\n };\n p1 = eval_args(p1);\n\n scope_push();\n while (x0 != nil_sym) {\n x1 = mksym(sym_name(car(x0)));\n sym_set(x1, car(p1));\n assign(sym_name(x1), x1);\n x0 = cdr(x0);\n p1 = cdr(p1);\n };\n x2 = eval_sexp(macro_body(p0));\n scope_pop();\n return eval_sexp(x2);\n};\n\neval_sexp: (p0) {\n allocate(2);\n x0 = p0[0]; (% node code %);\n if (x0 == NODE_CONS) { return eval_cons(p0); };\n if (x0 == NODE_SYMBOL) {\n x1 = deref(p0);\n if (sym_value(x1) != NULL) {\n return eval_sexp(sym_value(x1));\n };\n return x1;\n };\n return p0;\n};\n\ninit_evaluator: () {\n symbol_map = mkmap(&symbol_hash, &symbol_equal, 100);\n scopeid_stack = mkvec(0);\n scope_push(); (% global scope %);\n};\n\n","old_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: eval.rl 2010-05-25 22:10:05 nineties $\n %);\n\ninclude(stddef,code);\nexport(init_evaluator, assign, deref, check_arity, eval_sexp);\n\nsymbol_map: NULL; (% (symbol name, scope id) -> symbol object %);\n\nscopeid: 0;\nscopeid_stack: NULL;\n\n(% p0: (symbol name, scope id) %);\nsymbol_hash: (p0) {\n return strhash(p0[0])*3 + p0[1];\n};\n\nsymbol_equal: (p0, p1) {\n if (p0[1] != p1[1]) { return FALSE; };\n return streq(p0[0], p1[0]);\n};\n\nscope_push: () {\n scopeid = scopeid + 1;\n vec_pushback(scopeid_stack, scopeid);\n};\n\nscope_pop: () {\n vec_popback(scopeid_stack);\n};\n\n\n(% p0: symbol name, p1: value %);\nassign: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(symbol_map, mktup2(p0, x0), p1);\n};\n\n(% p0: symbol object %);\nderef: (p0) {\n allocate(4);\n x0 = vec_size(scopeid_stack)-1;\n x3 = sym_name(p0);\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(symbol_map, mktup2(x3, x1));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return p0;\n};\n\ncheck_arity: (p0, p1, p2) {\n if (length(p0) != p1) {\n fputs(stderr, \"ERROR '\");\n fputs(stderr, p2);\n fputs(stderr, \"': required \");\n fputi(stderr, p1);\n fputs(stderr, \" arguments\");\n exit(1);\n }\n};\n\neval_args: (p0) {\n if (p0 == nil_sym) { return nil_sym; };\n return mkcons(eval_sexp(car(p0)), eval_args(cdr(p0)));\n};\n\neval_cons: (p0) {\n allocate(2);\n x0 = car(p0);\n if (sym_p(x0) == nil_sym) { goto &eval_cons_error; };\n x1 = eval_sexp(x0);\n if (x1 == var_sym) { return eval_var(cdr(p0)); };\n if (x1 == set_sym) { return eval_set(cdr(p0)); };\n if (x1 == quote_sym) { return eval_quote(cdr(p0)); };\n if (x1 == if_sym) { return eval_if(cdr(p0)); };\n if (x1 == cond_sym) { return eval_cond(cdr(p0)); };\n if (x1 == while_sym) { return eval_while(cdr(p0)); };\n if (x1 == do_sym) { return eval_do(cdr(p0)); };\n if (x1 == lambda_sym) { return eval_lambda(cdr(p0)); };\n if (x1 == macro_sym) { return eval_macro(cdr(p0)); };\n if (prim_p(x1) != nil_sym) { return (prim_funptr(x1))(eval_args(cdr(p0))); };\n if (lambda_p(x1) != nil_sym) { return eval_applambda(x1, eval_args(cdr(p0))); };\n if (macro_p(x1) != nil_sym) { return eval_appmacro(x1, cdr(p0)); };\nlabel eval_cons_error;\n fputs(stderr, \"ERROR: invalid application of '\");\n pp_sexp(stderr, car(p0));\n fputs(stderr, \"'\\n\");\n exit(1);\n};\n\n(% (var ) %);\neval_var: (p0) {\n allocate(2);\n check_arity(p0, 2, \"var\");\n x0 = car(p0);\n x1 = eval_sexp(cadr(p0));\n sym_set(x0, x1);\n assign(sym_name(x0), x0);\n return x0;\n};\n\neval_set: (p0) {\n allocate(2);\n check_arity(p0, 2, \"set\");\n x0 = deref(car(p0));\n x1 = eval_sexp(cadr(p0));\n if (sym_value(x0) == NULL) {\n fputs(stderr, \"ERROR 'eval_set': undefined variable '\");\n fputs(stderr, sym_name(x0));\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n sym_set(x0, x1);\n return x0;\n};\n\neval_quote: (p0) {\n check_arity(p0, 1, \"quote\");\n return car(p0);\n};\n\n(% p0 : (cond ifthen ifelse) %);\neval_if: (p0) {\n allocate(2);\n check_arity(p0, 3, \"if\");\n scope_push();\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n if (x0 != nil_sym) {\n x1 = eval_sexp(car(p0));\n scope_pop();\n return x1;\n };\n x1 = eval_sexp(cadr(p0));\n scope_pop();\n return x1;\n};\n\neval_cond: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = car(p0);\n check_arity(x0, 2, \"cond\");\n if (eval_sexp(car(x0)) != nil_sym) {\n scope_pop();\n return eval_sexp(cadr(x0));\n };\n p0 = cdr(p0);\n };\n fputs(stderr, \"ERROR 'eval_cond': any condition was not met\\n\");\n exit(1);\n};\n\n(% p0: (cond body) %);\neval_while: (p0) {\n allocate(3);\n check_arity(p0, 2, \"while\");\n scope_push();\n x0 = car(p0); (% condition %);\n x1 = cadr(p0); (% body %);\n x2 = eval_sexp(x0);\n while (x2 != nil_sym) {\n eval_sexp(x1);\n x2 = eval_sexp(x0);\n };\n scope_pop();\n if (x2 != nil_sym) {\n fputs(stderr, \"ERROR 'while': conditional expression could not evaluated to true\/false\\n\");\n exit(1);\n };\n return nil_sym;\n};\n\neval_do: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n };\n scope_pop();\n return x0;\n};\n\n(% (lambda (params) body) %);\neval_lambda: (p0) {\n allocate(2);\n check_arity(p0, 2, \"lambda\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mklambda(x0, x1);\n};\n\n(% (macro (params) body) %);\neval_macro: (p0) {\n allocate(2);\n check_arity(p0, 2, \"macro\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mkmacro(x0, x1);\n};\n\n(% p0: lambda, p1: params %);\neval_applambda: (p0, p1) {\n allocate(3);\n x0 = lambda_params(p0);\n if (length(x0) != length(p1)) {\n fputs(stderr, \"ERROR: invalid number of argument (must be \");\n fputi(stderr, length(x0));\n fputi(stderr, \")\\n\");\n exit(1);\n };\n p1 = eval_args(p1);\n\n scope_push();\n while (x0 != nil_sym) {\n x1 = mksym(sym_name(car(x0)));\n sym_set(x1, car(p1));\n assign(sym_name(x1), x1);\n x0 = cdr(x0);\n p1 = cdr(p1);\n };\n x2 = eval_sexp(lambda_body(p0));\n scope_pop();\n return x2;\n};\n\n(% p0: macro, p1: params %);\neval_appmacro: (p0, p1) {\n allocate(3);\n x0 = macro_params(p0);\n if (length(x0) != length(p1)) {\n fputs(stderr, \"ERROR: invalid number of argument (must be \");\n fputi(stderr, length(x0));\n fputi(stderr, \")\\n\");\n exit(1);\n };\n p1 = eval_args(p1);\n\n scope_push();\n while (x0 != nil_sym) {\n x1 = mksym(sym_name(car(x0)));\n sym_set(x1, car(p1));\n assign(sym_name(x1), x1);\n x0 = cdr(x0);\n p1 = cdr(p1);\n };\n x2 = eval_sexp(macro_body(p0));\n scope_pop();\n return x2;\n};\n\neval_sexp: (p0) {\n allocate(2);\n x0 = p0[0]; (% node code %);\n if (x0 == NODE_CONS) { return eval_cons(p0); };\n if (x0 == NODE_SYMBOL) {\n x1 = deref(p0);\n if (sym_value(x1) != NULL) {\n return eval_sexp(sym_value(x1));\n };\n return x1;\n };\n return p0;\n};\n\ninit_evaluator: () {\n symbol_map = mkmap(&symbol_hash, &symbol_equal, 100);\n scopeid_stack = mkvec(0);\n scope_push(); (% global scope %);\n};\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e7614e21bad530b8e91c6cdf10d41fafba2f6174","subject":"Raise exceptions on parse errors in JavaParser","message":"Raise exceptions on parse errors in JavaParser","repos":"elabs\/stompede,elabs\/stomp_parser,elabs\/stomp_parser,elabs\/stompede","old_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.RubyNumeric;\nimport org.jruby.RubyException;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n \/*mark_message_size = 0;*\/\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n IRubyObject content_length = mark_message.callMethod(context, \"content_length\");\n\n if ( ! content_length.isNil()) {\n mark_content_length = RubyNumeric.num2int(content_length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n mark_message.callMethod(context, \"write_body\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action consume_null {\n ((mark_content_length != -1) && ((p - mark) < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || ((p - mark) < mark_content_length))\n }\n\n action check_message_size {\n \/*mark_message_size += 1;*\/\n \/*if (mark_message_size > max_message_size) {*\/\n \/* rb_raise(eMessageSizeExceeded, \"\");*\/\n \/*}*\/\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n IRubyObject args[] = { RubyString.newString(context.runtime, data), RubyFixnum.newFixnum(context.runtime, (long) p) };\n IRubyObject error = context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(context, \"build_parse_error\", args);\n throw new RaiseException((RubyException) error);\n }\n\n return context.nil;\n }\n}\n","old_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.RubyNumeric;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n \/*mark_message_size = 0;*\/\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n IRubyObject content_length = mark_message.callMethod(context, \"content_length\");\n\n if ( ! content_length.isNil()) {\n mark_content_length = RubyNumeric.num2int(content_length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n mark_message.callMethod(context, \"write_body\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action consume_null {\n ((mark_content_length != -1) && ((p - mark) < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || ((p - mark) < mark_content_length))\n }\n\n action check_message_size {\n \/*mark_message_size += 1;*\/\n \/*if (mark_message_size > max_message_size) {*\/\n \/* rb_raise(eMessageSizeExceeded, \"\");*\/\n \/*}*\/\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n \/\/ RaiseException error = context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(\"build_parse_error\");\n \/\/ throw error;\n }\n\n return context.nil;\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"143bdecfe03706a5cfd13389349f20acfe4e5b1b","subject":"rewrite set machines","message":"rewrite set machines\n","repos":"OpenBEL\/bel_parser,nbargnesi\/bel-parser,OpenBEL\/bel_parser,OpenBEL\/bel_parser,nbargnesi\/bel-parser,nbargnesi\/bel-parser","old_file":"lib\/bel_parser\/parsers\/bel_script\/set.rl","new_file":"lib\/bel_parser\/parsers\/bel_script\/set.rl","new_contents":"# begin: ragel\n=begin\n%%{\n machine bel;\n\n include 'common.rl';\n include 'identifier.rl';\n include 'string.rl';\n include 'list.rl';\n\n action add_key {\n $stderr.puts \"SET add_key\"\n key = @buffers.delete(:ident)\n @buffers[:set_name] = key\n }\n\n action add_ident_value {\n $stderr.puts \"SET add_ident_value\"\n ident = @buffers.delete(:ident)\n @buffers[:set_value] = ident\n }\n\n action add_string_value {\n $stderr.puts \"SET add_string_value\"\n string = @buffers.delete(:string)\n @buffers[:set_value] = string\n }\n\n action add_list_value {\n $stderr.puts \"SET add_list_value\"\n list = @buffers.delete(:list)\n @buffers[:set_value] = list\n }\n\n action set_end {\n $stderr.puts \"SET set_end\"\n $stderr.puts @buffers.inspect\n name = @buffers.delete(:set_name)\n value = @buffers.delete(:set_value)\n set = set(name, value, complete: name.complete && value.complete)\n @buffers[:set] = set\n }\n\n action yield_set {\n $stderr.puts \"SET yield_set\"\n yield @buffers[:set]\n }\n\n SET_KW =\n [sS]\n [eE]\n [tT]\n ;\n\n key =\n an_ident\n %add_key\n ;\n\n ident_value =\n an_ident\n %add_ident_value\n ;\n\n string_value =\n a_string\n %add_string_value\n ;\n\n list_value =\n a_list\n %add_list_value\n ;\n\n value =\n ident_value |\n string_value |\n list_value\n ;\n\n set_node :=\n SET_KW\n %{ $stderr.puts '% SET_KW' }\n SP+\n an_ident\n %add_key\n SP+\n EQL\n %{ $stderr.puts '% EQL' }\n SP+\n value\n %set_end\n %yield_set\n ;\n}%%\n=end\n# end: ragel\n\nrequire_relative '..\/ast\/node'\nrequire_relative '..\/mixin\/buffer'\nrequire_relative '..\/nonblocking_io_wrapper'\n\nmodule BELParser\n module Parsers\n module BELScript\n module Set\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def parse(content)\n return nil unless content\n\n Parser.new(content).each do |obj|\n yield obj\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n include BELParser::Parsers::Buffer\n include BELParser::Parsers::AST::Sexp\n\n def initialize(content)\n @content = content\n $stderr.puts \"\\n---\\ncontent: '\" + @content + \"'\"\n # begin: ragel\n %% write data;\n # end: ragel\n end\n\n def each\n @buffers = {}\n @incomplete = {}\n @accum_set = false\n @have_set = false\n @have_name = false\n @have_value = false\n data = @content.unpack('C*')\n p = 0\n pe = data.length\n eof = data.length\n\n # begin: ragel\n %% write init;\n %% write exec;\n # end: ragel\n end\n end\n end\n end\n end\nend\n\nif __FILE__ == $0\n $stdin.each_line do |line|\n BELParser::Parsers::BELScript::Set.parse(line) { |obj|\n puts obj.inspect\n }\n end\nend\n\n# vim: ft=ruby ts=2 sw=2:\n# encoding: utf-8\n","old_contents":"# begin: ragel\n=begin\n%%{\n machine bel;\n\n include 'identifier.rl';\n include 'string.rl';\n include 'list.rl';\n\n action start_set_keyword {\n #$stderr.puts 'start_set_keyword'\n @incomplete[:set_keyword] = []\n }\n\n action accum_set_keyword {\n #$stderr.puts 'accum_set_keyword \"' + fc.chr + '\"'\n @incomplete[:set_keyword] << fc\n @accum_set = true\n }\n\n action start_value {\n @incomplete[:set_value] = []\n }\n\n action accum_value {\n @incomplete[:set_value] << fc\n }\n\n action eof_value {\n $stderr.puts 'handle eof - what is incomplete?'\n $stderr.puts @incomplete.inspect\n }\n\n action end_set_keyword {\n #$stderr.puts 'end_set_keyword'\n # have we accumulated part of the set keyword?\n unless @accum_set\n fbreak;\n end\n buf = @incomplete.delete(:set_keyword)\n keyword = ord_to_str(buf)\n if keyword == 'SET'\n @have_set = true\n end\n }\n\n action eof_set_keyword {\n #$stderr.puts 'eof_set_keyword'\n }\n\n action eof_set {\n #$stderr.puts 'eof_set'\n }\n\n action set_name_end {\n #$stderr.puts \"set_name_end\"\n name = @buffers.delete(:ident)\n unless ident.nil?\n @have_name = true\n @buffers[:set_name] = name\n end\n }\n\n action set_value_end {\n $stderr.puts 'set_value_end'\n $stderr.puts @buffers.inspect\n if @buffers.key?(:ident)\n @have_value = true\n ident = @buffers.delete(:ident)\n @buffers[:set_value] = ident\n elsif @buffers.key?(:list)\n $stderr.puts \"I got a list!\"\n @have_value = true\n list = @buffers.delete(:list)\n @buffers[:set_value] = list\n elsif @buffers.key?(:string)\n @have_value = true\n string = @buffers.delete(:string)\n @buffers[:set_value] = string\n end\n }\n\n action set_end {\n #$stderr.puts \"set_end\"\n children = []\n if @have_name\n children << @buffers.delete(:set_name)\n end\n if @have_value\n children << @buffers.delete(:set_value)\n end\n completed = @have_set && @have_name && @have_value\n ast_node = set(*children, complete: completed)\n @buffers[:set] = ast_node\n yield @buffers[:set]\n }\n\n SET_KW = [sS][eE][tT];\n\n action set_keyword {\n @buffers[:set] = set()\n }\n\n action name {\n @buffers[:set] = @buffers[:set] << name(@buffers[:ident])\n }\n\n action string_value {\n @buffers[:set] = @buffers[:set] << value(@buffers[:string])\n }\n\n action ident_value {\n @buffers[:set] = @buffers[:set] << value(@buffers[:ident])\n }\n\n action list_value {\n @buffers[:set] = @buffers[:set] << value(@buffers[:list])\n }\n\n action yield_set {\n yield @buffers[:set]\n }\n\n SET =\n [sS]\n [eE]?\n [tT]?\n ;\n\n set =\n (SET | alnum+)\n >start_set_keyword\n $accum_set_keyword\n %end_set_keyword\n $eof(eof_set_keyword)\n ;\n\n name =\n an_ident\n %set_name_end\n ;\n\n value =\n (\n a_string |\n a_list |\n an_ident\n )\n >start_value\n $accum_value\n $eof(eof_value)\n %set_value_end\n ;\n\n set_ast :=\n (\n set? SP+ name? SP+ EQL? SP+ value?\n )\n NL?\n $set_end\n $eof(eof_set)\n ;\n}%%\n=end\n# end: ragel\n\nrequire_relative '..\/ast\/node'\nrequire_relative '..\/mixin\/buffer'\nrequire_relative '..\/nonblocking_io_wrapper'\n\nmodule BELParser\n module Parsers\n module BELScript\n module Set\n\n class << self\n\n MAX_LENGTH = 1024 * 128 # 128K\n\n def parse(content)\n return nil unless content\n\n Parser.new(content).each do |obj|\n yield obj\n end\n end\n end\n\n private\n\n class Parser\n include Enumerable\n include BELParser::Parsers::Buffer\n include BELParser::Parsers::AST::Sexp\n\n def initialize(content)\n @content = content\n # begin: ragel\n %% write data;\n # end: ragel\n end\n\n def each\n @buffers = {}\n @incomplete = {}\n @accum_set = false\n @have_set = false\n @have_name = false\n @have_value = false\n data = @content.unpack('C*')\n p = 0\n pe = data.length\n eof = data.length\n\n # begin: ragel\n %% write init;\n %% write exec;\n # end: ragel\n end\n end\n end\n end\n end\nend\n\nif __FILE__ == $0\n $stdin.each_line do |line|\n BELParser::Parsers::BELScript::Set.parse(line) { |obj|\n puts obj.inspect\n }\n end\nend\n\n# vim: ft=ruby ts=2 sw=2:\n# encoding: utf-8\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"45f82d53693060c347805e00111327e3fd9595db","subject":"SSA: Don't call the parser actions for tags no renderer supports ATM.","message":"SSA: Don't call the parser actions for tags no renderer supports ATM.\n\n","repos":"MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian","old_file":"Subtitles\/SubParsing.m.rl","new_file":"Subtitles\/SubParsing.m.rl","new_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = STUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = STUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum\n\t\t\t\t\t\t\t|\"fry\" floatnum\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","old_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = STUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = STUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum %bluredge\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum %frx\n\t\t\t\t\t\t\t|\"fry\" floatnum %fry\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"79591d65db6aa99cac01315899c4a41d4086fbd0","subject":"Reformatted state machine specification.","message":"Reformatted state machine specification.\n\nIn particular:\n\n- fit specifications to fit within 80 columns\n- organized blocks into rough categories\n","repos":"NUBIC\/castanet","old_file":"lib\/castanet\/response.rl","new_file":"lib\/castanet\/response.rl","new_contents":"require 'castanet'\n\n%%{\n machine parser;\n\n # Actions\n # -------\n\n action buffer { buffer << fc }\n action saveUsername { r.username = buffer; buffer = '' }\n action saveFailureCode { r.failure_code = buffer; buffer = '' }\n action saveFailureReason { r.failure_reason = buffer.strip; buffer = '' }\n action setAuthenticated { r.authenticated = true; eof = -1 }\n\n # XML definitions\n # ---------------\n\n quote = '\"' | \"'\";\n xmlContent = any -- [<&];\n\n # Leaf tags\n # ---------\n\n code = ( ( upper | '_' ) @buffer )+ %saveFailureCode;\n reason = ( xmlContent @buffer )+ %saveFailureReason;\n user = \"\" ( xmlContent @buffer )+ %saveUsername \"<\/cas:user>\";\n\n # Non-leaf tags\n # -------------\n\n serviceResponseStart = \"\";\n serviceResponseEnd = \"<\/cas:serviceResponse>\";\n\n authenticationFailureStart = \"\";\n authenticationFailureEnd = \"<\/cas:authenticationFailure>\";\n\n authenticationSuccessStart = \"\";\n authenticationSuccessEnd = \"<\/cas:authenticationSuccess>\";\n\n\n # Top-level elements\n # ------------------\n\n ok_cas_st = ( serviceResponseStart\n space*\n authenticationSuccessStart\n space*\n user\n space*\n authenticationSuccessEnd\n space*\n serviceResponseEnd ) @setAuthenticated;\n\n failed_cas_st = ( serviceResponseStart\n space*\n authenticationFailureStart\n reason\n authenticationFailureEnd\n space*\n serviceResponseEnd );\n\n cas_st = ok_cas_st | failed_cas_st;\n\n main := cas_st;\n}%%\n\nmodule Castanet\n class Response\n ##\n # Whether or not this response passed CAS authentication.\n #\n # @return [Boolean]\n attr_accessor :authenticated\n\n alias_method :authenticated?, :authenticated\n\n ##\n # The failure code returned on authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_code\n\n ##\n # The reason given by the CAS server for authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_reason\n\n ##\n # The name of the owner of the validated service or proxy ticket.\n #\n # This information is only present on authentication success.\n #\n # @return [String, nil]\n attr_accessor :username\n\n ##\n # Generates a {Response} object from a CAS response.\n #\n # @param [String] response the CAS response\n # @return [Response]\n def self.from_cas(response)\n data = response.strip.unpack('c*')\n buffer = ''\n eof = nil\n\n %% write init;\n\n new.tap do |r|\n %% write exec;\n end\n end\n\n def initialize\n self.authenticated = false\n end\n\n %% write data;\n end\nend\n","old_contents":"require 'castanet'\n\n%%{\n machine parser;\n\n action buffer { buffer << data.slice(p, 1).pack('c') }\n action saveUsername { r.username = buffer; buffer = '' }\n action saveFailureCode { r.failure_code = buffer; buffer = '' }\n action saveFailureReason { r.failure_reason = buffer.strip; buffer = '' }\n\n quote = '\"' | \"'\";\n xmlContent = any -- [<&];\n\n serviceResponseStart = \"\";\n\n code = ( ( upper | '_' ) @buffer )+ %saveFailureCode;\n reason = ( xmlContent @buffer )+ %saveFailureReason;\n\n authenticationFailureStart = \"\";\n authenticationSuccessStart = \"\";\n\n user = \"\" ( xmlContent @buffer )+ %saveUsername \"<\/cas:user>\";\n\n authenticationFailureEnd = \"<\/cas:authenticationFailure>\";\n authenticationSuccessEnd = \"<\/cas:authenticationSuccess>\";\n serviceResponseEnd = \"<\/cas:serviceResponse>\";\n\n action setAuthenticated { r.authenticated = true; eof = -1 }\n\n ok_cas_st = ( serviceResponseStart space* authenticationSuccessStart space* user space* authenticationSuccessEnd space* serviceResponseEnd ) @setAuthenticated;\n failed_cas_st = ( serviceResponseStart space* authenticationFailureStart reason authenticationFailureEnd space* serviceResponseEnd );\n cas_st = ok_cas_st | failed_cas_st;\n\n main := cas_st;\n}%%\n\nmodule Castanet\n class Response\n ##\n # Whether or not this response passed CAS authentication.\n #\n # @return [Boolean]\n attr_accessor :authenticated\n\n alias_method :authenticated?, :authenticated\n\n ##\n # The failure code returned on authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_code\n\n ##\n # The reason given by the CAS server for authentication failure.\n #\n # @return [String, nil]\n attr_accessor :failure_reason\n\n ##\n # The name of the owner of the validated service or proxy ticket.\n #\n # This information is only present on authentication success.\n #\n # @return [String, nil]\n attr_accessor :username\n\n ##\n # Generates a {Response} object from a CAS response.\n #\n # @param [String] response the CAS response\n # @return [Response]\n def self.from_cas(response)\n data = response.strip.unpack('c*')\n buffer = ''\n eof = nil\n\n %% write init;\n\n new.tap do |r|\n %% write exec;\n end\n end\n\n def initialize\n self.authenticated = false\n end\n\n %% write data;\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"07354ce699d1de6712b2793803676842cae92bd9","subject":"add space after comma in typized argument lists","message":"add space after comma in typized argument lists\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/postprocess.rl","new_file":"src\/postprocess.rl","new_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US);\n\n '_tsbus_cotm' => { fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:,;_\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>()[\\]{}\\t:;,_\\&]) => {fout << *ts;};\n *|;\n}%%\n\nclass PostProcess\n{\n\npublic:\n \/\/ constructor\n PostProcess(const string & filename) :\n filename_(filename),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false)\n { }\n\n \/\/ run postprocessor\n int execute()\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try\n {\n is.open(filename_.c_str());\n }\n catch (std::ifstream::failure e)\n {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char * buf = new char[(int)(1.1*length)];\n char * p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n\n ofstream fout;\n try\n {\n fout.open(filename_.c_str(), ios_base::trunc);\n }\n catch (std::ofstream::failure e)\n {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << filename_ << \": PARSE ERROR in line \" << line << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n\nprivate:\n string filename_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string filename;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n filename = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n PostProcess scanner(filename);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","old_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US);\n\n '_tsbus_cotm' => { fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); };\n ('<' . '::') => { fout.write(ts, 4); };\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:,;_\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>()[\\]{}\\t:;,_\\&]) => {fout << *ts;};\n *|;\n}%%\n\nclass PostProcess\n{\n\npublic:\n \/\/ constructor\n PostProcess(const string & filename) :\n filename_(filename),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false)\n { }\n\n \/\/ run postprocessor\n int execute()\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try\n {\n is.open(filename_.c_str());\n }\n catch (std::ifstream::failure e)\n {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char * buf = new char[(int)(1.1*length)];\n char * p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n\n ofstream fout;\n try\n {\n fout.open(filename_.c_str(), ios_base::trunc);\n }\n catch (std::ofstream::failure e)\n {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << filename_ << \": PARSE ERROR in line \" << line << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n\nprivate:\n string filename_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string filename;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n filename = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n PostProcess scanner(filename);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"56341b55857879542ac2e2a8b0789cd09ad03eb9","subject":"Cleaned up lexing of comments\/cdata.","message":"Cleaned up lexing of comments\/cdata.\n\nThanks to @whitequark for suggesting the use of the \"--\" operator.\n","repos":"YorickPeterse\/oga,dfockler\/oga,jeffreybaird\/oga,jeffreybaird\/oga,YorickPeterse\/oga,ttasanen\/oga,dfockler\/oga,jeffreybaird\/oga,YorickPeterse\/oga,ttasanen\/oga,altmetric\/oga,dfockler\/oga,ttasanen\/oga,altmetric\/oga,ttasanen\/oga,YorickPeterse\/oga,altmetric\/oga,ttasanen\/oga,jeffreybaird\/oga,YorickPeterse\/oga,altmetric\/oga,dfockler\/oga,jeffreybaird\/oga,dfockler\/oga,altmetric\/oga","old_file":"ext\/ragel\/base_lexer.rl","new_file":"ext\/ragel\/base_lexer.rl","new_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n #\n # ## Machine Transitions\n #\n # To transition from one machine to another always use `fnext` instead of\n # `fcall` and `fret`. This removes the need for the code to keep track of a\n # stack.\n #\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_]+;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences would\n # actually make the rules\/actions more complex.\n #\n\n comment_start = '';\n comment = comment_start (any* -- comment_end) comment_end;\n\n action start_comment {\n callback(\"on_comment\", data, encoding, ts + 4, te - 3);\n }\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n\n cdata_start = '';\n cdata = cdata_start (any* -- cdata_end) cdata_end;\n\n action start_cdata {\n callback(\"on_cdata\", data, encoding, ts + 9, te - 3);\n }\n\n # Processing Instructions\n #\n # http:\/\/www.w3.org\/TR\/xpath\/#section-Processing-Instruction-Nodes\n # http:\/\/en.wikipedia.org\/wiki\/Processing_Instruction\n #\n # These are tags meant to be used by parsers\/libraries for custom behaviour.\n # One example are the tags used by PHP: . Note that the XML\n # declaration tags () are not considered to be a processing\n # instruction.\n #\n\n proc_ins_start = '';\n\n action start_proc_ins {\n callback_simple(\"on_proc_ins_start\");\n callback(\"on_proc_ins_name\", data, encoding, ts + 2, te);\n\n mark = te;\n\n fnext proc_ins_body;\n }\n\n proc_ins_body := |*\n proc_ins_end => {\n callback(\"on_text\", data, encoding, mark, ts);\n callback_simple(\"on_proc_ins_end\");\n\n fnext main;\n };\n\n any;\n *|;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote+ dquote);\n string_squote = (squote ^squote+ squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n callback(\"on_string\", data, encoding, ts + 1, te - 1);\n }\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Consumes everything between the [ and ]. Due to the use of :> the ]\n # is not consumed by any+.\n '[' any+ :> ']' => {\n callback(\"on_doctype_inline\", data, encoding, ts + 1, te - 1);\n };\n\n # Lex the public\/system IDs as regular strings.\n string => emit_string;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fnext main;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n string => emit_string;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n action start_element {\n callback_simple(\"on_element_start\");\n fnext element_name;\n }\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(\"on_element_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_element_name\", data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"advance_line\");\n };\n\n # Attribute names and namespaces.\n identifier ':' => {\n callback(\"on_attribute_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n string => emit_string;\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(\"on_element_open_end\");\n fnext main;\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(\"on_element_end\");\n fnext main;\n };\n *|;\n\n # The main machine aka the entry point of Ragel.\n main := |*\n doctype_start => start_doctype;\n xml_decl_start => start_xml_decl;\n comment => start_comment;\n cdata => start_cdata;\n proc_ins_start => start_proc_ins;\n\n\n # The start of an element.\n '<' => start_element;\n\n # Regular closing tags.\n '<\/' identifier (':' identifier)* '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Treat everything else, except for \"<\", as regular text. The \"<\" sign\n # is used for tags so we can't emit text nodes for these characters.\n ^'<'+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","old_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n #\n # ## Machine Transitions\n #\n # To transition from one machine to another always use `fnext` instead of\n # `fcall` and `fret`. This removes the need for the code to keep track of a\n # stack.\n #\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_]+;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences would\n # actually make the rules\/actions more complex.\n #\n\n comment_start = '';\n\n action start_comment {\n mark = te;\n\n fnext comment_body;\n }\n\n comment_body := |*\n comment_end => {\n callback(\"on_comment\", data, encoding, mark, te - 3);\n\n mark = 0;\n\n fnext main;\n };\n\n any;\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n\n cdata_start = '';\n\n action start_cdata {\n mark = te;\n\n fnext cdata_body;\n }\n\n cdata_body := |*\n cdata_end => {\n callback(\"on_cdata\", data, encoding, mark, te - 3);\n\n mark = 0;\n\n fnext main;\n };\n\n any;\n *|;\n\n # Processing Instructions\n #\n # http:\/\/www.w3.org\/TR\/xpath\/#section-Processing-Instruction-Nodes\n # http:\/\/en.wikipedia.org\/wiki\/Processing_Instruction\n #\n # These are tags meant to be used by parsers\/libraries for custom behaviour.\n # One example are the tags used by PHP: . Note that the XML\n # declaration tags () are not considered to be a processing\n # instruction.\n #\n\n proc_ins_start = '';\n\n action start_proc_ins {\n callback_simple(\"on_proc_ins_start\");\n callback(\"on_proc_ins_name\", data, encoding, ts + 2, te);\n\n mark = te;\n\n fnext proc_ins_body;\n }\n\n proc_ins_body := |*\n proc_ins_end => {\n callback(\"on_text\", data, encoding, mark, ts);\n callback_simple(\"on_proc_ins_end\");\n\n fnext main;\n };\n\n any;\n *|;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n string_dquote = (dquote ^dquote+ dquote);\n string_squote = (squote ^squote+ squote);\n\n string = string_dquote | string_squote;\n\n action emit_string {\n callback(\"on_string\", data, encoding, ts + 1, te - 1);\n }\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Consumes everything between the [ and ]. Due to the use of :> the ]\n # is not consumed by any+.\n '[' any+ :> ']' => {\n callback(\"on_doctype_inline\", data, encoding, ts + 1, te - 1);\n };\n\n # Lex the public\/system IDs as regular strings.\n string => emit_string;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fnext main;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n string => emit_string;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n action start_element {\n callback_simple(\"on_element_start\");\n fnext element_name;\n }\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(\"on_element_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_element_name\", data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"advance_line\");\n };\n\n # Attribute names and namespaces.\n identifier ':' => {\n callback(\"on_attribute_ns\", data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n string => emit_string;\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(\"on_element_open_end\");\n fnext main;\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(\"on_element_end\");\n fnext main;\n };\n *|;\n\n # The main machine aka the entry point of Ragel.\n main := |*\n doctype_start => start_doctype;\n xml_decl_start => start_xml_decl;\n comment_start => start_comment;\n cdata_start => start_cdata;\n proc_ins_start => start_proc_ins;\n\n # The start of an element.\n '<' => start_element;\n\n # Regular closing tags.\n '<\/' identifier (':' identifier)* '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Treat everything else, except for \"<\", as regular text. The \"<\" sign\n # is used for tags so we can't emit text nodes for these characters.\n ^'<'+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"0c108b0ec105ff52fa6c4301afd731589f213b19","subject":"Remove unnecessary `fret`s from scanner","message":"Remove unnecessary `fret`s from scanner\n\nThese generated \"statement not reached\" warnings\n","repos":"ammar\/regexp_parser,ammar\/regexp_parser","old_file":"lib\/regexp_parser\/scanner\/scanner.rl","new_file":"lib\/regexp_parser\/scanner\/scanner.rl","new_contents":"%%{\n machine re_scanner;\n include re_property \"property.rl\";\n\n dot = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n comment = ('#' . [^\\n]* . '\\n');\n\n class_name_posix = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n class_posix = ('[:' . '^'? . class_name_posix . ':]');\n\n\n # these are not supported in ruby, and need verification\n collating_sequence = '[.' . (alpha | [\\-])+ . '.]';\n character_equivalent = '[=' . alpha . '=]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n\n escaped_ascii = [abefnrstv];\n octal_sequence = [0-7]{1,3};\n\n hex_sequence = 'x' . xdigit{1,2};\n hex_sequence_err = 'x' . [^0-9a-fA-F{];\n wide_hex_sequence = 'x' . '{' . xdigit{1,8} . '}';\n\n hex_or_not = (xdigit|[^0-9a-fA-F}]); # note closing curly at end\n\n wide_hex_seq_invalid = 'x' . '{' . hex_or_not{1,9};\n wide_hex_seq_empty = 'x' . '{' . (space+)? . '}';\n\n codepoint_single = 'u' . xdigit{4};\n codepoint_list = 'u{' . (xdigit{4} . space?)+'}';\n codepoint_sequence = codepoint_single | codepoint_list;\n\n control_sequence = ('c' | 'C-');\n\n meta_sequence = 'M-' . (backslash . control_sequence)?;\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_interval = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_interval;\n\n\n conditional = '(?(';\n\n group_comment = '?#' . [^)]* . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | (\"'\" . group_name_id . \"'\");\n group_lookup = group_name | group_number;\n\n group_named = ('?' . group_name );\n\n group_name_ref = group_ref . (('<' . group_name_id . group_level? '>') |\n (\"'\" . group_name_id . group_level? \"'\"));\n\n group_number_ref = group_ref . (('<' . group_number . group_level? '>') |\n (\"'\" . group_number . group_level? \"'\"));\n\n group_type = group_atomic | group_passive | group_named;\n\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = dot | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n ascii_print = ((0x20..0x7e) - meta_char)+;\n ascii_nonprint = (0x01..0x1f | 0x7f)+;\n\n utf8_2_byte = (0xc2..0xdf 0x80..0xbf)+;\n utf8_3_byte = (0xe0..0xef 0x80..0xbf 0x80..0xbf)+;\n utf8_4_byte = (0xf0..0xf4 0x80..0xbf 0x80..0xbf 0x80..0xbf)+;\n utf8_byte_sequence = utf8_2_byte | utf8_3_byte | utf8_4_byte;\n\n non_literal_escape = char_type | anchor_char | escaped_ascii |\n group_ref | [xucCM];\n\n # EOF error, used where it can be detected\n action premature_end_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise PrematureEndError.new( text )\n }\n\n # Invalid sequence error, used from sequences, like escapes and sets\n action invalid_sequence_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise InvalidSequenceError.new('sequence', text)\n }\n\n # group (nesting) and set open\/close actions\n action group_opened { @group_depth += 1; @in_group = true }\n action group_closed { @group_depth -= 1; @in_group = @group_depth > 0 ? true : false }\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :close, *text(data, ts, te))\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '-]' { # special case, emits two tokens\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :member, copy(data, ts..te-2), ts, te)\n emit(set_type, :close, copy(data, ts+1..te-1), ts, te)\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '^' {\n text = text(data, ts, te).first\n if @tokens.last[1] == :open\n emit(set_type, :negate, text, ts, te)\n else\n emit(set_type, :member, text, ts, te)\n end\n };\n\n alnum . '-' . alnum {\n emit(set_type, :range, *text(data, ts, te))\n };\n\n '&&' {\n emit(set_type, :intersection, *text(data, ts, te))\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n '[' >(open_bracket, 1) {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n class_posix >(open_bracket, 1) @eof(premature_end_error) {\n text = text(data, ts, te).first\n\n class_name = text[2..-3]\n if class_name[0].chr == '^'\n class_name = \"non#{class_name[1..-1]}\"\n end\n\n token_sym = \"class_#{class_name}\".to_sym\n emit(set_type, token_sym, text, ts, te)\n };\n\n collating_sequence >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :collation, *text(data, ts, te))\n };\n\n character_equivalent >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :equivalent, *text(data, ts, te))\n };\n\n # exclude the closing bracket as a cleaner workaround for dealing with the\n # ambiguity caused upon exit from the unicode properties machine\n meta_char -- ']' {\n emit(set_type, :member, *text(data, ts, te))\n };\n\n any |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :member, *text(data, ts, te))\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' > (escaped_set_alpha, 2) {\n emit(set_type, :backspace, *text(data, ts, te, 1))\n fret;\n };\n\n char_type > (escaped_set_alpha, 4) {\n case text = text(data, ts, te, 1).first\n when '\\d'; emit(set_type, :type_digit, text, ts-1, te)\n when '\\D'; emit(set_type, :type_nondigit, text, ts-1, te)\n when '\\h'; emit(set_type, :type_hex, text, ts-1, te)\n when '\\H'; emit(set_type, :type_nonhex, text, ts-1, te)\n when '\\s'; emit(set_type, :type_space, text, ts-1, te)\n when '\\S'; emit(set_type, :type_nonspace, text, ts-1, te)\n when '\\w'; emit(set_type, :type_word, text, ts-1, te)\n when '\\W'; emit(set_type, :type_nonword, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n emit(set_type, :range_hex, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence {\n emit(set_type, :member_hex, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char | [\\\\\\]\\-\\,] {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n\n property_char > (escaped_set_alpha, 3) {\n fhold;\n fnext character_set;\n fcall unicode_property;\n };\n\n # special case exclusion of escaped dash, could be cleaner.\n (ascii_print - char_type -- [\\-}]) > (escaped_set_alpha, 1) |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n [1-9] {\n text = text(data, ts, te, 1).first\n emit(:backref, :number, text, ts-1, te)\n fret;\n };\n\n octal_sequence {\n emit(:escape, :octal, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char {\n case text = text(data, ts, te, 1).first\n when '\\.'; emit(:escape, :dot, text, ts-1, te)\n when '\\|'; emit(:escape, :alternation, text, ts-1, te)\n when '\\^'; emit(:escape, :bol, text, ts-1, te)\n when '\\$'; emit(:escape, :eol, text, ts-1, te)\n when '\\?'; emit(:escape, :zero_or_one, text, ts-1, te)\n when '\\*'; emit(:escape, :zero_or_more, text, ts-1, te)\n when '\\+'; emit(:escape, :one_or_more, text, ts-1, te)\n when '\\('; emit(:escape, :group_open, text, ts-1, te)\n when '\\)'; emit(:escape, :group_close, text, ts-1, te)\n when '\\{'; emit(:escape, :interval_open, text, ts-1, te)\n when '\\}'; emit(:escape, :interval_close, text, ts-1, te)\n when '\\['; emit(:escape, :set_open, text, ts-1, te)\n when '\\]'; emit(:escape, :set_close, text, ts-1, te)\n when \"\\\\\\\\\";\n emit(:escape, :backslash, text, ts-1, te)\n end\n fret;\n };\n\n escaped_ascii > (escaped_alpha, 7) {\n # \\b is emitted as backspace only when inside a character set, otherwise\n # it is a word boundary anchor. A syntax might \"normalize\" it if needed.\n case text = text(data, ts, te, 1).first\n when '\\a'; emit(:escape, :bell, text, ts-1, te)\n when '\\e'; emit(:escape, :escape, text, ts-1, te)\n when '\\f'; emit(:escape, :form_feed, text, ts-1, te)\n when '\\n'; emit(:escape, :newline, text, ts-1, te)\n when '\\r'; emit(:escape, :carriage, text, ts-1, te)\n when '\\s'; emit(:escape, :space, text, ts-1, te)\n when '\\t'; emit(:escape, :tab, text, ts-1, te)\n when '\\v'; emit(:escape, :vertical_tab, text, ts-1, te)\n end\n fret;\n };\n\n codepoint_sequence > (escaped_alpha, 6) $eof(premature_end_error) {\n text = text(data, ts, te, 1).first\n if text[2].chr == '{'\n emit(:escape, :codepoint_list, text, ts-1, te)\n else\n emit(:escape, :codepoint, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex, *text(data, ts, te, 1))\n fret;\n };\n\n wide_hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex_wide, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence_err @invalid_sequence_error {\n fret;\n };\n\n (wide_hex_seq_invalid | wide_hex_seq_empty) {\n raise InvalidSequenceError.new(\"wide hex sequence\")\n fret;\n };\n\n control_sequence >(escaped_alpha, 4) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :control, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"control sequence\")\n end\n else\n raise PrematureEndError.new(\"control sequence\")\n end\n fret;\n };\n\n meta_sequence >(backslashed, 3) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :meta_sequence, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"meta sequence\")\n end\n else\n raise PrematureEndError.new(\"meta sequence\")\n end\n fret;\n };\n\n property_char > (escaped_alpha, 2) {\n fhold;\n fnext main;\n fcall unicode_property;\n };\n\n (any -- non_literal_escape) > (escaped_alpha, 1) {\n emit(:escape, :literal, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # conditional expressions scanner\n # --------------------------------------------------------------------------\n conditional_expression := |*\n group_lookup . ')' {\n text = text(data, ts, te-1).first\n emit(:conditional, :condition, text, ts, te-1)\n emit(:conditional, :condition_close, ')', te-1, te)\n };\n\n any {\n fhold;\n fcall main;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n # ------------------------------------------------------------------------\n dot {\n emit(:meta, :dot, *text(data, ts, te))\n };\n\n alternation {\n if in_conditional and conditional_stack.length > 0 and \n conditional_stack.last[1] == @group_depth\n emit(:conditional, :separator, *text(data, ts, te))\n else\n emit(:meta, :alternation, *text(data, ts, te))\n end\n };\n\n # Anchors\n # ------------------------------------------------------------------------\n beginning_of_line {\n emit(:anchor, :bol, *text(data, ts, te))\n };\n\n end_of_line {\n emit(:anchor, :eol, *text(data, ts, te))\n };\n\n backslash . 'K' > (backslashed, 4) {\n emit(:keep, :mark, *text(data, ts, te))\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = text(data, ts, te).first\n when '\\\\A'; emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; emit(:anchor, :eos_ob_eol, text, ts, te)\n when '\\\\b'; emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; emit(:anchor, :nonword_boundary, text, ts, te)\n when '\\\\G'; emit(:anchor, :match_start, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in anchor at #{text} (char #{ts})\")\n end\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S space, non-space\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = text(data, ts, te).first\n when '\\\\d'; emit(:type, :digit, text, ts, te)\n when '\\\\D'; emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; emit(:type, :hex, text, ts, te)\n when '\\\\H'; emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; emit(:type, :space, text, ts, te)\n when '\\\\S'; emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; emit(:type, :word, text, ts, te)\n when '\\\\W'; emit(:type, :nonword, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in type at #{text} (char #{ts})\")\n end\n };\n\n\n # Character sets\n # ------------------------------------------------------------------------\n set_open {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n\n # Conditional expression\n # (?(condition)Y|N) conditional expression\n # ------------------------------------------------------------------------\n conditional {\n text = text(data, ts, te).first\n\n in_conditional = true unless in_conditional\n conditional_depth += 1\n conditional_stack << [conditional_depth, @group_depth]\n\n emit(:conditional, :open, text[0..-2], ts, te-1)\n emit(:conditional, :condition_open, '(', te-1, te)\n fcall conditional_expression;\n };\n\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n # special case for close, action performed on all transitions to get the \n # correct closing count.\n # ------------------------------------------------------------------------\n group_open . group_comment $group_closed {\n emit(:group, :comment, *text(data, ts, te))\n };\n\n # Expression options:\n # (?imxdau-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n # d: default class rules (1.9 compatible)\n # a: ASCII class rules (\\s, \\w, etc.)\n # u: Unicode class rules (\\s, \\w, etc.)\n #\n # (?imxdau-imx:subexp) option on\/off for subexp\n # ------------------------------------------------------------------------\n group_open . group_options >group_opened {\n p = scan_options(p, data, ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?group_opened {\n case text = text(data, ts, te).first\n when '(?='; emit(:assertion, :lookahead, text, ts, te)\n when '(?!'; emit(:assertion, :nlookahead, text, ts, te)\n when '(?<='; emit(:assertion, :lookbehind, text, ts, te)\n when '(?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group\n # (?'name'subexp) named group (single quoted version)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type >group_opened {\n case text = text(data, ts, te).first\n when '(?:'; emit(:group, :passive, text, ts, te)\n when '(?>'; emit(:group, :atomic, text, ts, te)\n\n when \/^\\(\\?<(\\w*)>\/\n empty_name_error(:group, 'named group (ab)') if $1.empty?\n\n emit(:group, :named_ab, text, ts, te)\n\n when \/^\\(\\?'(\\w*)'\/\n empty_name_error(:group, 'named group (sq)') if $1.empty?\n\n emit(:group, :named_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown subexpression group format '#{text}'\")\n end\n };\n\n group_open @group_opened {\n text = text(data, ts, te).first\n emit(:group, :capture, text, ts, te)\n };\n\n group_close @group_closed {\n if in_conditional and conditional_stack.last and\n conditional_stack.last[1] == (@group_depth + 1)\n\n emit(:conditional, :close, *text(data, ts, te))\n conditional_stack.pop\n\n if conditional_stack.length == 0\n in_conditional = false\n end\n else\n if @spacing_stack.length > 1 and\n @spacing_stack.last[1] == (@group_depth + 1)\n @spacing_stack.pop\n\n @free_spacing = @spacing_stack.last[0]\n\n if @spacing_stack.length == 1\n @in_options = false\n end\n end\n\n emit(:group, :close, *text(data, ts, te))\n end\n };\n\n\n # Group backreference, named and numbered\n # ------------------------------------------------------------------------\n backslash . (group_name_ref | group_number_ref) > (backslashed, 4) {\n case text = text(data, ts, te).first\n when \/^\\\\([gk])<>\/ # angle brackets\n empty_backref_error(\"ref\/call (ab)\")\n\n when \/^\\\\([gk])''\/ # single quotes\n empty_backref_error(\"ref\/call (sq)\")\n\n when \/^\\\\([gk])<[^\\d-](\\w+)?>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :name_ref_ab, text, ts, te)\n else\n emit(:backref, :name_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'[^\\d-](\\w+)?'\/ #single quotes\n if $1 == 'k'\n emit(:backref, :name_ref_sq, text, ts, te)\n else\n emit(:backref, :name_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_ref_ab, text, ts, te)\n else\n emit(:backref, :number_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_ref_sq, text, ts, te)\n else\n emit(:backref, :number_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<-\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_rel_ref_ab, text, ts, te)\n else\n emit(:backref, :number_rel_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'-\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_rel_ref_sq, text, ts, te)\n else\n emit(:backref, :number_rel_call_sq, text, ts, te)\n end\n\n when \/^\\\\k<[^\\d-](\\w+)?[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :name_nest_ref_ab, text, ts, te)\n\n when \/^\\\\k'[^\\d-](\\w+)?[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :name_nest_ref_sq, text, ts, te)\n\n when \/^\\\\([gk])<\\d+[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :number_nest_ref_ab, text, ts, te)\n\n when \/^\\\\([gk])'\\d+[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :number_nest_ref_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown backreference format '#{text}'\")\n end\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = text(data, ts, te).first\n when '?' ; emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n\n zero_or_more {\n case text = text(data, ts, te).first\n when '*' ; emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n\n one_or_more {\n case text = text(data, ts, te).first\n when '+' ; emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n quantifier_interval @err(premature_end_error) {\n emit(:quantifier, :interval, *text(data, ts, te))\n };\n\n # Escaped sequences\n # ------------------------------------------------------------------------\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n comment {\n if @free_spacing\n emit(:free_space, :comment, *text(data, ts, te))\n else\n append_literal(data, ts, te)\n end\n };\n\n space+ {\n if @free_spacing\n emit(:free_space, :whitespace, *text(data, ts, te))\n else\n append_literal(data, ts, te)\n end\n };\n\n # Literal: any run of ASCII (pritable or non-printable), and\/or UTF-8,\n # except meta characters.\n # ------------------------------------------------------------------------\n (ascii_print -- space)+ |\n ascii_nonprint+ |\n utf8_2_byte+ |\n utf8_3_byte+ |\n utf8_4_byte+ {\n append_literal(data, ts, te)\n };\n\n *|;\n}%%\n\n# THIS IS A GENERATED FILE, DO NOT EDIT DIRECTLY\n# This file was generated from lib\/regexp_parser\/scanner\/scanner.rl\n\nmodule Regexp::Scanner\n %% write data;\n\n # General scanner error (catch all)\n class ScannerError < StandardError; end\n\n # Base for all scanner validation errors\n class ValidationError < StandardError\n def initialize(reason)\n super reason\n end\n end\n\n # Unexpected end of pattern\n class PrematureEndError < ScannerError\n def initialize(where = '')\n super \"Premature end of pattern at #{where}\"\n end\n end\n\n # Invalid sequence format. Used for escape sequences, mainly.\n class InvalidSequenceError < ValidationError\n def initialize(what = 'sequence', where = '')\n super \"Invalid #{what} at #{where}\"\n end\n end\n\n # Invalid group. Used for named groups.\n class InvalidGroupError < ValidationError\n def initialize(what, reason)\n super \"Invalid #{what}, #{reason}.\"\n end\n end\n\n # Invalid groupOption. Used for inline options.\n class InvalidGroupOption < ValidationError\n def initialize(option, text)\n super \"Invalid group option #{option} in #{text}\"\n end\n end\n\n # Invalid back reference. Used for name a number refs\/calls.\n class InvalidBackrefError < ValidationError\n def initialize(what, reason)\n super \"Invalid back reference #{what}, #{reason}\"\n end\n end\n\n # The property name was not recognized by the scanner.\n class UnknownUnicodePropertyError < ValidationError\n def initialize(name)\n super \"Unknown unicode character property name #{name}\"\n end\n end\n\n # Scans the given regular expression text, or Regexp object and collects the\n # emitted token into an array that gets returned at the end. If a block is\n # given, it gets called for each emitted token.\n #\n # This method may raise errors if a syntax error is encountered.\n # --------------------------------------------------------------------------\n def self.scan(input_object, &block)\n top, stack = 0, []\n\n if input_object.is_a?(Regexp)\n input = input_object.source\n @free_spacing = (input_object.options & Regexp::EXTENDED != 0)\n else\n input = input_object\n @free_spacing = false\n end\n\n\n data = input.unpack(\"c*\") if input.is_a?(String)\n eof = data.length\n\n @tokens = []\n @block = block_given? ? block : nil\n\n @in_group, @group_depth = false, 0\n @in_options, @spacing_stack = false, [[@free_spacing, 0]]\n\n in_set, set_depth, set_type = false, 0, :set\n in_conditional, conditional_depth, conditional_stack = false, 0, []\n\n %% write init;\n %% write exec;\n\n if cs == re_scanner_error\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise ScannerError.new(\"Scan error at '#{text}'\")\n end\n\n raise PrematureEndError.new(\"(missing group closing paranthesis) \"+\n \"[#{@in_group}:#{@group_depth}]\") if @in_group\n raise PrematureEndError.new(\"(missing set closing bracket) \"+\n \"[#{in_set}:#{set_depth}]\") if in_set\n\n # when the entire expression is a literal run\n emit_literal if @literal\n\n @tokens\n end\n\n private\n\n # Ragel's regex-based scan of the group options introduced a lot of\n # ambiguity, so we just ask it to find the beginning of what looks\n # like an options run and handle the rest in here.\n def self.scan_options(p, data, ts, te)\n text = text(data, ts, te).first\n\n options_char, options_length = true, 0\n\n # Copy while we have option characters. There is no maximum length,\n # as ruby allows things like '(?xxxxxxxxx-xxxxxxxxxxxxx:abc)'.\n negative_options = false\n while options_char\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c =~ \/[-mixdau]\/\n negative_options = true if c == '-'\n\n raise InvalidGroupOption.new(c, text) if negative_options and\n c =~ \/[dau]\/\n\n text << c ; p += 1 ; options_length += 1\n else\n options_char = false\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n end\n\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c == ':'\n # Include the ':' in the options text\n text << c ; p += 1 ; options_length += 1\n emit_options(text, ts, te + options_length)\n\n elsif c == ')'\n # Don't include the closing ')', let group_close handle it.\n emit_options(text, ts, te + options_length)\n\n else\n # Plain Regexp reports this as 'undefined group option'\n raise ScannerError.new(\n \"Unexpected `#{c}' in options sequence, ':' or ')' expected\")\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n\n p # return the new value of the data pointer\n end\n\n # Copy from ts to te from data as text\n def self.copy(data, range)\n data[range].pack('c*')\n end\n\n # Copy from ts to te from data as text, returning an array with the text\n # and the offsets used to copy it.\n def self.text(data, ts, te, soff = 0)\n [copy(data, ts-soff..te-1), ts-soff, te]\n end\n\n # Appends one or more characters to the literal buffer, to be emitted later\n # by a call to emit_literal. Contents can be a mix of ASCII and UTF-8.\n def self.append_literal(data, ts, te)\n @literal ||= []\n @literal << text(data, ts, te)\n end\n\n # Emits the literal run collected by calls to the append_literal method,\n # using the total start (ts) and end (te) offsets of the run.\n def self.emit_literal\n ts, te = @literal.first[1], @literal.last[2]\n text = @literal.map {|t| t[0]}.join\n\n text.force_encoding('utf-8') if text.respond_to?(:force_encoding)\n\n @literal = nil\n emit(:literal, :literal, text, ts, te)\n end\n\n def self.emit_options(text, ts, te)\n if text =~ \/\\(\\?([mixdau]+)?-?([mix]+)?:\/\n positive, negative = $1, $2\n\n if positive =~ \/x\/\n @free_spacing = true\n end\n\n # If the x appears in both, treat it like ruby does, the second cancels\n # the first.\n if negative =~ \/x\/\n @free_spacing = false\n end\n end\n\n @in_options = true\n @spacing_stack << [@free_spacing, @group_depth]\n\n emit(:group, :options, text, ts, te)\n end\n\n # Emits an array with the details of the scanned pattern\n def self.emit(type, token, text, ts, te)\n #puts \"EMIT: type: #{type}, token: #{token}, text: #{text}, ts: #{ts}, te: #{te}\"\n\n emit_literal if @literal\n\n if @block\n @block.call type, token, text, ts, te\n end\n\n @tokens << [type, token, text, ts, te]\n end\n\n # Centralizes and unifies the handling of validation related\n # errors.\n def self.validation_error(type, what, reason)\n case type\n when :group\n error = InvalidGroupError.new(what, reason)\n when :backref\n error = InvalidBackrefError.new(what, reason)\n when :sequence\n error = InvalidSequenceError.new(what, reason)\n else\n error = ValidationError.new('expression')\n end\n\n raise error # unless @@config.validation_ignore\n end\n\n # Used for references with an empty name or number\n def self.empty_backref_error(type, what)\n validation_error(:backref, what, 'ref ID is empty')\n end\n\n # Used for named expressions with an empty name\n def self.empty_name_error(type, what)\n validation_error(type, what, 'name is empty')\n end\n\nend # module Regexp::Scanner\n","old_contents":"%%{\n machine re_scanner;\n include re_property \"property.rl\";\n\n dot = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n comment = ('#' . [^\\n]* . '\\n');\n\n class_name_posix = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n class_posix = ('[:' . '^'? . class_name_posix . ':]');\n\n\n # these are not supported in ruby, and need verification\n collating_sequence = '[.' . (alpha | [\\-])+ . '.]';\n character_equivalent = '[=' . alpha . '=]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n\n escaped_ascii = [abefnrstv];\n octal_sequence = [0-7]{1,3};\n\n hex_sequence = 'x' . xdigit{1,2};\n hex_sequence_err = 'x' . [^0-9a-fA-F{];\n wide_hex_sequence = 'x' . '{' . xdigit{1,8} . '}';\n\n hex_or_not = (xdigit|[^0-9a-fA-F}]); # note closing curly at end\n\n wide_hex_seq_invalid = 'x' . '{' . hex_or_not{1,9};\n wide_hex_seq_empty = 'x' . '{' . (space+)? . '}';\n\n codepoint_single = 'u' . xdigit{4};\n codepoint_list = 'u{' . (xdigit{4} . space?)+'}';\n codepoint_sequence = codepoint_single | codepoint_list;\n\n control_sequence = ('c' | 'C-');\n\n meta_sequence = 'M-' . (backslash . control_sequence)?;\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_interval = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_interval;\n\n\n conditional = '(?(';\n\n group_comment = '?#' . [^)]* . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | (\"'\" . group_name_id . \"'\");\n group_lookup = group_name | group_number;\n\n group_named = ('?' . group_name );\n\n group_name_ref = group_ref . (('<' . group_name_id . group_level? '>') |\n (\"'\" . group_name_id . group_level? \"'\"));\n\n group_number_ref = group_ref . (('<' . group_number . group_level? '>') |\n (\"'\" . group_number . group_level? \"'\"));\n\n group_type = group_atomic | group_passive | group_named;\n\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = dot | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n ascii_print = ((0x20..0x7e) - meta_char)+;\n ascii_nonprint = (0x01..0x1f | 0x7f)+;\n\n utf8_2_byte = (0xc2..0xdf 0x80..0xbf)+;\n utf8_3_byte = (0xe0..0xef 0x80..0xbf 0x80..0xbf)+;\n utf8_4_byte = (0xf0..0xf4 0x80..0xbf 0x80..0xbf 0x80..0xbf)+;\n utf8_byte_sequence = utf8_2_byte | utf8_3_byte | utf8_4_byte;\n\n non_literal_escape = char_type | anchor_char | escaped_ascii |\n group_ref | [xucCM];\n\n # EOF error, used where it can be detected\n action premature_end_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise PrematureEndError.new( text )\n }\n\n # Invalid sequence error, used from sequences, like escapes and sets\n action invalid_sequence_error {\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise InvalidSequenceError.new('sequence', text)\n }\n\n # group (nesting) and set open\/close actions\n action group_opened { @group_depth += 1; @in_group = true }\n action group_closed { @group_depth -= 1; @in_group = @group_depth > 0 ? true : false }\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :close, *text(data, ts, te))\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '-]' { # special case, emits two tokens\n set_type = set_depth > 1 ? :subset : :set\n set_depth -= 1; in_set = set_depth > 0 ? true : false\n\n emit(set_type, :member, copy(data, ts..te-2), ts, te)\n emit(set_type, :close, copy(data, ts+1..te-1), ts, te)\n\n if set_depth == 0\n fgoto main;\n else\n fret;\n end\n };\n\n '^' {\n text = text(data, ts, te).first\n if @tokens.last[1] == :open\n emit(set_type, :negate, text, ts, te)\n else\n emit(set_type, :member, text, ts, te)\n end\n };\n\n alnum . '-' . alnum {\n emit(set_type, :range, *text(data, ts, te))\n };\n\n '&&' {\n emit(set_type, :intersection, *text(data, ts, te))\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n '[' >(open_bracket, 1) {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n class_posix >(open_bracket, 1) @eof(premature_end_error) {\n text = text(data, ts, te).first\n\n class_name = text[2..-3]\n if class_name[0].chr == '^'\n class_name = \"non#{class_name[1..-1]}\"\n end\n\n token_sym = \"class_#{class_name}\".to_sym\n emit(set_type, token_sym, text, ts, te)\n };\n\n collating_sequence >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :collation, *text(data, ts, te))\n };\n\n character_equivalent >(open_bracket, 1) @eof(premature_end_error) {\n emit(set_type, :equivalent, *text(data, ts, te))\n };\n\n # exclude the closing bracket as a cleaner workaround for dealing with the\n # ambiguity caused upon exit from the unicode properties machine\n meta_char -- ']' {\n emit(set_type, :member, *text(data, ts, te))\n };\n\n any |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :member, *text(data, ts, te))\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' > (escaped_set_alpha, 2) {\n emit(set_type, :backspace, *text(data, ts, te, 1))\n fret;\n };\n\n char_type > (escaped_set_alpha, 4) {\n case text = text(data, ts, te, 1).first\n when '\\d'; emit(set_type, :type_digit, text, ts-1, te)\n when '\\D'; emit(set_type, :type_nondigit, text, ts-1, te)\n when '\\h'; emit(set_type, :type_hex, text, ts-1, te)\n when '\\H'; emit(set_type, :type_nonhex, text, ts-1, te)\n when '\\s'; emit(set_type, :type_space, text, ts-1, te)\n when '\\S'; emit(set_type, :type_nonspace, text, ts-1, te)\n when '\\w'; emit(set_type, :type_word, text, ts-1, te)\n when '\\W'; emit(set_type, :type_nonword, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n emit(set_type, :range_hex, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence {\n emit(set_type, :member_hex, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char | [\\\\\\]\\-\\,] {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n\n property_char > (escaped_set_alpha, 3) {\n fhold;\n fnext character_set;\n fcall unicode_property;\n fret;\n };\n\n # special case exclusion of escaped dash, could be cleaner.\n (ascii_print - char_type -- [\\-}]) > (escaped_set_alpha, 1) |\n ascii_nonprint |\n utf8_2_byte |\n utf8_3_byte |\n utf8_4_byte {\n emit(set_type, :escape, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n [1-9] {\n text = text(data, ts, te, 1).first\n emit(:backref, :number, text, ts-1, te)\n fret;\n };\n\n octal_sequence {\n emit(:escape, :octal, *text(data, ts, te, 1))\n fret;\n };\n\n meta_char {\n case text = text(data, ts, te, 1).first\n when '\\.'; emit(:escape, :dot, text, ts-1, te)\n when '\\|'; emit(:escape, :alternation, text, ts-1, te)\n when '\\^'; emit(:escape, :bol, text, ts-1, te)\n when '\\$'; emit(:escape, :eol, text, ts-1, te)\n when '\\?'; emit(:escape, :zero_or_one, text, ts-1, te)\n when '\\*'; emit(:escape, :zero_or_more, text, ts-1, te)\n when '\\+'; emit(:escape, :one_or_more, text, ts-1, te)\n when '\\('; emit(:escape, :group_open, text, ts-1, te)\n when '\\)'; emit(:escape, :group_close, text, ts-1, te)\n when '\\{'; emit(:escape, :interval_open, text, ts-1, te)\n when '\\}'; emit(:escape, :interval_close, text, ts-1, te)\n when '\\['; emit(:escape, :set_open, text, ts-1, te)\n when '\\]'; emit(:escape, :set_close, text, ts-1, te)\n when \"\\\\\\\\\";\n emit(:escape, :backslash, text, ts-1, te)\n end\n fret;\n };\n\n escaped_ascii > (escaped_alpha, 7) {\n # \\b is emitted as backspace only when inside a character set, otherwise\n # it is a word boundary anchor. A syntax might \"normalize\" it if needed.\n case text = text(data, ts, te, 1).first\n when '\\a'; emit(:escape, :bell, text, ts-1, te)\n when '\\e'; emit(:escape, :escape, text, ts-1, te)\n when '\\f'; emit(:escape, :form_feed, text, ts-1, te)\n when '\\n'; emit(:escape, :newline, text, ts-1, te)\n when '\\r'; emit(:escape, :carriage, text, ts-1, te)\n when '\\s'; emit(:escape, :space, text, ts-1, te)\n when '\\t'; emit(:escape, :tab, text, ts-1, te)\n when '\\v'; emit(:escape, :vertical_tab, text, ts-1, te)\n end\n fret;\n };\n\n codepoint_sequence > (escaped_alpha, 6) $eof(premature_end_error) {\n text = text(data, ts, te, 1).first\n if text[2].chr == '{'\n emit(:escape, :codepoint_list, text, ts-1, te)\n else\n emit(:escape, :codepoint, text, ts-1, te)\n end\n fret;\n };\n\n hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex, *text(data, ts, te, 1))\n fret;\n };\n\n wide_hex_sequence > (escaped_alpha, 5) $eof(premature_end_error) {\n emit(:escape, :hex_wide, *text(data, ts, te, 1))\n fret;\n };\n\n hex_sequence_err @invalid_sequence_error {\n fret;\n };\n\n (wide_hex_seq_invalid | wide_hex_seq_empty) {\n raise InvalidSequenceError.new(\"wide hex sequence\")\n fret;\n };\n\n control_sequence >(escaped_alpha, 4) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :control, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"control sequence\")\n end\n else\n raise PrematureEndError.new(\"control sequence\")\n end\n fret;\n };\n\n meta_sequence >(backslashed, 3) $eof(premature_end_error) {\n if data[te]\n c = data[te].chr\n if c =~ \/[\\x00-\\x7F]\/\n emit(:escape, :meta_sequence, copy(data, ts-1..te), ts-1, te+1)\n p += 1\n else\n raise InvalidSequenceError.new(\"meta sequence\")\n end\n else\n raise PrematureEndError.new(\"meta sequence\")\n end\n fret;\n };\n\n property_char > (escaped_alpha, 2) {\n fhold;\n fnext main;\n fcall unicode_property; fret;\n };\n\n (any -- non_literal_escape) > (escaped_alpha, 1) {\n emit(:escape, :literal, *text(data, ts, te, 1))\n fret;\n };\n *|;\n\n\n # conditional expressions scanner\n # --------------------------------------------------------------------------\n conditional_expression := |*\n group_lookup . ')' {\n text = text(data, ts, te-1).first\n emit(:conditional, :condition, text, ts, te-1)\n emit(:conditional, :condition_close, ')', te-1, te)\n };\n\n any {\n fhold;\n fcall main;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n # ------------------------------------------------------------------------\n dot {\n emit(:meta, :dot, *text(data, ts, te))\n };\n\n alternation {\n if in_conditional and conditional_stack.length > 0 and \n conditional_stack.last[1] == @group_depth\n emit(:conditional, :separator, *text(data, ts, te))\n else\n emit(:meta, :alternation, *text(data, ts, te))\n end\n };\n\n # Anchors\n # ------------------------------------------------------------------------\n beginning_of_line {\n emit(:anchor, :bol, *text(data, ts, te))\n };\n\n end_of_line {\n emit(:anchor, :eol, *text(data, ts, te))\n };\n\n backslash . 'K' > (backslashed, 4) {\n emit(:keep, :mark, *text(data, ts, te))\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = text(data, ts, te).first\n when '\\\\A'; emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; emit(:anchor, :eos_ob_eol, text, ts, te)\n when '\\\\b'; emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; emit(:anchor, :nonword_boundary, text, ts, te)\n when '\\\\G'; emit(:anchor, :match_start, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in anchor at #{text} (char #{ts})\")\n end\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S space, non-space\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = text(data, ts, te).first\n when '\\\\d'; emit(:type, :digit, text, ts, te)\n when '\\\\D'; emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; emit(:type, :hex, text, ts, te)\n when '\\\\H'; emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; emit(:type, :space, text, ts, te)\n when '\\\\S'; emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; emit(:type, :word, text, ts, te)\n when '\\\\W'; emit(:type, :nonword, text, ts, te)\n else\n raise ScannerError.new(\n \"Unexpected character in type at #{text} (char #{ts})\")\n end\n };\n\n\n # Character sets\n # ------------------------------------------------------------------------\n set_open {\n set_depth += 1; in_set = true\n set_type = set_depth > 1 ? :subset : :set\n\n emit(set_type, :open, *text(data, ts, te))\n fcall character_set;\n };\n\n\n # Conditional expression\n # (?(condition)Y|N) conditional expression\n # ------------------------------------------------------------------------\n conditional {\n text = text(data, ts, te).first\n\n in_conditional = true unless in_conditional\n conditional_depth += 1\n conditional_stack << [conditional_depth, @group_depth]\n\n emit(:conditional, :open, text[0..-2], ts, te-1)\n emit(:conditional, :condition_open, '(', te-1, te)\n fcall conditional_expression;\n };\n\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n # special case for close, action performed on all transitions to get the \n # correct closing count.\n # ------------------------------------------------------------------------\n group_open . group_comment $group_closed {\n emit(:group, :comment, *text(data, ts, te))\n };\n\n # Expression options:\n # (?imxdau-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n # d: default class rules (1.9 compatible)\n # a: ASCII class rules (\\s, \\w, etc.)\n # u: Unicode class rules (\\s, \\w, etc.)\n #\n # (?imxdau-imx:subexp) option on\/off for subexp\n # ------------------------------------------------------------------------\n group_open . group_options >group_opened {\n p = scan_options(p, data, ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?group_opened {\n case text = text(data, ts, te).first\n when '(?='; emit(:assertion, :lookahead, text, ts, te)\n when '(?!'; emit(:assertion, :nlookahead, text, ts, te)\n when '(?<='; emit(:assertion, :lookbehind, text, ts, te)\n when '(?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group\n # (?'name'subexp) named group (single quoted version)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type >group_opened {\n case text = text(data, ts, te).first\n when '(?:'; emit(:group, :passive, text, ts, te)\n when '(?>'; emit(:group, :atomic, text, ts, te)\n\n when \/^\\(\\?<(\\w*)>\/\n empty_name_error(:group, 'named group (ab)') if $1.empty?\n\n emit(:group, :named_ab, text, ts, te)\n\n when \/^\\(\\?'(\\w*)'\/\n empty_name_error(:group, 'named group (sq)') if $1.empty?\n\n emit(:group, :named_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown subexpression group format '#{text}'\")\n end\n };\n\n group_open @group_opened {\n text = text(data, ts, te).first\n emit(:group, :capture, text, ts, te)\n };\n\n group_close @group_closed {\n if in_conditional and conditional_stack.last and\n conditional_stack.last[1] == (@group_depth + 1)\n\n emit(:conditional, :close, *text(data, ts, te))\n conditional_stack.pop\n\n if conditional_stack.length == 0\n in_conditional = false\n end\n else\n if @spacing_stack.length > 1 and\n @spacing_stack.last[1] == (@group_depth + 1)\n @spacing_stack.pop\n\n @free_spacing = @spacing_stack.last[0]\n\n if @spacing_stack.length == 1\n @in_options = false\n end\n end\n\n emit(:group, :close, *text(data, ts, te))\n end\n };\n\n\n # Group backreference, named and numbered\n # ------------------------------------------------------------------------\n backslash . (group_name_ref | group_number_ref) > (backslashed, 4) {\n case text = text(data, ts, te).first\n when \/^\\\\([gk])<>\/ # angle brackets\n empty_backref_error(\"ref\/call (ab)\")\n\n when \/^\\\\([gk])''\/ # single quotes\n empty_backref_error(\"ref\/call (sq)\")\n\n when \/^\\\\([gk])<[^\\d-](\\w+)?>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :name_ref_ab, text, ts, te)\n else\n emit(:backref, :name_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'[^\\d-](\\w+)?'\/ #single quotes\n if $1 == 'k'\n emit(:backref, :name_ref_sq, text, ts, te)\n else\n emit(:backref, :name_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_ref_ab, text, ts, te)\n else\n emit(:backref, :number_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_ref_sq, text, ts, te)\n else\n emit(:backref, :number_call_sq, text, ts, te)\n end\n\n when \/^\\\\([gk])<-\\d+>\/ # angle-brackets\n if $1 == 'k'\n emit(:backref, :number_rel_ref_ab, text, ts, te)\n else\n emit(:backref, :number_rel_call_ab, text, ts, te)\n end\n\n when \/^\\\\([gk])'-\\d+'\/ # single quotes\n if $1 == 'k'\n emit(:backref, :number_rel_ref_sq, text, ts, te)\n else\n emit(:backref, :number_rel_call_sq, text, ts, te)\n end\n\n when \/^\\\\k<[^\\d-](\\w+)?[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :name_nest_ref_ab, text, ts, te)\n\n when \/^\\\\k'[^\\d-](\\w+)?[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :name_nest_ref_sq, text, ts, te)\n\n when \/^\\\\([gk])<\\d+[+\\-]\\d+>\/ # angle-brackets\n emit(:backref, :number_nest_ref_ab, text, ts, te)\n\n when \/^\\\\([gk])'\\d+[+\\-]\\d+'\/ # single-quotes\n emit(:backref, :number_nest_ref_sq, text, ts, te)\n\n else\n raise ScannerError.new(\n \"Unknown backreference format '#{text}'\")\n end\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = text(data, ts, te).first\n when '?' ; emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n\n zero_or_more {\n case text = text(data, ts, te).first\n when '*' ; emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n\n one_or_more {\n case text = text(data, ts, te).first\n when '+' ; emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n quantifier_interval @err(premature_end_error) {\n emit(:quantifier, :interval, *text(data, ts, te))\n };\n\n # Escaped sequences\n # ------------------------------------------------------------------------\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n comment {\n if @free_spacing\n emit(:free_space, :comment, *text(data, ts, te))\n else\n append_literal(data, ts, te)\n end\n };\n\n space+ {\n if @free_spacing\n emit(:free_space, :whitespace, *text(data, ts, te))\n else\n append_literal(data, ts, te)\n end\n };\n\n # Literal: any run of ASCII (pritable or non-printable), and\/or UTF-8,\n # except meta characters.\n # ------------------------------------------------------------------------\n (ascii_print -- space)+ |\n ascii_nonprint+ |\n utf8_2_byte+ |\n utf8_3_byte+ |\n utf8_4_byte+ {\n append_literal(data, ts, te)\n };\n\n *|;\n}%%\n\n# THIS IS A GENERATED FILE, DO NOT EDIT DIRECTLY\n# This file was generated from lib\/regexp_parser\/scanner\/scanner.rl\n\nmodule Regexp::Scanner\n %% write data;\n\n # General scanner error (catch all)\n class ScannerError < StandardError; end\n\n # Base for all scanner validation errors\n class ValidationError < StandardError\n def initialize(reason)\n super reason\n end\n end\n\n # Unexpected end of pattern\n class PrematureEndError < ScannerError\n def initialize(where = '')\n super \"Premature end of pattern at #{where}\"\n end\n end\n\n # Invalid sequence format. Used for escape sequences, mainly.\n class InvalidSequenceError < ValidationError\n def initialize(what = 'sequence', where = '')\n super \"Invalid #{what} at #{where}\"\n end\n end\n\n # Invalid group. Used for named groups.\n class InvalidGroupError < ValidationError\n def initialize(what, reason)\n super \"Invalid #{what}, #{reason}.\"\n end\n end\n\n # Invalid groupOption. Used for inline options.\n class InvalidGroupOption < ValidationError\n def initialize(option, text)\n super \"Invalid group option #{option} in #{text}\"\n end\n end\n\n # Invalid back reference. Used for name a number refs\/calls.\n class InvalidBackrefError < ValidationError\n def initialize(what, reason)\n super \"Invalid back reference #{what}, #{reason}\"\n end\n end\n\n # The property name was not recognized by the scanner.\n class UnknownUnicodePropertyError < ValidationError\n def initialize(name)\n super \"Unknown unicode character property name #{name}\"\n end\n end\n\n # Scans the given regular expression text, or Regexp object and collects the\n # emitted token into an array that gets returned at the end. If a block is\n # given, it gets called for each emitted token.\n #\n # This method may raise errors if a syntax error is encountered.\n # --------------------------------------------------------------------------\n def self.scan(input_object, &block)\n top, stack = 0, []\n\n if input_object.is_a?(Regexp)\n input = input_object.source\n @free_spacing = (input_object.options & Regexp::EXTENDED != 0)\n else\n input = input_object\n @free_spacing = false\n end\n\n\n data = input.unpack(\"c*\") if input.is_a?(String)\n eof = data.length\n\n @tokens = []\n @block = block_given? ? block : nil\n\n @in_group, @group_depth = false, 0\n @in_options, @spacing_stack = false, [[@free_spacing, 0]]\n\n in_set, set_depth, set_type = false, 0, :set\n in_conditional, conditional_depth, conditional_stack = false, 0, []\n\n %% write init;\n %% write exec;\n\n if cs == re_scanner_error\n text = ts ? copy(data, ts-1..-1) : data.pack('c*')\n raise ScannerError.new(\"Scan error at '#{text}'\")\n end\n\n raise PrematureEndError.new(\"(missing group closing paranthesis) \"+\n \"[#{@in_group}:#{@group_depth}]\") if @in_group\n raise PrematureEndError.new(\"(missing set closing bracket) \"+\n \"[#{in_set}:#{set_depth}]\") if in_set\n\n # when the entire expression is a literal run\n emit_literal if @literal\n\n @tokens\n end\n\n private\n\n # Ragel's regex-based scan of the group options introduced a lot of\n # ambiguity, so we just ask it to find the beginning of what looks\n # like an options run and handle the rest in here.\n def self.scan_options(p, data, ts, te)\n text = text(data, ts, te).first\n\n options_char, options_length = true, 0\n\n # Copy while we have option characters. There is no maximum length,\n # as ruby allows things like '(?xxxxxxxxx-xxxxxxxxxxxxx:abc)'.\n negative_options = false\n while options_char\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c =~ \/[-mixdau]\/\n negative_options = true if c == '-'\n\n raise InvalidGroupOption.new(c, text) if negative_options and\n c =~ \/[dau]\/\n\n text << c ; p += 1 ; options_length += 1\n else\n options_char = false\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n end\n\n if data[te + options_length]\n c = data[te + options_length].chr\n\n if c == ':'\n # Include the ':' in the options text\n text << c ; p += 1 ; options_length += 1\n emit_options(text, ts, te + options_length)\n\n elsif c == ')'\n # Don't include the closing ')', let group_close handle it.\n emit_options(text, ts, te + options_length)\n\n else\n # Plain Regexp reports this as 'undefined group option'\n raise ScannerError.new(\n \"Unexpected `#{c}' in options sequence, ':' or ')' expected\")\n end\n else\n raise PrematureEndError.new(\"expression options `#{text}'\")\n end\n\n p # return the new value of the data pointer\n end\n\n # Copy from ts to te from data as text\n def self.copy(data, range)\n data[range].pack('c*')\n end\n\n # Copy from ts to te from data as text, returning an array with the text\n # and the offsets used to copy it.\n def self.text(data, ts, te, soff = 0)\n [copy(data, ts-soff..te-1), ts-soff, te]\n end\n\n # Appends one or more characters to the literal buffer, to be emitted later\n # by a call to emit_literal. Contents can be a mix of ASCII and UTF-8.\n def self.append_literal(data, ts, te)\n @literal ||= []\n @literal << text(data, ts, te)\n end\n\n # Emits the literal run collected by calls to the append_literal method,\n # using the total start (ts) and end (te) offsets of the run.\n def self.emit_literal\n ts, te = @literal.first[1], @literal.last[2]\n text = @literal.map {|t| t[0]}.join\n\n text.force_encoding('utf-8') if text.respond_to?(:force_encoding)\n\n @literal = nil\n emit(:literal, :literal, text, ts, te)\n end\n\n def self.emit_options(text, ts, te)\n if text =~ \/\\(\\?([mixdau]+)?-?([mix]+)?:\/\n positive, negative = $1, $2\n\n if positive =~ \/x\/\n @free_spacing = true\n end\n\n # If the x appears in both, treat it like ruby does, the second cancels\n # the first.\n if negative =~ \/x\/\n @free_spacing = false\n end\n end\n\n @in_options = true\n @spacing_stack << [@free_spacing, @group_depth]\n\n emit(:group, :options, text, ts, te)\n end\n\n # Emits an array with the details of the scanned pattern\n def self.emit(type, token, text, ts, te)\n #puts \"EMIT: type: #{type}, token: #{token}, text: #{text}, ts: #{ts}, te: #{te}\"\n\n emit_literal if @literal\n\n if @block\n @block.call type, token, text, ts, te\n end\n\n @tokens << [type, token, text, ts, te]\n end\n\n # Centralizes and unifies the handling of validation related\n # errors.\n def self.validation_error(type, what, reason)\n case type\n when :group\n error = InvalidGroupError.new(what, reason)\n when :backref\n error = InvalidBackrefError.new(what, reason)\n when :sequence\n error = InvalidSequenceError.new(what, reason)\n else\n error = ValidationError.new('expression')\n end\n\n raise error # unless @@config.validation_ignore\n end\n\n # Used for references with an empty name or number\n def self.empty_backref_error(type, what)\n validation_error(:backref, what, 'ref ID is empty')\n end\n\n # Used for named expressions with an empty name\n def self.empty_name_error(type, what)\n validation_error(type, what, 'name is empty')\n end\n\nend # module Regexp::Scanner\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"63870c784390e16675bd07517cb7795189abaa39","subject":"print flat ast; easier to read\/assert","message":"print flat ast; easier to read\/assert\n","repos":"nbargnesi\/libbel,OpenBEL\/libbel,OpenBEL\/libbel,nbargnesi\/libbel","old_file":"term.rl","new_file":"term.rl","new_contents":"\/*\n * Parses BEL terms.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"belparser.h\"\n\n%%{\n machine set;\n write data;\n}%%\n\nbel_arg_stack* stack_init(int max) {\n bel_arg_stack* stack;\n bel_ast_node* contents;\n\n stack = (bel_arg_stack *) malloc(sizeof(bel_arg_stack));\n contents = (bel_ast_node *) malloc(sizeof(bel_ast_node) * max);\n\n if (contents == NULL) {\n fprintf(stderr, \"Insufficient memory to initialize stack.\\n\");\n exit(1); \/* Exit, returning error code. *\/\n }\n\n stack->top = -1;\n stack->max = max;\n stack->contents = contents;\n\n return stack;\n};\n\nvoid stack_destroy(bel_arg_stack* stack) {\n free(stack->contents);\n stack->top = -1;\n stack->max = 0;\n stack->contents = NULL;\n};\n\nbel_ast_node* stack_peek(bel_arg_stack* stack) {\n if (stack_is_full(stack)) {\n fprintf(stderr, \"Can't push element on stack: stack is full.\\n\");\n exit(1);\n }\n\n bel_ast_node* top = &(stack->contents[stack->top]);\n return top;\n};\n\nvoid stack_push(bel_arg_stack* stack, bel_ast_node element) {\n if (stack_is_full(stack)) {\n fprintf(stderr, \"Can't push element on stack: stack is full.\\n\");\n exit(1);\n }\n\n stack->contents[++stack->top] = element;\n};\n\nbel_ast_node stack_pop(bel_arg_stack* stack) {\n if (stack_is_empty(stack)) {\n fprintf(stderr, \"Can't pop element from stack: stack is empty.\\n\");\n exit(1);\n }\n\n return stack->contents[stack->top--];\n};\n\nint stack_is_empty(bel_arg_stack* stack) {\n return stack->top < 0;\n};\n\nint stack_is_full(bel_arg_stack* stack) {\n return stack->top >= stack->max - 1;\n};\n\nbel_ast_node* bel_new_ast_node_token(bel_ast_token_type type) {\n bel_ast_node* node;\n node = malloc(sizeof(bel_ast_node));\n node->token = malloc(sizeof(bel_ast_node_token));\n node->token->type = TOKEN;\n node->token->ttype = type;\n node->token->left = NULL;\n node->token->right = NULL;\n return node;\n};\n\nbel_ast_node* bel_new_ast_node_value(bel_ast_value_type type, char value[]) {\n bel_ast_node* node;\n char* copy_value;\n\n if (value) {\n copy_value = (char *) malloc(sizeof(value));\n strncpy(copy_value, value, sizeof(value));\n } else {\n copy_value = NULL;\n }\n\n node = malloc(sizeof(bel_ast_node));\n node->value = malloc(sizeof(bel_ast_node_value));\n node->value->type = VALUE;\n node->value->vtype = type;\n node->value->value = copy_value;\n return node;\n};\n\nbel_ast* bel_new_ast() {\n bel_ast* ast;\n ast = malloc(sizeof(bel_ast));\n ast->root = NULL;\n return ast;\n};\n\nvoid bel_free_ast(bel_ast* ast) {\n if (!ast) {\n return;\n }\n bel_free_ast_node(ast->root);\n free(ast);\n};\n\nvoid bel_free_ast_node(bel_ast_node* node) {\n if (node->type_info->type == TOKEN && node->token->ttype != TOKEN_NIL) {\n bel_free_ast_node(node->token->left);\n bel_free_ast_node(node->token->right);\n }\n free(node);\n};\n\nvoid bel_print_ast_node(bel_ast_node* node) {\n if (!node) {\n return;\n }\n\n switch(node->type_info->type) {\n case TOKEN:\n switch(node->type_info->ttype) {\n case TOKEN_ARG:\n fprintf(stdout, \"ARG\\n\");\n break;\n case TOKEN_NIL:\n fprintf(stdout, \"NIL\\n\");\n break;\n case TOKEN_NV:\n fprintf(stdout, \"NV\\n\");\n break;\n case TOKEN_TERM:\n fprintf(stdout, \"TERM\\n\");\n break;\n }\n bel_print_ast_node(node->token->left);\n bel_print_ast_node(node->token->right);\n break;\n case VALUE:\n switch(node->type_info->vtype) {\n case VALUE_FX:\n fprintf(stdout, \"fx(%s)\\n\", node->value->value);\n break;\n case VALUE_NIL:\n fprintf(stdout, \"nil(%s)\\n\", node->value->value);\n break;\n case VALUE_PFX:\n fprintf(stdout, \"pfx(%s)\\n\", node->value->value);\n break;\n case VALUE_VAL:\n fprintf(stdout, \"val(%s)\\n\", node->value->value);\n break;\n }\n break;\n }\n}\n\nvoid bel_print_ast_node_flat(bel_ast_node* node, char* tree_flat_string) {\n if (!node) {\n return;\n }\n\n char val[128];\n switch(node->type_info->type) {\n case TOKEN:\n switch(node->type_info->ttype) {\n case TOKEN_ARG:\n strcat(tree_flat_string, \"ARG \");\n break;\n case TOKEN_NIL:\n strcat(tree_flat_string, \"NIL \");\n break;\n case TOKEN_NV:\n strcat(tree_flat_string, \"NV \");\n break;\n case TOKEN_TERM:\n strcat(tree_flat_string, \"TERM \");\n break;\n }\n bel_print_ast_node_flat(node->token->left, tree_flat_string);\n bel_print_ast_node_flat(node->token->right, tree_flat_string);\n break;\n case VALUE:\n switch(node->type_info->vtype) {\n case VALUE_FX:\n sprintf(val, \"fx(%s) \", node->value->value);\n strcat(tree_flat_string, val);\n break;\n case VALUE_NIL:\n sprintf(val, \"nil(%s) \", node->value->value);\n strcat(tree_flat_string, val);\n break;\n case VALUE_PFX:\n sprintf(val, \"pfx(%s) \", node->value->value);\n strcat(tree_flat_string, val);\n break;\n case VALUE_VAL:\n sprintf(val, \"val(%s) \", node->value->value);\n strcat(tree_flat_string, val);\n break;\n }\n break;\n }\n}\n\nvoid bel_print_ast(bel_ast* ast) {\n if (!ast) {\n return;\n }\n bel_print_ast_node(ast->root);\n fprintf(stdout, \"\\n\");\n};\n\nvoid bel_print_ast_flat(bel_ast* ast) {\n if (!ast) {\n return;\n }\n\n char tree_flat_string[1024];\n memset(tree_flat_string, '\\0', 1024);\n bel_print_ast_node_flat(ast->root, tree_flat_string);\n fprintf(stdout, \"%s\\n\", tree_flat_string);\n};\n\n#define VALUE_SIZE 128\n#define BUFSIZE 1024 * 32 \/\/ 32 kilobytes\n#define ARG_STACK_SIZE 100\n\nbel_ast* parse_term(char* line, char value[]) {\n int cs;\n char *p;\n char *pe;\n bel_ast_node* current_term;\n bel_ast_node* current_nv;\n bel_ast_node* arg;\n bel_ast_node* next_arg;\n bel_ast* ast;\n bel_arg_stack* arg_stack;\n int vi;\n\n p = line;\n pe = line + strlen(line);\n current_term = NULL;\n current_nv = NULL;\n arg = NULL;\n next_arg = NULL;\n ast = bel_new_ast();\n arg_stack = stack_init(ARG_STACK_SIZE);\n vi = 0;\n\n %%{\n action vi {\n value[vi++] = fc;\n }\n\n action FX {\n current_term = bel_new_ast_node_token(TOKEN_TERM);\n current_term->token->left = bel_new_ast_node_value(VALUE_FX, value);\n\n \/\/ Set term as AST root; on first term\n if (!ast->root) {\n ast->root = current_term;\n }\n\n \/\/ Create Nil argument as a placeholder; add to stack\n arg = bel_new_ast_node_token(TOKEN_ARG);\n arg->token->left = bel_new_ast_node_token(TOKEN_NIL);\n arg->token->right = bel_new_ast_node_token(TOKEN_NIL);\n stack_push(arg_stack, *arg);\n\n \/\/ Set as term argument\n current_term->token->right = arg;\n\n\t memset(value, '\\0', VALUE_SIZE);\n vi = 0;\n }\n\n action PFX {\n bel_ast_node* top = stack_peek(arg_stack);\n current_nv = bel_new_ast_node_token(TOKEN_NV);\n current_nv->token->left = bel_new_ast_node_value(VALUE_PFX, value);\n current_nv->token->right = bel_new_ast_node_value(VALUE_VAL, \"\");\n top->token->left = current_nv;\n\n next_arg = bel_new_ast_node_token(TOKEN_ARG);\n next_arg->token->left = bel_new_ast_node_token(TOKEN_NIL);\n next_arg->token->right = bel_new_ast_node_token(TOKEN_NIL);\n top->token->right = next_arg;\n stack_push(arg_stack, *next_arg);\n\n\t memset(value, '\\0', VALUE_SIZE);\n vi = 0;\n }\n\n action VAL {\n bel_ast_node* top = stack_peek(arg_stack);\n if (!current_nv) {\n current_nv = bel_new_ast_node_token(TOKEN_NV);\n current_nv->token->left = bel_new_ast_node_value(VALUE_PFX, \"\");\n current_nv->token->right = bel_new_ast_node_value(VALUE_VAL, value);\n top->token->left = current_nv;\n\n next_arg = bel_new_ast_node_token(TOKEN_ARG);\n next_arg->token->left = bel_new_ast_node_token(TOKEN_NIL);\n next_arg->token->right = bel_new_ast_node_token(TOKEN_NIL);\n top->token->right = next_arg;\n stack_push(arg_stack, *next_arg);\n } else {\n current_nv->token->right = bel_new_ast_node_value(VALUE_VAL, value);\n }\n\n current_nv = 0;\n\t memset(value, '\\0', VALUE_SIZE);\n vi = 0;\n }\n\n SP = ' ';\n O_PAREN = '(';\n C_PAREN = ')';\n COLON = ':';\n IDENT = [a-zA-Z0-9_]+;\n STRING = ('\"' ('\\\\\\\"' | [^\"])* '\"');\n FUNCTION = ('proteinAbundance'|'p'|'rnaAbundance'|'r'|'abundance'|'a'|'microRNAAbundance'|'m'|'geneAbundance'|'g'|'biologicalProcess'|'bp'|'pathology'|'path'|'complexAbundance'|'complex'|'translocation'|'tloc'|'cellSecretion'|'sec'|'cellSurfaceExpression'|'surf'|'reaction'|'rxn'|'compositeAbundance'|'composite'|'fusion'|'fus'|'degradation'|'deg'|'molecularActivity'|'act'|'catalyticActivity'|'cat'|'kinaseActivity'|'kin'|'phosphataseActivity'|'phos'|'peptidaseActivity'|'pep'|'ribosylationActivity'|'ribo'|'transcriptionalActivity'|'tscript'|'transportActivity'|'tport'|'gtpBoundActivity'|'gtp'|'chaperoneActivity'|'chap'|'proteinModification'|'pmod'|'substitution'|'sub'|'truncation'|'trunc'|'reactants'|'products'|'list');\n# FUNCTION = ('p'|'r'|'a'|'m'|'g'|'bp');\n\n# term =\n# FUNCTION $vi %FX <>lerr(FX) O_PAREN C_PAREN;\n term =\n FUNCTION $vi %FX\n O_PAREN \n (\n (IDENT $vi ':')? @PFX (STRING $vi | IDENT $vi) %VAL \n )\n (\n SP* ',' SP*\n (IDENT $vi ':')? @PFX (STRING $vi | IDENT $vi) %VAL\n )*\n C_PAREN;\n\n main :=\n term;\n\n # Initialize and execute.\n write init;\n write exec;\n }%%\n\n if (arg_stack) {\n stack_destroy(arg_stack);\n }\n\n return ast;\n};\n\nint main(int argc, char *argv[]) {\n FILE *input;\n int len;\n char line[BUFSIZE];\n char value[VALUE_SIZE];\n\n if (argc == 2) {\n input = fopen(argv[1], \"rb\");\n } else {\n input = stdin;\n }\n\n while (fgets(line, BUFSIZE, input) != NULL) {\n len = strlen(line);\n if (line[len - 1] == '\\n') {\n line[len - 1] = '\\0';\n }\n\n\t memset(value, '\\0', VALUE_SIZE);\n\t fprintf(stdout, \"parsing line -> %s\\n\", line);\n bel_ast* tree = parse_term(line, value);\n\n if (!tree->root) {\n fprintf(stderr, \"parse failed\\n\");\n exit(1);\n }\n\n bel_print_ast_flat(tree);\n bel_free_ast(tree);\n }\n fclose(input);\n return 0;\n}\n\n\/\/ vim: ft=c sw=4 ts=4 sts=4 expandtab\n","old_contents":"\/*\n * Parses BEL terms.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"belparser.h\"\n\n%%{\n machine set;\n write data;\n}%%\n\nbel_arg_stack* stack_init(int max) {\n bel_arg_stack* stack;\n bel_ast_node* contents;\n\n stack = (bel_arg_stack *) malloc(sizeof(bel_arg_stack));\n contents = (bel_ast_node *) malloc(sizeof(bel_ast_node) * max);\n\n if (contents == NULL) {\n fprintf(stderr, \"Insufficient memory to initialize stack.\\n\");\n exit(1); \/* Exit, returning error code. *\/\n }\n\n stack->top = -1;\n stack->max = max;\n stack->contents = contents;\n\n return stack;\n};\n\nvoid stack_destroy(bel_arg_stack* stack) {\n free(stack->contents);\n stack->top = -1;\n stack->max = 0;\n stack->contents = NULL;\n};\n\nbel_ast_node* stack_peek(bel_arg_stack* stack) {\n if (stack_is_full(stack)) {\n fprintf(stderr, \"Can't push element on stack: stack is full.\\n\");\n exit(1);\n }\n\n bel_ast_node* top = &(stack->contents[stack->top]);\n return top;\n};\n\nvoid stack_push(bel_arg_stack* stack, bel_ast_node element) {\n if (stack_is_full(stack)) {\n fprintf(stderr, \"Can't push element on stack: stack is full.\\n\");\n exit(1);\n }\n\n stack->contents[++stack->top] = element;\n};\n\nbel_ast_node stack_pop(bel_arg_stack* stack) {\n if (stack_is_empty(stack)) {\n fprintf(stderr, \"Can't pop element from stack: stack is empty.\\n\");\n exit(1);\n }\n\n return stack->contents[stack->top--];\n};\n\nint stack_is_empty(bel_arg_stack* stack) {\n return stack->top < 0;\n};\n\nint stack_is_full(bel_arg_stack* stack) {\n return stack->top >= stack->max - 1;\n};\n\nbel_ast_node* bel_new_ast_node_token(bel_ast_token_type type) {\n bel_ast_node* node;\n node = malloc(sizeof(bel_ast_node));\n node->token = malloc(sizeof(bel_ast_node_token));\n node->token->type = TOKEN;\n node->token->ttype = type;\n node->token->left = NULL;\n node->token->right = NULL;\n return node;\n};\n\nbel_ast_node* bel_new_ast_node_value(bel_ast_value_type type, char value[]) {\n bel_ast_node* node;\n char* copy_value;\n\n if (value) {\n copy_value = (char *) malloc(sizeof(value));\n strncpy(copy_value, value, sizeof(value));\n } else {\n copy_value = NULL;\n }\n\n node = malloc(sizeof(bel_ast_node));\n node->value = malloc(sizeof(bel_ast_node_value));\n node->value->type = VALUE;\n node->value->vtype = type;\n node->value->value = copy_value;\n return node;\n};\n\nbel_ast* bel_new_ast() {\n bel_ast* ast;\n ast = malloc(sizeof(bel_ast));\n ast->root = NULL;\n return ast;\n};\n\nvoid bel_free_ast(bel_ast* ast) {\n if (!ast) {\n return;\n }\n bel_free_ast_node(ast->root);\n free(ast);\n};\n\nvoid bel_free_ast_node(bel_ast_node* node) {\n if (node->type_info->type == TOKEN && node->token->ttype != TOKEN_NIL) {\n fprintf(stdout, \"free token: %u\\n\", node->type_info->ttype);\n bel_free_ast_node(node->token->left);\n bel_free_ast_node(node->token->right);\n }\n free(node);\n};\n\nvoid bel_print_ast_node(bel_ast_node* node) {\n if (!node) {\n return;\n }\n\n switch(node->type_info->type) {\n case TOKEN:\n switch(node->type_info->ttype) {\n case TOKEN_ARG:\n fprintf(stdout, \"ARG\\n\");\n break;\n case TOKEN_NIL:\n fprintf(stdout, \"NIL\\n\");\n break;\n case TOKEN_NV:\n fprintf(stdout, \"NV\\n\");\n break;\n case TOKEN_TERM:\n fprintf(stdout, \"TERM\\n\");\n break;\n }\n bel_print_ast_node(node->token->left);\n bel_print_ast_node(node->token->right);\n break;\n case VALUE:\n switch(node->type_info->vtype) {\n case VALUE_FX:\n fprintf(stdout, \"fx(%s)\\n\", node->value->value);\n break;\n case VALUE_NIL:\n fprintf(stdout, \"nil(%s)\\n\", node->value->value);\n break;\n case VALUE_PFX:\n fprintf(stdout, \"pfx(%s)\\n\", node->value->value);\n break;\n case VALUE_VAL:\n fprintf(stdout, \"val(%s)\\n\", node->value->value);\n break;\n }\n break;\n }\n}\n\nvoid bel_print_ast(bel_ast* ast) {\n if (!ast) {\n return;\n }\n bel_print_ast_node(ast->root);\n fprintf(stdout, \"\\n\");\n};\n\n#define VALUE_SIZE 128\n#define BUFSIZE 1024 * 32 \/\/ 32 kilobytes\n#define ARG_STACK_SIZE 100\n\nbel_ast* parse_term(char* line, char value[]) {\n int cs;\n char *p;\n char *pe;\n bel_ast_node* current_term;\n bel_ast_node* current_nv;\n bel_ast_node* arg;\n bel_ast_node* next_arg;\n bel_ast* ast;\n bel_arg_stack* arg_stack;\n int vi;\n\n p = line;\n pe = line + strlen(line);\n current_term = NULL;\n current_nv = NULL;\n arg = NULL;\n next_arg = NULL;\n ast = bel_new_ast();\n arg_stack = stack_init(ARG_STACK_SIZE);\n vi = 0;\n\n %%{\n action vi {\n value[vi++] = fc;\n }\n\n action FX {\n current_term = bel_new_ast_node_token(TOKEN_TERM);\n current_term->token->left = bel_new_ast_node_value(VALUE_FX, value);\n\n \/\/ Set term as AST root; on first term\n if (!ast->root) {\n ast->root = current_term;\n }\n\n \/\/ Create Nil argument as a placeholder; add to stack\n arg = bel_new_ast_node_token(TOKEN_ARG);\n arg->token->left = bel_new_ast_node_token(TOKEN_NIL);\n arg->token->right = bel_new_ast_node_token(TOKEN_NIL);\n stack_push(arg_stack, *arg);\n\n \/\/ Set as term argument\n current_term->token->right = arg;\n\n\t memset(value, '\\0', VALUE_SIZE);\n vi = 0;\n }\n\n action PFX {\n bel_ast_node* top = stack_peek(arg_stack);\n current_nv = bel_new_ast_node_token(TOKEN_NV);\n current_nv->token->left = bel_new_ast_node_value(VALUE_PFX, value);\n current_nv->token->right = bel_new_ast_node_value(VALUE_VAL, \"\");\n top->token->left = current_nv;\n\n next_arg = bel_new_ast_node_token(TOKEN_ARG);\n next_arg->token->left = bel_new_ast_node_token(TOKEN_NIL);\n next_arg->token->right = bel_new_ast_node_token(TOKEN_NIL);\n top->token->right = next_arg;\n stack_push(arg_stack, *next_arg);\n\n\t memset(value, '\\0', VALUE_SIZE);\n vi = 0;\n }\n\n action VAL {\n bel_ast_node* top = stack_peek(arg_stack);\n if (!current_nv) {\n current_nv = bel_new_ast_node_token(TOKEN_NV);\n current_nv->token->left = bel_new_ast_node_value(VALUE_PFX, \"\");\n current_nv->token->right = bel_new_ast_node_value(VALUE_VAL, value);\n top->token->left = current_nv;\n\n next_arg = bel_new_ast_node_token(TOKEN_ARG);\n next_arg->token->left = bel_new_ast_node_token(TOKEN_NIL);\n next_arg->token->right = bel_new_ast_node_token(TOKEN_NIL);\n top->token->right = next_arg;\n stack_push(arg_stack, *next_arg);\n } else {\n current_nv->token->right = bel_new_ast_node_value(VALUE_VAL, value);\n }\n\n current_nv = 0;\n\t memset(value, '\\0', VALUE_SIZE);\n vi = 0;\n }\n\n SP = ' ';\n O_PAREN = '(';\n C_PAREN = ')';\n COLON = ':';\n IDENT = [a-zA-Z0-9_]+;\n STRING = ('\"' ('\\\\\\\"' | [^\"])* '\"');\n FUNCTION = ('proteinAbundance'|'p'|'rnaAbundance'|'r'|'abundance'|'a'|'microRNAAbundance'|'m'|'geneAbundance'|'g'|'biologicalProcess'|'bp'|'pathology'|'path'|'complexAbundance'|'complex'|'translocation'|'tloc'|'cellSecretion'|'sec'|'cellSurfaceExpression'|'surf'|'reaction'|'rxn'|'compositeAbundance'|'composite'|'fusion'|'fus'|'degradation'|'deg'|'molecularActivity'|'act'|'catalyticActivity'|'cat'|'kinaseActivity'|'kin'|'phosphataseActivity'|'phos'|'peptidaseActivity'|'pep'|'ribosylationActivity'|'ribo'|'transcriptionalActivity'|'tscript'|'transportActivity'|'tport'|'gtpBoundActivity'|'gtp'|'chaperoneActivity'|'chap'|'proteinModification'|'pmod'|'substitution'|'sub'|'truncation'|'trunc'|'reactants'|'products'|'list');\n# FUNCTION = ('p'|'r'|'a'|'m'|'g'|'bp');\n\n# term =\n# FUNCTION $vi %FX <>lerr(FX) O_PAREN C_PAREN;\n term =\n FUNCTION $vi %FX\n O_PAREN \n (\n (IDENT $vi ':')? @PFX (STRING $vi | IDENT $vi) %VAL \n )\n (\n SP* ',' SP*\n (IDENT $vi ':')? @PFX (STRING $vi | IDENT $vi) %VAL\n )*\n C_PAREN;\n\n main :=\n term;\n\n # Initialize and execute.\n write init;\n write exec;\n }%%\n\n if (arg_stack) {\n stack_destroy(arg_stack);\n }\n\n return ast;\n};\n\nint main(int argc, char *argv[]) {\n FILE *input;\n int len;\n char line[BUFSIZE];\n char value[VALUE_SIZE];\n\n if (argc == 2) {\n input = fopen(argv[1], \"rb\");\n } else {\n input = stdin;\n }\n\n while (fgets(line, BUFSIZE, input) != NULL) {\n len = strlen(line);\n if (line[len - 1] == '\\n') {\n line[len - 1] = '\\0';\n }\n\n\t memset(value, '\\0', VALUE_SIZE);\n\t fprintf(stdout, \"parsing line -> %s\\n\", line);\n bel_ast* tree = parse_term(line, value);\n\n if (!tree->root) {\n fprintf(stderr, \"parse failed\\n\");\n exit(1);\n }\n bel_print_ast(tree);\n bel_free_ast(tree);\n }\n fclose(input);\n return 0;\n}\n\n\/\/ vim: ft=c sw=4 ts=4 sts=4 expandtab\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"6142b49d2ce5f6fae5d0cd00e4ca7683689b76d7","subject":"fix ugly p counter at end","message":"fix ugly p counter at end\n","repos":"razum2um\/params_tree","old_file":"hello_world.rl","new_file":"hello_world.rl","new_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ]) >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER? @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n #@hash.inspect\n #@hash_stack.inspect\n @hash_stack.first\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\ns = \"default(all,usadasdid(zczxc(pio(xqwe)),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\nputs s\nputs ParamsTree::Parser.new.process s\n","old_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ])+ >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); p + 1 == pe and @hash[key] = {}; };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n puts @hash_stack.inspect\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\nParamsTree::Parser.new.process \"default(all,usadasdid(zczxc(pio(xqwe)),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"9367b74a3dca3c0d9fca7382030b5b80ba7073ea","subject":"Check for integer overflow in content-length.","message":"Check for integer overflow in content-length.\n\nAlso only allow single digits in the HTTP version.\nNeed multiple digits? Convince me.\n","repos":"OpenMusicKontrollers\/chimaerad,tjweir\/http-parser,OpenMusicKontrollers\/chimaerad,tmm1\/http-parser,humbletim\/http-parser,OpenMusicKontrollers\/chimaerad,arsane\/http-parser,ignacio\/http-parser,tml\/http-parser,mopemope\/http-parser,apaprocki\/http-parser,OpenMusicKontrollers\/chimaerad,TooTallNate\/http-parser,nikicat\/http-parser,OpenMusicKontrollers\/chimaerad,OpenMusicKontrollers\/chimaerad,thomaslee\/http-parser","old_file":"http_parser.rl","new_file":"http_parser.rl","new_contents":"\/* Copyright (c) 2008, 2009 Ryan Dahl (ry@tinyclouds.org)\n * Based on Zed Shaw's Mongrel, copyright (c) Zed A. Shaw\n *\n * All rights reserved.\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n *\/\n#include \"http_parser.h\"\n#include \n#ifndef NDEBUG\n# include \n#endif\n\nstatic int unhex[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n };\n#define TRUE 1\n#define FALSE 0\n#define MIN(a,b) (a < b ? a : b)\n#define NULL (void*)(0)\n\n#define MAX_FIELD_SIZE 80*1024\n\n#define REMAINING (pe - p)\n#define CALLBACK(FOR) \\\ndo { \\\n if (parser->FOR##_mark) { \\\n parser->FOR##_size += p - parser->FOR##_mark; \\\n if (parser->FOR##_size > MAX_FIELD_SIZE) { \\\n parser->buffer_overflow = TRUE; \\\n return 0; \\\n } \\\n if (parser->on_##FOR) { \\\n callback_return_value = parser->on_##FOR(parser, \\\n parser->FOR##_mark, \\\n p - parser->FOR##_mark); \\\n } \\\n } \\\n} while(0)\n\n#define RESET_PARSER(parser) \\\n parser->chunk_size = 0; \\\n parser->eating = 0; \\\n parser->header_field_mark = NULL; \\\n parser->header_value_mark = NULL; \\\n parser->query_string_mark = NULL; \\\n parser->path_mark = NULL; \\\n parser->uri_mark = NULL; \\\n parser->fragment_mark = NULL; \\\n parser->status_code = 0; \\\n parser->method = 0; \\\n parser->transfer_encoding = HTTP_IDENTITY; \\\n parser->version_major = 0; \\\n parser->version_minor = 0; \\\n parser->keep_alive = -1; \\\n parser->content_length = 0; \\\n parser->body_read = 0; \n\n#define END_REQUEST \\\ndo { \\\n if (parser->on_message_complete) { \\\n callback_return_value = \\\n parser->on_message_complete(parser); \\\n } \\\n RESET_PARSER(parser); \\\n} while (0)\n\n#define SKIP_BODY(nskip) \\\ndo { \\\n tmp = (nskip); \\\n if (parser->on_body && tmp > 0) { \\\n callback_return_value = parser->on_body(parser, p, tmp); \\\n } \\\n if (callback_return_value == 0) { \\\n p += tmp; \\\n parser->body_read += tmp; \\\n parser->chunk_size -= tmp; \\\n if (0 == parser->chunk_size) { \\\n parser->eating = FALSE; \\\n if (parser->transfer_encoding == HTTP_IDENTITY) { \\\n END_REQUEST; \\\n } \\\n } else { \\\n parser->eating = TRUE; \\\n } \\\n } \\\n} while (0)\n\n%%{\n machine http_parser;\n\n action mark_header_field {\n parser->header_field_mark = p;\n parser->header_field_size = 0;\n }\n\n action mark_header_value {\n parser->header_value_mark = p;\n parser->header_value_size = 0;\n }\n\n action mark_fragment {\n parser->fragment_mark = p;\n parser->fragment_size = 0;\n }\n\n action mark_query_string {\n parser->query_string_mark = p;\n parser->query_string_size = 0;\n }\n\n action mark_request_path {\n parser->path_mark = p;\n parser->path_size = 0;\n }\n\n action mark_request_uri {\n parser->uri_mark = p;\n parser->uri_size = 0;\n }\n\n action header_field {\n CALLBACK(header_field);\n if (callback_return_value != 0) fbreak;\n parser->header_field_mark = NULL;\n parser->header_field_size = 0;\n }\n\n action header_value {\n CALLBACK(header_value);\n if (callback_return_value != 0) fbreak;\n parser->header_value_mark = NULL;\n parser->header_value_size = 0;\n }\n\n action request_uri { \n CALLBACK(uri);\n if (callback_return_value != 0) fbreak;\n parser->uri_mark = NULL;\n parser->uri_size = 0;\n }\n\n action fragment { \n CALLBACK(fragment);\n if (callback_return_value != 0) fbreak;\n parser->fragment_mark = NULL;\n parser->fragment_size = 0;\n }\n\n action query_string { \n CALLBACK(query_string);\n if (callback_return_value != 0) fbreak;\n parser->query_string_mark = NULL;\n parser->query_string_size = 0;\n }\n\n action request_path {\n CALLBACK(path);\n if (callback_return_value != 0) fbreak;\n parser->path_mark = NULL;\n parser->path_size = 0;\n }\n\n action headers_complete {\n if(parser->on_headers_complete) {\n callback_return_value = parser->on_headers_complete(parser);\n if (callback_return_value != 0) fbreak;\n }\n }\n\n action begin_message {\n if(parser->on_message_begin) {\n callback_return_value = parser->on_message_begin(parser);\n if (callback_return_value != 0) fbreak;\n }\n }\n\n action content_length {\n if (parser->content_length > INT_MAX) {\n parser->buffer_overflow = TRUE;\n return 0;\n }\n parser->content_length *= 10;\n parser->content_length += *p - '0';\n }\n\n action status_code {\n parser->status_code *= 10;\n parser->status_code += *p - '0';\n }\n\n action use_identity_encoding { parser->transfer_encoding = HTTP_IDENTITY; }\n action use_chunked_encoding { parser->transfer_encoding = HTTP_CHUNKED; }\n\n action set_keep_alive { parser->keep_alive = TRUE; }\n action set_not_keep_alive { parser->keep_alive = FALSE; }\n\n action version_major {\n parser->version_major *= 10;\n parser->version_major += *p - '0';\n }\n\n action version_minor {\n parser->version_minor *= 10;\n parser->version_minor += *p - '0';\n }\n\n action add_to_chunk_size {\n parser->chunk_size *= 16;\n parser->chunk_size += unhex[(int)*p];\n }\n\n action skip_chunk_data {\n SKIP_BODY(MIN(parser->chunk_size, REMAINING));\n if (callback_return_value != 0) fbreak;\n\n fhold; \n if (parser->chunk_size > REMAINING) {\n fbreak;\n } else {\n fgoto chunk_end; \n }\n }\n\n action end_chunked_body {\n END_REQUEST;\n if (parser->type == HTTP_REQUEST) {\n fnext Requests;\n } else {\n fnext Responses;\n }\n }\n\n action body_logic {\n if (parser->transfer_encoding == HTTP_CHUNKED) {\n fnext ChunkedBody;\n } else {\n \/* this is pretty stupid. i'd prefer to combine this with skip_chunk_data *\/\n parser->chunk_size = parser->content_length;\n p += 1; \n\n SKIP_BODY(MIN(REMAINING, parser->content_length));\n if (callback_return_value != 0) fbreak;\n\n fhold;\n if(parser->chunk_size > REMAINING) {\n fbreak;\n }\n }\n }\n\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" \n | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n quote = \"\\\"\";\n# qdtext = token -- \"\\\"\"; \n# quoted_pair = \"\\\" ascii;\n# quoted_string = \"\\\"\" (qdtext | quoted_pair )* \"\\\"\";\n\n# headers\n\n Method = ( \"COPY\" %{ parser->method = HTTP_COPY; }\n | \"DELETE\" %{ parser->method = HTTP_DELETE; }\n | \"GET\" %{ parser->method = HTTP_GET; }\n | \"HEAD\" %{ parser->method = HTTP_HEAD; }\n | \"LOCK\" %{ parser->method = HTTP_LOCK; }\n | \"MKCOL\" %{ parser->method = HTTP_MKCOL; }\n | \"MOVE\" %{ parser->method = HTTP_MOVE; }\n | \"OPTIONS\" %{ parser->method = HTTP_OPTIONS; }\n | \"POST\" %{ parser->method = HTTP_POST; }\n | \"PROPFIND\" %{ parser->method = HTTP_PROPFIND; }\n | \"PROPPATCH\" %{ parser->method = HTTP_PROPPATCH; }\n | \"PUT\" %{ parser->method = HTTP_PUT; }\n | \"TRACE\" %{ parser->method = HTTP_TRACE; }\n | \"UNLOCK\" %{ parser->method = HTTP_UNLOCK; }\n ); # Not allowing extension methods\n\n HTTP_Version = \"HTTP\/\" digit $version_major \".\" digit $version_minor;\n\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n path = ( pchar+ ( \"\/\" pchar* )* ) ;\n query = ( uchar | reserved )* >mark_query_string %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = ( param ( \";\" param )* ) ;\n rel_path = ( path? (\";\" params)? ) ;\n absolute_path = ( \"\/\"+ rel_path ) >mark_request_path %request_path (\"?\" query)?;\n Request_URI = ( \"*\" | absolute_uri | absolute_path ) >mark_request_uri %request_uri;\n Fragment = ( uchar | reserved )* >mark_fragment %fragment;\n\n field_name = ( token -- \":\" )+;\n Field_Name = field_name >mark_header_field %header_field;\n\n field_value = ((any - \" \") any*)?;\n Field_Value = field_value >mark_header_value %header_value;\n\n hsep = \":\" \" \"*;\n header = (field_name hsep field_value) :> CRLF;\n Header = ( (\"Content-Length\"i hsep digit+ $content_length)\n | (\"Connection\"i hsep \n ( \"Keep-Alive\"i %set_keep_alive\n | \"close\"i %set_not_keep_alive\n )\n )\n | (\"Transfer-Encoding\"i %use_chunked_encoding hsep \"identity\" %use_identity_encoding)\n | (Field_Name hsep Field_Value)\n ) :> CRLF;\n\n Headers = (Header)* :> CRLF @headers_complete;\n\n Request_Line = ( Method \" \" Request_URI (\"#\" Fragment)? \" \" HTTP_Version CRLF ) ;\n\n StatusCode = (digit digit digit) $status_code;\n ReasonPhrase = ascii+ -- (\"\\r\" | \"\\n\");\n StatusLine = HTTP_Version \" \" StatusCode \" \" ReasonPhrase CRLF;\n\n# chunked message\n trailing_headers = header*;\n #chunk_ext_val = token | quoted_string;\n chunk_ext_val = token*;\n chunk_ext_name = token*;\n chunk_extension = ( \";\" \" \"* chunk_ext_name (\"=\" chunk_ext_val)? )*;\n last_chunk = \"0\"+ chunk_extension CRLF;\n chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size;\n chunk_end = CRLF;\n chunk_body = any >skip_chunk_data;\n chunk_begin = chunk_size chunk_extension CRLF;\n chunk = chunk_begin chunk_body chunk_end;\n ChunkedBody := chunk* last_chunk trailing_headers CRLF @end_chunked_body;\n\n Request = (Request_Line Headers) >begin_message @body_logic;\n Response = (StatusLine Headers) >begin_message @body_logic;\n\n Requests := Request*;\n Responses := Response*;\n\n main := any >{\n fhold;\n if (parser->type == HTTP_REQUEST) {\n fgoto Requests;\n } else {\n fgoto Responses;\n }\n };\n\n}%%\n\n%% write data;\n\nvoid\nhttp_parser_init (http_parser *parser, enum http_parser_type type) \n{\n int cs = 0;\n %% write init;\n parser->cs = cs;\n parser->type = type;\n parser->buffer_overflow = 0;\n\n parser->on_message_begin = NULL;\n parser->on_path = NULL;\n parser->on_query_string = NULL;\n parser->on_uri = NULL;\n parser->on_header_field = NULL;\n parser->on_header_value = NULL;\n parser->on_headers_complete = NULL;\n parser->on_body = NULL;\n parser->on_message_complete = NULL;\n\n RESET_PARSER(parser);\n}\n\n\/** exec **\/\nsize_t\nhttp_parser_execute (http_parser *parser, const char *buffer, size_t len)\n{\n size_t tmp; \/\/ REMOVE ME this is extremely hacky\n int callback_return_value = 0;\n const char *p, *pe;\n int cs = parser->cs;\n\n p = buffer;\n pe = buffer+len;\n\n if (0 < parser->chunk_size && parser->eating) {\n \/* eat body *\/\n SKIP_BODY(MIN(len, parser->chunk_size));\n if (callback_return_value != 0) goto out;\n }\n\n if (parser->header_field_mark) parser->header_field_mark = buffer;\n if (parser->header_value_mark) parser->header_value_mark = buffer;\n if (parser->fragment_mark) parser->fragment_mark = buffer;\n if (parser->query_string_mark) parser->query_string_mark = buffer;\n if (parser->path_mark) parser->path_mark = buffer;\n if (parser->uri_mark) parser->uri_mark = buffer;\n\n %% write exec;\n\n parser->cs = cs;\n\n CALLBACK(header_field);\n CALLBACK(header_value);\n CALLBACK(fragment);\n CALLBACK(query_string);\n CALLBACK(path);\n CALLBACK(uri);\n\nout:\n assert(p <= pe && \"buffer overflow after parsing execute\");\n return(p - buffer);\n}\n\nint\nhttp_parser_has_error (http_parser *parser) \n{\n if (parser->buffer_overflow) return TRUE;\n return parser->cs == http_parser_error;\n}\n\nint\nhttp_parser_should_keep_alive (http_parser *parser)\n{\n if (parser->keep_alive == -1)\n if (parser->version_major == 1)\n return (parser->version_minor != 0);\n else if (parser->version_major == 0)\n return FALSE;\n else\n return TRUE;\n else\n return parser->keep_alive;\n}\n","old_contents":"\/* Copyright (c) 2008, 2009 Ryan Dahl (ry@tinyclouds.org)\n * Based on Zed Shaw's Mongrel, copyright (c) Zed A. Shaw\n *\n * All rights reserved.\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n *\/\n#include \"http_parser.h\"\n#ifndef NDEBUG\n# include \n#endif\n\nstatic int unhex[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n };\n#define TRUE 1\n#define FALSE 0\n#define MIN(a,b) (a < b ? a : b)\n#define NULL (void*)(0)\n\n#define MAX_FIELD_SIZE 80*1024\n\n#define REMAINING (pe - p)\n#define CALLBACK(FOR) \\\ndo { \\\n if (parser->FOR##_mark) { \\\n parser->FOR##_size += p - parser->FOR##_mark; \\\n if (parser->FOR##_size > MAX_FIELD_SIZE) { \\\n parser->buffer_overflow = TRUE; \\\n return 0; \\\n } \\\n if (parser->on_##FOR) { \\\n callback_return_value = parser->on_##FOR(parser, \\\n parser->FOR##_mark, \\\n p - parser->FOR##_mark); \\\n } \\\n } \\\n} while(0)\n\n#define RESET_PARSER(parser) \\\n parser->chunk_size = 0; \\\n parser->eating = 0; \\\n parser->header_field_mark = NULL; \\\n parser->header_value_mark = NULL; \\\n parser->query_string_mark = NULL; \\\n parser->path_mark = NULL; \\\n parser->uri_mark = NULL; \\\n parser->fragment_mark = NULL; \\\n parser->status_code = 0; \\\n parser->method = 0; \\\n parser->transfer_encoding = HTTP_IDENTITY; \\\n parser->version_major = 0; \\\n parser->version_minor = 0; \\\n parser->keep_alive = -1; \\\n parser->content_length = 0; \\\n parser->body_read = 0; \n\n#define END_REQUEST \\\ndo { \\\n if (parser->on_message_complete) { \\\n callback_return_value = \\\n parser->on_message_complete(parser); \\\n } \\\n RESET_PARSER(parser); \\\n} while (0)\n\n#define SKIP_BODY(nskip) \\\ndo { \\\n tmp = (nskip); \\\n if (parser->on_body && tmp > 0) { \\\n callback_return_value = parser->on_body(parser, p, tmp); \\\n } \\\n if (callback_return_value == 0) { \\\n p += tmp; \\\n parser->body_read += tmp; \\\n parser->chunk_size -= tmp; \\\n if (0 == parser->chunk_size) { \\\n parser->eating = FALSE; \\\n if (parser->transfer_encoding == HTTP_IDENTITY) { \\\n END_REQUEST; \\\n } \\\n } else { \\\n parser->eating = TRUE; \\\n } \\\n } \\\n} while (0)\n\n%%{\n machine http_parser;\n\n action mark_header_field {\n parser->header_field_mark = p;\n parser->header_field_size = 0;\n }\n\n action mark_header_value {\n parser->header_value_mark = p;\n parser->header_value_size = 0;\n }\n\n action mark_fragment {\n parser->fragment_mark = p;\n parser->fragment_size = 0;\n }\n\n action mark_query_string {\n parser->query_string_mark = p;\n parser->query_string_size = 0;\n }\n\n action mark_request_path {\n parser->path_mark = p;\n parser->path_size = 0;\n }\n\n action mark_request_uri {\n parser->uri_mark = p;\n parser->uri_size = 0;\n }\n\n action header_field {\n CALLBACK(header_field);\n if (callback_return_value != 0) fbreak;\n parser->header_field_mark = NULL;\n parser->header_field_size = 0;\n }\n\n action header_value {\n CALLBACK(header_value);\n if (callback_return_value != 0) fbreak;\n parser->header_value_mark = NULL;\n parser->header_value_size = 0;\n }\n\n action request_uri { \n CALLBACK(uri);\n if (callback_return_value != 0) fbreak;\n parser->uri_mark = NULL;\n parser->uri_size = 0;\n }\n\n action fragment { \n CALLBACK(fragment);\n if (callback_return_value != 0) fbreak;\n parser->fragment_mark = NULL;\n parser->fragment_size = 0;\n }\n\n action query_string { \n CALLBACK(query_string);\n if (callback_return_value != 0) fbreak;\n parser->query_string_mark = NULL;\n parser->query_string_size = 0;\n }\n\n action request_path {\n CALLBACK(path);\n if (callback_return_value != 0) fbreak;\n parser->path_mark = NULL;\n parser->path_size = 0;\n }\n\n action headers_complete {\n if(parser->on_headers_complete) {\n callback_return_value = parser->on_headers_complete(parser);\n if (callback_return_value != 0) fbreak;\n }\n }\n\n action begin_message {\n if(parser->on_message_begin) {\n callback_return_value = parser->on_message_begin(parser);\n if (callback_return_value != 0) fbreak;\n }\n }\n\n action content_length {\n parser->content_length *= 10;\n parser->content_length += *p - '0';\n }\n\n action status_code {\n parser->status_code *= 10;\n parser->status_code += *p - '0';\n }\n\n action use_identity_encoding { parser->transfer_encoding = HTTP_IDENTITY; }\n action use_chunked_encoding { parser->transfer_encoding = HTTP_CHUNKED; }\n\n action set_keep_alive { parser->keep_alive = TRUE; }\n action set_not_keep_alive { parser->keep_alive = FALSE; }\n\n action version_major {\n parser->version_major *= 10;\n parser->version_major += *p - '0';\n }\n\n action version_minor {\n parser->version_minor *= 10;\n parser->version_minor += *p - '0';\n }\n\n action add_to_chunk_size {\n parser->chunk_size *= 16;\n parser->chunk_size += unhex[(int)*p];\n }\n\n action skip_chunk_data {\n SKIP_BODY(MIN(parser->chunk_size, REMAINING));\n if (callback_return_value != 0) fbreak;\n\n fhold; \n if (parser->chunk_size > REMAINING) {\n fbreak;\n } else {\n fgoto chunk_end; \n }\n }\n\n action end_chunked_body {\n END_REQUEST;\n if (parser->type == HTTP_REQUEST) {\n fnext Requests;\n } else {\n fnext Responses;\n }\n }\n\n action body_logic {\n if (parser->transfer_encoding == HTTP_CHUNKED) {\n fnext ChunkedBody;\n } else {\n \/* this is pretty stupid. i'd prefer to combine this with skip_chunk_data *\/\n parser->chunk_size = parser->content_length;\n p += 1; \n\n SKIP_BODY(MIN(REMAINING, parser->content_length));\n if (callback_return_value != 0) fbreak;\n\n fhold;\n if(parser->chunk_size > REMAINING) {\n fbreak;\n }\n }\n }\n\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" \n | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n quote = \"\\\"\";\n# qdtext = token -- \"\\\"\"; \n# quoted_pair = \"\\\" ascii;\n# quoted_string = \"\\\"\" (qdtext | quoted_pair )* \"\\\"\";\n\n# headers\n\n Method = ( \"COPY\" %{ parser->method = HTTP_COPY; }\n | \"DELETE\" %{ parser->method = HTTP_DELETE; }\n | \"GET\" %{ parser->method = HTTP_GET; }\n | \"HEAD\" %{ parser->method = HTTP_HEAD; }\n | \"LOCK\" %{ parser->method = HTTP_LOCK; }\n | \"MKCOL\" %{ parser->method = HTTP_MKCOL; }\n | \"MOVE\" %{ parser->method = HTTP_MOVE; }\n | \"OPTIONS\" %{ parser->method = HTTP_OPTIONS; }\n | \"POST\" %{ parser->method = HTTP_POST; }\n | \"PROPFIND\" %{ parser->method = HTTP_PROPFIND; }\n | \"PROPPATCH\" %{ parser->method = HTTP_PROPPATCH; }\n | \"PUT\" %{ parser->method = HTTP_PUT; }\n | \"TRACE\" %{ parser->method = HTTP_TRACE; }\n | \"UNLOCK\" %{ parser->method = HTTP_UNLOCK; }\n ); # Not allowing extension methods\n\n HTTP_Version = \"HTTP\/\" digit+ $version_major \".\" digit+ $version_minor;\n\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n path = ( pchar+ ( \"\/\" pchar* )* ) ;\n query = ( uchar | reserved )* >mark_query_string %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = ( param ( \";\" param )* ) ;\n rel_path = ( path? (\";\" params)? ) ;\n absolute_path = ( \"\/\"+ rel_path ) >mark_request_path %request_path (\"?\" query)?;\n Request_URI = ( \"*\" | absolute_uri | absolute_path ) >mark_request_uri %request_uri;\n Fragment = ( uchar | reserved )* >mark_fragment %fragment;\n\n field_name = ( token -- \":\" )+;\n Field_Name = field_name >mark_header_field %header_field;\n\n field_value = ((any - \" \") any*)?;\n Field_Value = field_value >mark_header_value %header_value;\n\n hsep = \":\" \" \"*;\n header = (field_name hsep field_value) :> CRLF;\n Header = ( (\"Content-Length\"i hsep digit+ $content_length)\n | (\"Connection\"i hsep \n ( \"Keep-Alive\"i %set_keep_alive\n | \"close\"i %set_not_keep_alive\n )\n )\n | (\"Transfer-Encoding\"i %use_chunked_encoding hsep \"identity\" %use_identity_encoding)\n | (Field_Name hsep Field_Value)\n ) :> CRLF;\n\n Headers = (Header)* :> CRLF @headers_complete;\n\n Request_Line = ( Method \" \" Request_URI (\"#\" Fragment)? \" \" HTTP_Version CRLF ) ;\n\n StatusCode = (digit digit digit) $status_code;\n ReasonPhrase = ascii+ -- (\"\\r\" | \"\\n\");\n StatusLine = HTTP_Version \" \" StatusCode \" \" ReasonPhrase CRLF;\n\n# chunked message\n trailing_headers = header*;\n #chunk_ext_val = token | quoted_string;\n chunk_ext_val = token*;\n chunk_ext_name = token*;\n chunk_extension = ( \";\" \" \"* chunk_ext_name (\"=\" chunk_ext_val)? )*;\n last_chunk = \"0\"+ chunk_extension CRLF;\n chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size;\n chunk_end = CRLF;\n chunk_body = any >skip_chunk_data;\n chunk_begin = chunk_size chunk_extension CRLF;\n chunk = chunk_begin chunk_body chunk_end;\n ChunkedBody := chunk* last_chunk trailing_headers CRLF @end_chunked_body;\n\n Request = (Request_Line Headers) >begin_message @body_logic;\n Response = (StatusLine Headers) >begin_message @body_logic;\n\n Requests := Request*;\n Responses := Response*;\n\n main := any >{\n fhold;\n if (parser->type == HTTP_REQUEST) {\n fgoto Requests;\n } else {\n fgoto Responses;\n }\n };\n\n}%%\n\n%% write data;\n\nvoid\nhttp_parser_init (http_parser *parser, enum http_parser_type type) \n{\n int cs = 0;\n %% write init;\n parser->cs = cs;\n parser->type = type;\n parser->buffer_overflow = 0;\n\n parser->on_message_begin = NULL;\n parser->on_path = NULL;\n parser->on_query_string = NULL;\n parser->on_uri = NULL;\n parser->on_header_field = NULL;\n parser->on_header_value = NULL;\n parser->on_headers_complete = NULL;\n parser->on_body = NULL;\n parser->on_message_complete = NULL;\n\n RESET_PARSER(parser);\n}\n\n\/** exec **\/\nsize_t\nhttp_parser_execute (http_parser *parser, const char *buffer, size_t len)\n{\n size_t tmp; \/\/ REMOVE ME this is extremely hacky\n int callback_return_value = 0;\n const char *p, *pe;\n int cs = parser->cs;\n\n p = buffer;\n pe = buffer+len;\n\n if (0 < parser->chunk_size && parser->eating) {\n \/* eat body *\/\n SKIP_BODY(MIN(len, parser->chunk_size));\n if (callback_return_value != 0) goto out;\n }\n\n if (parser->header_field_mark) parser->header_field_mark = buffer;\n if (parser->header_value_mark) parser->header_value_mark = buffer;\n if (parser->fragment_mark) parser->fragment_mark = buffer;\n if (parser->query_string_mark) parser->query_string_mark = buffer;\n if (parser->path_mark) parser->path_mark = buffer;\n if (parser->uri_mark) parser->uri_mark = buffer;\n\n %% write exec;\n\n parser->cs = cs;\n\n CALLBACK(header_field);\n CALLBACK(header_value);\n CALLBACK(fragment);\n CALLBACK(query_string);\n CALLBACK(path);\n CALLBACK(uri);\n\nout:\n assert(p <= pe && \"buffer overflow after parsing execute\");\n return(p - buffer);\n}\n\nint\nhttp_parser_has_error (http_parser *parser) \n{\n if (parser->buffer_overflow) return TRUE;\n return parser->cs == http_parser_error;\n}\n\nint\nhttp_parser_should_keep_alive (http_parser *parser)\n{\n if (parser->keep_alive == -1)\n if (parser->version_major == 1)\n return (parser->version_minor != 0);\n else if (parser->version_major == 0)\n return FALSE;\n else\n return TRUE;\n else\n return parser->keep_alive;\n}\n","returncode":0,"stderr":"","license":"artistic-2.0","lang":"Ragel in Ruby Host"} {"commit":"98ea5fa3a07a6e9740648adb008e5cfeb8a789f5","subject":"Add header parsing to JavaParser","message":"Add header parsing to JavaParser","repos":"elabs\/stompede,elabs\/stompede,elabs\/stomp_parser,elabs\/stomp_parser","old_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n \/*mark_message_size = 0;*\/\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n \/*VALUE length = rb_funcall(mark_message, g_content_length, 0);*\/\n \/*if ( ! NIL_P(length)) {*\/\n \/* mark_content_length = NUM2LONG(length);*\/\n \/*} else {*\/\n \/* mark_content_length = -1;*\/\n \/*}*\/\n }\n\n action write_body {\n \/*rb_funcall(mark_message, g_write_body, 1, MARK_STR_NEW());*\/\n \/*mark = NULL;*\/\n }\n\n action consume_null {\n false\n \/*((mark_content_length != -1) && (MARK_LEN < mark_content_length))*\/\n }\n\n action consume_octet {\n true\n \/*((mark_content_length == -1) || (MARK_LEN < mark_content_length))*\/\n }\n\n action check_message_size {\n \/*mark_message_size += 1;*\/\n \/*if (mark_message_size > max_message_size) {*\/\n \/* rb_raise(eMessageSizeExceeded, \"\");*\/\n \/*}*\/\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n \/\/ RaiseException error = context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(\"build_parse_error\");\n \/\/ throw error;\n }\n\n return context.nil;\n }\n}\n","old_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n \/*mark_message_size = 0;*\/\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n \/*mark_key = MARK_STR_NEW();*\/\n \/*mark = NULL;*\/\n }\n\n action write_header {\n \/*rb_funcall(mark_message, g_write_header, 2, mark_key, MARK_STR_NEW());*\/\n \/*mark_key = Qnil;*\/\n \/*mark = NULL;*\/\n }\n\n action finish_headers {\n \/*VALUE length = rb_funcall(mark_message, g_content_length, 0);*\/\n \/*if ( ! NIL_P(length)) {*\/\n \/* mark_content_length = NUM2LONG(length);*\/\n \/*} else {*\/\n \/* mark_content_length = -1;*\/\n \/*}*\/\n }\n\n action write_body {\n \/*rb_funcall(mark_message, g_write_body, 1, MARK_STR_NEW());*\/\n \/*mark = NULL;*\/\n }\n\n action consume_null {\n false\n \/*((mark_content_length != -1) && (MARK_LEN < mark_content_length))*\/\n }\n\n action consume_octet {\n true\n \/*((mark_content_length == -1) || (MARK_LEN < mark_content_length))*\/\n }\n\n action check_message_size {\n \/*mark_message_size += 1;*\/\n \/*if (mark_message_size > max_message_size) {*\/\n \/* rb_raise(eMessageSizeExceeded, \"\");*\/\n \/*}*\/\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n \/\/ RaiseException error = context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(\"build_parse_error\");\n \/\/ throw error;\n }\n\n return context.nil;\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f14b4674cdbebc19626e29865a1e805846589bf9","subject":"minor code cleanup","message":"minor code cleanup\n\nAllocate scanners for included files on the heap. Consistent with the main\nline.\n","repos":"timoc\/colm,timoc\/colm,timoc\/colm,timoc\/colm","old_file":"colm\/lmscan.rl","new_file":"colm\/lmscan.rl","new_contents":"\/*\n * Copyright 2006-2012 Adrian Thurston \n *\/\n\n\/* This file is part of Colm.\n *\n * Colm is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Colm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Colm; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"global.h\"\n#include \"lmscan.h\"\n#include \"lmparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\n\/\/#define PRINT_TOKENS\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid ColmScanner::sectionParseInit()\n{\n\t%% write init;\n}\n\nostream &ColmScanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool ColmScanner::recursiveInclude( const char *inclFileName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 )\n\t\t\treturn true;\n\t}\n\treturn false;\t\n}\n\nvoid ColmScanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = ts;\n\t\/\/cerr << \"adding \" << te - from << \" to column\" << endl;\n\tcolumn += te - from;\n\tlastnl = 0;\n}\n\nvoid ColmScanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid ColmScanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\nbool isAbsolutePath( const char *path )\n{\n\treturn path[0] == '\/';\n}\n\nifstream *ColmScanner::tryOpenInclude( char **pathChecks, long &found )\n{\n\tchar **check = pathChecks;\n\tifstream *inFile = new ifstream;\n\t\n\twhile ( *check != 0 ) {\n\t\tinFile->open( *check );\n\t\tif ( inFile->is_open() ) {\n\t\t\tfound = check - pathChecks;\n\t\t\treturn inFile;\n\t\t}\n\t\tcheck += 1;\n\t}\n\n\tfound = -1;\n\tdelete inFile;\n\treturn 0;\n}\n\nchar **ColmScanner::makeIncludePathChecks( const char *thisFileName, const char *fileName )\n{\n\tchar **checks = 0;\n\tlong nextCheck = 0;\n\tchar *data = strdup(fileName);\n\tlong length = strlen(fileName);\n\n\t\/* Absolute path? *\/\n\tif ( isAbsolutePath( data ) ) {\n\t\tchecks = new char*[2];\n\t\tchecks[nextCheck++] = data;\n\t}\n\telse {\n\t\t\/* Search from the the location of the current file. *\/\n\t\tchecks = new char *[2 + includePaths.length()];\n\t\tconst char *lastSlash = strrchr( thisFileName, '\/' );\n\t\tif ( lastSlash == 0 )\n\t\t\tchecks[nextCheck++] = data;\n\t\telse {\n\t\t\tlong givenPathLen = (lastSlash - thisFileName) + 1;\n\t\t\tlong checklen = givenPathLen + length;\n\t\t\tchar *check = new char[checklen+1];\n\t\t\tmemcpy( check, thisFileName, givenPathLen );\n\t\t\tmemcpy( check+givenPathLen, data, length );\n\t\t\tcheck[checklen] = 0;\n\t\t\tchecks[nextCheck++] = check;\n\t\t}\n\n\t\t\/* Search from the include paths given on the command line. *\/\n\t\tfor ( ArgsVector::Iter incp = includePaths; incp.lte(); incp++ ) {\n\t\t\tlong pathLen = strlen( *incp );\n\t\t\tlong checkLen = pathLen + 1 + length;\n\t\t\tchar *check = new char[checkLen+1];\n\t\t\tmemcpy( check, *incp, pathLen );\n\t\t\tcheck[pathLen] = '\/';\n\t\t\tmemcpy( check+pathLen+1, data, length );\n\t\t\tcheck[checkLen] = 0;\n\t\t\tchecks[nextCheck++] = check;\n\t\t}\n\t}\n\n\tchecks[nextCheck] = 0;\n\treturn checks;\n}\n\n\n%%{\n\tmachine section_parse;\n\timport \"lmparse.h\";\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_include\n\t{\n\t\tString src( lit, lit_len );\n\t\tString fileName;\n\t\tbool unused;\n\n\t\t\/* Need a location. *\/\n\t\tInputLoc here;\n\t\there.fileName = fileName;\n\t\there.line = line;\n\t\there.col = column;\n\n\t\tprepareLitString( fileName, unused, src, here );\n\t\tchar **checks = makeIncludePathChecks( this->fileName, fileName );\n\n\t\t\/* Open the input file for reading. *\/\n\t\tlong found = 0;\n\t\tifstream *inFile = tryOpenInclude( checks, found );\n\t\tif ( inFile == 0 ) {\n\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\tfileName << \" for reading\" << endl;\n\t\t}\n\t\telse {\n\t\t\t\/* Only proceed with the include if it was found. *\/\n\t\t\tif ( recursiveInclude( checks[found] ) )\n\t\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\n\t\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t\t * name then check if what we are including is already in the stack. *\/\n\t\t\tincludeStack.append( IncludeStackItem( checks[found] ) );\n\n\t\t\tColmScanner *scanner = new ColmScanner( fileName, *inFile, output, parser, includeDepth+1 );\n\t\t\tscanner->scan();\n\t\t\tdelete inFile;\n\n\t\t\t\/* Remove the last element (len-1) *\/\n\t\t\tincludeStack.remove( -1 );\n\n\t\t\tdelete scanner;\n\t\t}\n\t}\n\n\tinclude_target = \n\t\tTK_Literal >clear_words @store_lit;\n\n\tinclude_stmt =\n\t\t( KW_Include include_target ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction handle_token\n\t{\n\/\/\tcout << Parser_lelNames[type] << \" \";\n\/\/\tif ( start != 0 ) {\n\/\/\t\tcout.write( start, end-start );\n\/\/\t}\n\/\/\tcout << endl;\n\n\t\tInputLoc loc;\n\n\t\t#ifdef PRINT_TOKENS\n\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\tcerr << \" \" << toklen;\n\t\tif ( tokdata != 0 )\n\t\t\tcerr << \" \" << tokdata;\n\t\tcerr << endl;\n\t\t#endif\n\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = column;\n\n\t\tif ( tokdata != 0 && tokdata[toklen-1] == '\\n' )\n\t\t\tloc.line -= 1;\n\n\t\tparser->token( loc, type, tokdata, toklen );\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Include ) @handle_token;\n\n\tmain := ( \n\t\tinclude_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid ColmScanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\tint *eof = 0;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n}\n\nvoid ColmScanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t\/* Probably use: token( -1 ); *\/\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( TK_ReChar, '\\0' ); };\n\t\t'\\\\a' => { token( TK_ReChar, '\\a' ); };\n\t\t'\\\\b' => { token( TK_ReChar, '\\b' ); };\n\t\t'\\\\t' => { token( TK_ReChar, '\\t' ); };\n\t\t'\\\\n' => { token( TK_ReChar, '\\n' ); };\n\t\t'\\\\v' => { token( TK_ReChar, '\\v' ); };\n\t\t'\\\\f' => { token( TK_ReChar, '\\f' ); };\n\t\t'\\\\r' => { token( TK_ReChar, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( TK_ReChar, ts+1, te ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( TK_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( TK_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( TK_ReChar, ts, te ); };\n\n\t*|;\n\n\tregular_type := |*\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, ts, te ); };\n\t\thex_number => { token( TK_Hex, ts, te ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, ts, te ); };\n\n\t\t'[' => { token( TK_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( TK_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( '\/'); fret; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\n\t\t':>' => { token( TK_ColonGt ); };\n\t\t':>>' => { token( TK_ColonGtGt ); };\n\t\t'<:' => { token( TK_LtColon ); };\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n\n\tliteral_pattern := |*\n\t\t'\\\\' '0' { litBuf.append( '\\0' ); };\n\t\t'\\\\' 'a' { litBuf.append( '\\a' ); };\n\t\t'\\\\' 'b' { litBuf.append( '\\b' ); };\n\t\t'\\\\' 't' { litBuf.append( '\\t' ); };\n\t\t'\\\\' 'n' { litBuf.append( '\\n' ); };\n\t\t'\\\\' 'v' { litBuf.append( '\\v' ); };\n\t\t'\\\\' 'f' { litBuf.append( '\\f' ); };\n\t\t'\\\\' 'r' { litBuf.append( '\\r' ); };\n\n\t\t'\\\\' any {\n\t\t\tlitBuf.append( ts[1] );\n\t\t};\n\t\t'\"' => {\n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\tNL => {\n\t\t\tlitBuf.append( '\\n' );\n\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\tlitBuf.clear();\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\t'[' => { \n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '[' );\n\t\t\tfcall main;\n\t\t};\n\t\tany => { \n\t\t\tlitBuf.append( *ts );\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tmain := |*\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'commit' => { token( KW_Commit ); };\n\t\t'token' => { token( KW_Token ); };\n\t\t'literal' => { token( KW_Literal ); };\n\t\t'rl' => { token( KW_Rl ); };\n\t\t'def' => { token( KW_Def ); };\n\t\t'ignore' => { token( KW_Ignore ); };\n\t\t'construct' => { token( KW_Construct ); };\n\t\t'cons' => { token( KW_Construct ); };\n\t\t'new' => { token( KW_New ); };\n\t\t'if' => { token( KW_If ); };\n\t\t'reject' => { token( KW_Reject ); };\n\t\t'while' => { token( KW_While ); };\n\t\t'else' => { token( KW_Else ); };\n\t\t'elsif' => { token( KW_Elsif ); };\n\t\t'match' => { token( KW_Match ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'iter' => { token( KW_Iter ); };\n\t\t'prints' => { token( KW_PrintStream ); };\n\t\t'print' => { token( KW_Print ); };\n\t\t'print_xml_ac' => { token( KW_PrintXMLAC ); };\n\t\t'print_xml' => { token( KW_PrintXML ); };\n\t\t'namespace' => { token( KW_Namespace ); };\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'map' => { token( KW_Map ); };\n\t\t'list' => { token( KW_List ); };\n\t\t'vector' => { token( KW_Vector ); };\n\t\t'accum' => { token( KW_Accum ); };\n\t\t'parser' => { token( KW_Accum ); };\n\t\t'return' => { token( KW_Return ); };\n\t\t'break' => { token( KW_Break ); };\n\t\t'yield' => { token( KW_Yield ); };\n\t\t'typeid' => { token( KW_TypeId ); };\n\t\t'make_token' => { token( KW_MakeToken ); };\n\t\t'make_tree' => { token( KW_MakeTree ); };\n\t\t'reducefirst' => { token( KW_ReduceFirst ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'in' => { token( KW_In ); };\n\t\t'nil' => { token( KW_Nil ); };\n\t\t'true' => { token( KW_True ); };\n\t\t'false' => { token( KW_False ); };\n\t\t'parse' => { token( KW_Parse ); };\n\t\t'parse_stop' => { token( KW_ParseStop ); };\n\t\t'global' => { token( KW_Global ); };\n\t\t'export' => { token( KW_Export ); };\n\t\t'ptr' => { token( KW_Ptr ); };\n\t\t'ref' => { token( KW_Ref ); };\n\t\t'deref' => { token( KW_Deref ); };\n\t\t'require' => { token( KW_Require ); };\n\t\t'preeof' => { token( KW_Preeof ); };\n\t\t'left' => { token( KW_Left ); };\n\t\t'right' => { token( KW_Right ); };\n\t\t'nonassoc' => { token( KW_Nonassoc ); };\n\t\t'prec' => { token( KW_Prec ); };\n\t\t'include' => { token( KW_Include ); };\n\t\t'context' => { token( KW_Context ); };\n\t\t'alias' => { token( KW_Alias ); };\n\t\t'send' => { token( KW_Send ); };\n\t\t'ni' => { token( KW_Ni ); };\n\t\t'ci' => { token( KW_Ci ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\tnumber => { token( TK_Number, ts, te ); };\n\n\t\t'\/' => { \n\t\t\ttoken( '\/' ); \n\t\t\tif ( parser->enterRl )\n\t\t\t\tfcall regular_type;\n\t\t};\n\n\t\t\"~\" [^\\n]* NL => { \n\t\t\ttoken( '\"' );\n\t\t\ttoken( TK_LitPat, ts+1, te );\n\t\t\ttoken( '\"' );\n\t\t};\n\n\t\t\"'\" ([^'\\\\\\n] | '\\\\' (any | NL))* ( \"'\" | NL ) => {\n\t\t\ttoken( TK_Literal, ts, te );\n\t\t};\n\n\t\t'\"' => { \n\t\t\ttoken( '\"' );\n\t\t\tlitBuf.clear(); \n\t\t\tfcall literal_pattern;\n\t\t};\n\t\t'[' => { \n\t\t\ttoken( '[' ); \n\t\t\tfcall main;\n\t\t};\n\n\t\t']' => {\n\t\t\ttoken( ']' );\n\t\t\tif ( top > 0 )\n\t\t\t\tfret;\n\t\t};\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\t\t'==' => { token( TK_DoubleEql ); };\n\t\t'!=' => { token( TK_NotEql ); };\n\t\t'::' => { token( TK_DoubleColon ); };\n\t\t'<=' => { token( TK_LessEql ); };\n\t\t'>=' => { token( TK_GrtrEql ); };\n\t\t'->' => { token( TK_RightArrow ); };\n\t\t'&&' => { token( TK_AmpAmp ); };\n\t\t'||' => { token( TK_BarBar ); };\n\t\t'<<' => { token( TK_LtLt ); };\n\t\t\n\t\t('+' | '-' | '*' | '\/' | '(' | ')' | '@' | '$' | '^' ) => { token( *ts ); };\n\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n}%%\n\n%% write data;\n\nvoid ColmScanner::scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[32];\n\tbool execute = true;\n\n\tsectionParseInit();\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( ts != 0 )\n\t\t\t\tts = newbuf + ( ts - buf );\n\t\t\tte = newbuf + ( te - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\tchar *eof = 0;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"colm scanner error (metalanguage)\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = ts;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( ts != 0 )\n\t\t\t\tts -= shiftback;\n\t\t\tte -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\tdelete[] buf;\n}\n\nvoid ColmScanner::eof()\n{\n\tInputLoc loc;\n\tloc.fileName = \"\";\n\tloc.line = line;\n\tloc.col = 1;\n\tparser->token( loc, ColmParser_tk_eof, 0, 0 );\n}\n","old_contents":"\/*\n * Copyright 2006-2012 Adrian Thurston \n *\/\n\n\/* This file is part of Colm.\n *\n * Colm is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Colm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Colm; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"global.h\"\n#include \"lmscan.h\"\n#include \"lmparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\n\/\/#define PRINT_TOKENS\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid ColmScanner::sectionParseInit()\n{\n\t%% write init;\n}\n\nostream &ColmScanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool ColmScanner::recursiveInclude( const char *inclFileName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 )\n\t\t\treturn true;\n\t}\n\treturn false;\t\n}\n\nvoid ColmScanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = ts;\n\t\/\/cerr << \"adding \" << te - from << \" to column\" << endl;\n\tcolumn += te - from;\n\tlastnl = 0;\n}\n\nvoid ColmScanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid ColmScanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\nbool isAbsolutePath( const char *path )\n{\n\treturn path[0] == '\/';\n}\n\nifstream *ColmScanner::tryOpenInclude( char **pathChecks, long &found )\n{\n\tchar **check = pathChecks;\n\tifstream *inFile = new ifstream;\n\t\n\twhile ( *check != 0 ) {\n\t\tinFile->open( *check );\n\t\tif ( inFile->is_open() ) {\n\t\t\tfound = check - pathChecks;\n\t\t\treturn inFile;\n\t\t}\n\t\tcheck += 1;\n\t}\n\n\tfound = -1;\n\tdelete inFile;\n\treturn 0;\n}\n\nchar **ColmScanner::makeIncludePathChecks( const char *thisFileName, const char *fileName )\n{\n\tchar **checks = 0;\n\tlong nextCheck = 0;\n\tchar *data = strdup(fileName);\n\tlong length = strlen(fileName);\n\n\t\/* Absolute path? *\/\n\tif ( isAbsolutePath( data ) ) {\n\t\tchecks = new char*[2];\n\t\tchecks[nextCheck++] = data;\n\t}\n\telse {\n\t\t\/* Search from the the location of the current file. *\/\n\t\tchecks = new char *[2 + includePaths.length()];\n\t\tconst char *lastSlash = strrchr( thisFileName, '\/' );\n\t\tif ( lastSlash == 0 )\n\t\t\tchecks[nextCheck++] = data;\n\t\telse {\n\t\t\tlong givenPathLen = (lastSlash - thisFileName) + 1;\n\t\t\tlong checklen = givenPathLen + length;\n\t\t\tchar *check = new char[checklen+1];\n\t\t\tmemcpy( check, thisFileName, givenPathLen );\n\t\t\tmemcpy( check+givenPathLen, data, length );\n\t\t\tcheck[checklen] = 0;\n\t\t\tchecks[nextCheck++] = check;\n\t\t}\n\n\t\t\/* Search from the include paths given on the command line. *\/\n\t\tfor ( ArgsVector::Iter incp = includePaths; incp.lte(); incp++ ) {\n\t\t\tlong pathLen = strlen( *incp );\n\t\t\tlong checkLen = pathLen + 1 + length;\n\t\t\tchar *check = new char[checkLen+1];\n\t\t\tmemcpy( check, *incp, pathLen );\n\t\t\tcheck[pathLen] = '\/';\n\t\t\tmemcpy( check+pathLen+1, data, length );\n\t\t\tcheck[checkLen] = 0;\n\t\t\tchecks[nextCheck++] = check;\n\t\t}\n\t}\n\n\tchecks[nextCheck] = 0;\n\treturn checks;\n}\n\n\n%%{\n\tmachine section_parse;\n\timport \"lmparse.h\";\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_include\n\t{\n\t\tString src( lit, lit_len );\n\t\tString fileName;\n\t\tbool unused;\n\n\t\t\/* Need a location. *\/\n\t\tInputLoc here;\n\t\there.fileName = fileName;\n\t\there.line = line;\n\t\there.col = column;\n\n\t\tprepareLitString( fileName, unused, src, here );\n\t\tchar **checks = makeIncludePathChecks( this->fileName, fileName );\n\n\t\t\/* Open the input file for reading. *\/\n\t\tlong found = 0;\n\t\tifstream *inFile = tryOpenInclude( checks, found );\n\t\tif ( inFile == 0 ) {\n\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\tfileName << \" for reading\" << endl;\n\t\t}\n\t\telse {\n\t\t\t\/* Only proceed with the include if it was found. *\/\n\t\t\tif ( recursiveInclude( checks[found] ) )\n\t\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\n\t\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t\t * name then check if what we are including is already in the stack. *\/\n\t\t\tincludeStack.append( IncludeStackItem( checks[found] ) );\n\n\t\t\tColmScanner scanner( fileName, *inFile, output, parser, includeDepth+1 );\n\t\t\tscanner.scan();\n\t\t\tdelete inFile;\n\n\t\t\t\/* Remove the last element (len-1) *\/\n\t\t\tincludeStack.remove( -1 );\n\t\t}\n\t}\n\n\tinclude_target = \n\t\tTK_Literal >clear_words @store_lit;\n\n\tinclude_stmt =\n\t\t( KW_Include include_target ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction handle_token\n\t{\n\/\/\tcout << Parser_lelNames[type] << \" \";\n\/\/\tif ( start != 0 ) {\n\/\/\t\tcout.write( start, end-start );\n\/\/\t}\n\/\/\tcout << endl;\n\n\t\tInputLoc loc;\n\n\t\t#ifdef PRINT_TOKENS\n\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\tcerr << \" \" << toklen;\n\t\tif ( tokdata != 0 )\n\t\t\tcerr << \" \" << tokdata;\n\t\tcerr << endl;\n\t\t#endif\n\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = column;\n\n\t\tif ( tokdata != 0 && tokdata[toklen-1] == '\\n' )\n\t\t\tloc.line -= 1;\n\n\t\tparser->token( loc, type, tokdata, toklen );\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Include ) @handle_token;\n\n\tmain := ( \n\t\tinclude_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid ColmScanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\tint *eof = 0;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n}\n\nvoid ColmScanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t\/* Probably use: token( -1 ); *\/\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( TK_ReChar, '\\0' ); };\n\t\t'\\\\a' => { token( TK_ReChar, '\\a' ); };\n\t\t'\\\\b' => { token( TK_ReChar, '\\b' ); };\n\t\t'\\\\t' => { token( TK_ReChar, '\\t' ); };\n\t\t'\\\\n' => { token( TK_ReChar, '\\n' ); };\n\t\t'\\\\v' => { token( TK_ReChar, '\\v' ); };\n\t\t'\\\\f' => { token( TK_ReChar, '\\f' ); };\n\t\t'\\\\r' => { token( TK_ReChar, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( TK_ReChar, ts+1, te ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( TK_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( TK_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( TK_ReChar, ts, te ); };\n\n\t*|;\n\n\tregular_type := |*\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, ts, te ); };\n\t\thex_number => { token( TK_Hex, ts, te ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, ts, te ); };\n\n\t\t'[' => { token( TK_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( TK_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( '\/'); fret; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\n\t\t':>' => { token( TK_ColonGt ); };\n\t\t':>>' => { token( TK_ColonGtGt ); };\n\t\t'<:' => { token( TK_LtColon ); };\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n\n\tliteral_pattern := |*\n\t\t'\\\\' '0' { litBuf.append( '\\0' ); };\n\t\t'\\\\' 'a' { litBuf.append( '\\a' ); };\n\t\t'\\\\' 'b' { litBuf.append( '\\b' ); };\n\t\t'\\\\' 't' { litBuf.append( '\\t' ); };\n\t\t'\\\\' 'n' { litBuf.append( '\\n' ); };\n\t\t'\\\\' 'v' { litBuf.append( '\\v' ); };\n\t\t'\\\\' 'f' { litBuf.append( '\\f' ); };\n\t\t'\\\\' 'r' { litBuf.append( '\\r' ); };\n\n\t\t'\\\\' any {\n\t\t\tlitBuf.append( ts[1] );\n\t\t};\n\t\t'\"' => {\n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\tNL => {\n\t\t\tlitBuf.append( '\\n' );\n\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\tlitBuf.clear();\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\t'[' => { \n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '[' );\n\t\t\tfcall main;\n\t\t};\n\t\tany => { \n\t\t\tlitBuf.append( *ts );\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tmain := |*\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'commit' => { token( KW_Commit ); };\n\t\t'token' => { token( KW_Token ); };\n\t\t'literal' => { token( KW_Literal ); };\n\t\t'rl' => { token( KW_Rl ); };\n\t\t'def' => { token( KW_Def ); };\n\t\t'ignore' => { token( KW_Ignore ); };\n\t\t'construct' => { token( KW_Construct ); };\n\t\t'cons' => { token( KW_Construct ); };\n\t\t'new' => { token( KW_New ); };\n\t\t'if' => { token( KW_If ); };\n\t\t'reject' => { token( KW_Reject ); };\n\t\t'while' => { token( KW_While ); };\n\t\t'else' => { token( KW_Else ); };\n\t\t'elsif' => { token( KW_Elsif ); };\n\t\t'match' => { token( KW_Match ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'iter' => { token( KW_Iter ); };\n\t\t'prints' => { token( KW_PrintStream ); };\n\t\t'print' => { token( KW_Print ); };\n\t\t'print_xml_ac' => { token( KW_PrintXMLAC ); };\n\t\t'print_xml' => { token( KW_PrintXML ); };\n\t\t'namespace' => { token( KW_Namespace ); };\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'map' => { token( KW_Map ); };\n\t\t'list' => { token( KW_List ); };\n\t\t'vector' => { token( KW_Vector ); };\n\t\t'accum' => { token( KW_Accum ); };\n\t\t'parser' => { token( KW_Accum ); };\n\t\t'return' => { token( KW_Return ); };\n\t\t'break' => { token( KW_Break ); };\n\t\t'yield' => { token( KW_Yield ); };\n\t\t'typeid' => { token( KW_TypeId ); };\n\t\t'make_token' => { token( KW_MakeToken ); };\n\t\t'make_tree' => { token( KW_MakeTree ); };\n\t\t'reducefirst' => { token( KW_ReduceFirst ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'in' => { token( KW_In ); };\n\t\t'nil' => { token( KW_Nil ); };\n\t\t'true' => { token( KW_True ); };\n\t\t'false' => { token( KW_False ); };\n\t\t'parse' => { token( KW_Parse ); };\n\t\t'parse_stop' => { token( KW_ParseStop ); };\n\t\t'global' => { token( KW_Global ); };\n\t\t'export' => { token( KW_Export ); };\n\t\t'ptr' => { token( KW_Ptr ); };\n\t\t'ref' => { token( KW_Ref ); };\n\t\t'deref' => { token( KW_Deref ); };\n\t\t'require' => { token( KW_Require ); };\n\t\t'preeof' => { token( KW_Preeof ); };\n\t\t'left' => { token( KW_Left ); };\n\t\t'right' => { token( KW_Right ); };\n\t\t'nonassoc' => { token( KW_Nonassoc ); };\n\t\t'prec' => { token( KW_Prec ); };\n\t\t'include' => { token( KW_Include ); };\n\t\t'context' => { token( KW_Context ); };\n\t\t'alias' => { token( KW_Alias ); };\n\t\t'send' => { token( KW_Send ); };\n\t\t'ni' => { token( KW_Ni ); };\n\t\t'ci' => { token( KW_Ci ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\tnumber => { token( TK_Number, ts, te ); };\n\n\t\t'\/' => { \n\t\t\ttoken( '\/' ); \n\t\t\tif ( parser->enterRl )\n\t\t\t\tfcall regular_type;\n\t\t};\n\n\t\t\"~\" [^\\n]* NL => { \n\t\t\ttoken( '\"' );\n\t\t\ttoken( TK_LitPat, ts+1, te );\n\t\t\ttoken( '\"' );\n\t\t};\n\n\t\t\"'\" ([^'\\\\\\n] | '\\\\' (any | NL))* ( \"'\" | NL ) => {\n\t\t\ttoken( TK_Literal, ts, te );\n\t\t};\n\n\t\t'\"' => { \n\t\t\ttoken( '\"' );\n\t\t\tlitBuf.clear(); \n\t\t\tfcall literal_pattern;\n\t\t};\n\t\t'[' => { \n\t\t\ttoken( '[' ); \n\t\t\tfcall main;\n\t\t};\n\n\t\t']' => {\n\t\t\ttoken( ']' );\n\t\t\tif ( top > 0 )\n\t\t\t\tfret;\n\t\t};\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\t\t'==' => { token( TK_DoubleEql ); };\n\t\t'!=' => { token( TK_NotEql ); };\n\t\t'::' => { token( TK_DoubleColon ); };\n\t\t'<=' => { token( TK_LessEql ); };\n\t\t'>=' => { token( TK_GrtrEql ); };\n\t\t'->' => { token( TK_RightArrow ); };\n\t\t'&&' => { token( TK_AmpAmp ); };\n\t\t'||' => { token( TK_BarBar ); };\n\t\t'<<' => { token( TK_LtLt ); };\n\t\t\n\t\t('+' | '-' | '*' | '\/' | '(' | ')' | '@' | '$' | '^' ) => { token( *ts ); };\n\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n}%%\n\n%% write data;\n\nvoid ColmScanner::scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[32];\n\tbool execute = true;\n\n\tsectionParseInit();\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( ts != 0 )\n\t\t\t\tts = newbuf + ( ts - buf );\n\t\t\tte = newbuf + ( te - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\tchar *eof = 0;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"colm scanner error (metalanguage)\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = ts;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( ts != 0 )\n\t\t\t\tts -= shiftback;\n\t\t\tte -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\tdelete[] buf;\n}\n\nvoid ColmScanner::eof()\n{\n\tInputLoc loc;\n\tloc.fileName = \"\";\n\tloc.line = line;\n\tloc.col = 1;\n\tparser->token( loc, ColmParser_tk_eof, 0, 0 );\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"1400a859cea32ef19615d7f8ff8b2ab26f1e1eae","subject":"Make sure C strings always end with a NULL.","message":"Make sure C strings always end with a NULL.\n\nHaven't bumped into any problems just yet. However, in theory all sorts of evil\ncould happen here. Which is part of the problem of C: so much shit is undefined\nbehaviour that you can take a single step and fall in 15 holes at the same time.\nIn theory, because nobody bothered to actually specify it properly.\n","repos":"YorickPeterse\/oga,ttasanen\/oga,dfockler\/oga,altmetric\/oga,YorickPeterse\/oga,dfockler\/oga,jeffreybaird\/oga,ttasanen\/oga,altmetric\/oga,ttasanen\/oga,dfockler\/oga,jeffreybaird\/oga,ttasanen\/oga,altmetric\/oga,YorickPeterse\/oga,altmetric\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,YorickPeterse\/oga,dfockler\/oga,ttasanen\/oga,altmetric\/oga,jeffreybaird\/oga,jeffreybaird\/oga","old_file":"ext\/c\/lexer.rl","new_file":"ext\/c\/lexer.rl","new_contents":"#include \"lexer.h\"\n\n\/*\nThe following two macros allow the Ragel grammar to use generic function calls\nwithout relying on the setup of the C or Java lexer. Using these macros we can\nalso pass along `self` to the callback functions without having to hard-code\nthis in to the Ragel grammar.\n\nIn the C lexer we don't need the `data` variable (since this is pulled in based\non `ts` and `te`) so the macro ignores this argument.\n*\/\n\n#define callback(name, data, encoding, start, stop) \\\n liboga_xml_lexer_callback(self, name, encoding, start, stop);\n\n#define callback_simple(name) \\\n liboga_xml_lexer_callback_simple(self, name);\n\n#define oga_ivar_get(owner, name) \\\n rb_ivar_get(owner, rb_intern(name))\n\n#define oga_ivar_set(owner, name, value) \\\n rb_ivar_set(owner, rb_intern(name), value)\n\n#define advance_line(amount) \\\n rb_funcall(self, rb_intern(\"advance_line\"), 1, INT2NUM(amount));\n\n%%machine c_lexer;\n\n\/**\n * Calls a method defined in the Ruby side of the lexer. The String value is\n * created based on the values of `ts` and `te` and uses the encoding specified\n * in `encoding`.\n *\n * @example\n * rb_encoding *encoding = rb_enc_get(...);\n * liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n *\/\nvoid liboga_xml_lexer_callback(\n VALUE self,\n const char *name,\n rb_encoding *encoding,\n const char *ts,\n const char *te\n)\n{\n VALUE value = rb_enc_str_new(ts, te - ts, encoding);\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 1, value);\n}\n\n\/**\n * Calls a method defined in the Ruby side of the lexer without passing it any\n * arguments.\n *\n * @example\n * liboga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n *\/\nvoid liboga_xml_lexer_callback_simple(VALUE self, const char *name)\n{\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 0);\n}\n\n%% write data;\n\n\/**\n * Lexes the String specifies as the method argument. Token values have the\n * same encoding as the input value.\n *\n * This method keeps track of an internal state using the instance variables\n * `@act` and `@cs`.\n *\/\nVALUE oga_xml_lexer_advance(VALUE self, VALUE data_block)\n{\n \/* Make sure that all data passed back to Ruby has the proper encoding. *\/\n rb_encoding *encoding = rb_enc_get(data_block);\n\n char *data_str_val = StringValueCStr(data_block);\n\n const char *p = data_str_val;\n const char *pe = data_str_val + strlen(data_str_val);\n const char *eof = pe;\n const char *ts = 0;\n const char *te = 0;\n const char *mark = 0;\n\n int act = NUM2INT(oga_ivar_get(self, \"@act\"));\n int cs = NUM2INT(oga_ivar_get(self, \"@cs\"));\n int lines = 0;\n\n %% write exec;\n\n oga_ivar_set(self, \"@act\", INT2NUM(act));\n oga_ivar_set(self, \"@cs\", INT2NUM(cs));\n\n return Qnil;\n}\n\n\/**\n * Resets the internal state of the lexer.\n *\/\nVALUE oga_xml_lexer_reset(VALUE self)\n{\n oga_ivar_set(self, \"@act\", INT2NUM(0));\n oga_ivar_set(self, \"@cs\", INT2NUM(c_lexer_start));\n\n return Qnil;\n}\n\n%%{\n include base_lexer \"base_lexer.rl\";\n}%%\n\nvoid Init_liboga_xml_lexer()\n{\n VALUE mOga = rb_const_get(rb_cObject, rb_intern(\"Oga\"));\n VALUE mXML = rb_const_get(mOga, rb_intern(\"XML\"));\n VALUE cLexer = rb_define_class_under(mXML, \"Lexer\", rb_cObject);\n\n rb_define_method(cLexer, \"advance_native\", oga_xml_lexer_advance, 1);\n rb_define_method(cLexer, \"reset_native\", oga_xml_lexer_reset, 0);\n}\n","old_contents":"#include \"lexer.h\"\n\n\/*\nThe following two macros allow the Ragel grammar to use generic function calls\nwithout relying on the setup of the C or Java lexer. Using these macros we can\nalso pass along `self` to the callback functions without having to hard-code\nthis in to the Ragel grammar.\n\nIn the C lexer we don't need the `data` variable (since this is pulled in based\non `ts` and `te`) so the macro ignores this argument.\n*\/\n\n#define callback(name, data, encoding, start, stop) \\\n liboga_xml_lexer_callback(self, name, encoding, start, stop);\n\n#define callback_simple(name) \\\n liboga_xml_lexer_callback_simple(self, name);\n\n#define oga_ivar_get(owner, name) \\\n rb_ivar_get(owner, rb_intern(name))\n\n#define oga_ivar_set(owner, name, value) \\\n rb_ivar_set(owner, rb_intern(name), value)\n\n#define advance_line(amount) \\\n rb_funcall(self, rb_intern(\"advance_line\"), 1, INT2NUM(amount));\n\n%%machine c_lexer;\n\n\/**\n * Calls a method defined in the Ruby side of the lexer. The String value is\n * created based on the values of `ts` and `te` and uses the encoding specified\n * in `encoding`.\n *\n * @example\n * rb_encoding *encoding = rb_enc_get(...);\n * liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n *\/\nvoid liboga_xml_lexer_callback(\n VALUE self,\n const char *name,\n rb_encoding *encoding,\n const char *ts,\n const char *te\n)\n{\n VALUE value = rb_enc_str_new(ts, te - ts, encoding);\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 1, value);\n}\n\n\/**\n * Calls a method defined in the Ruby side of the lexer without passing it any\n * arguments.\n *\n * @example\n * liboga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n *\/\nvoid liboga_xml_lexer_callback_simple(VALUE self, const char *name)\n{\n VALUE method = rb_intern(name);\n\n rb_funcall(self, method, 0);\n}\n\n%% write data;\n\n\/**\n * Lexes the String specifies as the method argument. Token values have the\n * same encoding as the input value.\n *\n * This method keeps track of an internal state using the instance variables\n * `@act` and `@cs`.\n *\/\nVALUE oga_xml_lexer_advance(VALUE self, VALUE data_block)\n{\n \/* Make sure that all data passed back to Ruby has the proper encoding. *\/\n rb_encoding *encoding = rb_enc_get(data_block);\n\n char *data_str_val = StringValuePtr(data_block);\n\n const char *p = data_str_val;\n const char *pe = data_str_val + strlen(data_str_val);\n const char *eof = pe;\n const char *ts = 0;\n const char *te = 0;\n const char *mark = 0;\n\n int act = NUM2INT(oga_ivar_get(self, \"@act\"));\n int cs = NUM2INT(oga_ivar_get(self, \"@cs\"));\n int lines = 0;\n\n %% write exec;\n\n oga_ivar_set(self, \"@act\", INT2NUM(act));\n oga_ivar_set(self, \"@cs\", INT2NUM(cs));\n\n return Qnil;\n}\n\n\/**\n * Resets the internal state of the lexer.\n *\/\nVALUE oga_xml_lexer_reset(VALUE self)\n{\n oga_ivar_set(self, \"@act\", INT2NUM(0));\n oga_ivar_set(self, \"@cs\", INT2NUM(c_lexer_start));\n\n return Qnil;\n}\n\n%%{\n include base_lexer \"base_lexer.rl\";\n}%%\n\nvoid Init_liboga_xml_lexer()\n{\n VALUE mOga = rb_const_get(rb_cObject, rb_intern(\"Oga\"));\n VALUE mXML = rb_const_get(mOga, rb_intern(\"XML\"));\n VALUE cLexer = rb_define_class_under(mXML, \"Lexer\", rb_cObject);\n\n rb_define_method(cLexer, \"advance_native\", oga_xml_lexer_advance, 1);\n rb_define_method(cLexer, \"reset_native\", oga_xml_lexer_reset, 0);\n}\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"b006289c5f2133462c4c41bb8925f0359a0fd1f6","subject":"Removed extra space in c\/lexer.rl","message":"Removed extra space in c\/lexer.rl\n","repos":"YorickPeterse\/oga,altmetric\/oga,jeffreybaird\/oga,dfockler\/oga,ttasanen\/oga,YorickPeterse\/oga,dfockler\/oga,ttasanen\/oga,jeffreybaird\/oga,ttasanen\/oga,altmetric\/oga,ttasanen\/oga,altmetric\/oga,YorickPeterse\/oga,jeffreybaird\/oga,YorickPeterse\/oga,dfockler\/oga,altmetric\/oga,altmetric\/oga,dfockler\/oga,ttasanen\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,jeffreybaird\/oga","old_file":"ext\/c\/lexer.rl","new_file":"ext\/c\/lexer.rl","new_contents":"#include \"lexer.h\"\n\n\/*\nThe following two macros allow the Ragel grammar to use generic function calls\nwithout relying on the setup of the C or Java lexer. Using these macros we can\nalso pass along `self` to the callback functions without having to hard-code\nthis in to the Ragel grammar.\n\nIn the C lexer we don't need the `data` variable (since this is pulled in based\non `ts` and `te`) so the macro ignores this argument.\n*\/\n\n#define callback(name, data, encoding, start, stop) \\\n liboga_xml_lexer_callback(self, name, encoding, start, stop);\n\n#define callback_simple(name) \\\n liboga_xml_lexer_callback_simple(self, name);\n\n#define oga_ivar_get(owner, name) \\\n rb_ivar_get(owner, rb_intern(name))\n\n#define oga_ivar_set(owner, name, value) \\\n rb_ivar_set(owner, rb_intern(name), value)\n\n#define advance_line(amount) \\\n rb_funcall(self, rb_intern(\"advance_line\"), 1, INT2NUM(amount));\n\n%%machine c_lexer;\n\n\/**\n * Calls a method defined in the Ruby side of the lexer. The String value is\n * created based on the values of `ts` and `te` and uses the encoding specified\n * in `encoding`.\n *\n * @example\n * rb_encoding *encoding = rb_enc_get(...);\n * liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n *\/\nvoid liboga_xml_lexer_callback(\n VALUE self,\n VALUE name,\n rb_encoding *encoding,\n const char *ts,\n const char *te\n)\n{\n VALUE value = rb_enc_str_new(ts, te - ts, encoding);\n\n rb_funcall(self, name, 1, value);\n}\n\n\/**\n * Calls a method defined in the Ruby side of the lexer without passing it any\n * arguments.\n *\n * @example\n * liboga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n *\/\nvoid liboga_xml_lexer_callback_simple(VALUE self, VALUE name)\n{\n rb_funcall(self, name, 0);\n}\n\n%% write data;\n\n\/**\n * Lexes the String specifies as the method argument. Token values have the\n * same encoding as the input value.\n *\n * This method keeps track of an internal state using the instance variables\n * `@act` and `@cs`.\n *\/\nVALUE oga_xml_lexer_advance(VALUE self, VALUE data_block)\n{\n OgaLexerState *state;\n\n \/* Make sure that all data passed back to Ruby has the proper encoding. *\/\n rb_encoding *encoding = rb_enc_get(data_block);\n\n char *data_str_val = StringValueCStr(data_block);\n\n Data_Get_Struct(self, OgaLexerState, state);\n\n const char *p = data_str_val;\n const char *pe = data_str_val + strlen(data_str_val);\n const char *eof = pe;\n const char *ts = 0;\n const char *te = 0;\n const char *mark = 0;\n\n int lines = state->lines;\n\n VALUE id_advance_line = rb_intern(\"advance_line\");\n VALUE id_on_attribute = rb_intern(\"on_attribute\");\n VALUE id_on_attribute_ns = rb_intern(\"on_attribute_ns\");\n VALUE id_on_cdata = rb_intern(\"on_cdata\");\n VALUE id_on_comment = rb_intern(\"on_comment\");\n VALUE id_on_doctype_end = rb_intern(\"on_doctype_end\");\n VALUE id_on_doctype_inline = rb_intern(\"on_doctype_inline\");\n VALUE id_on_doctype_name = rb_intern(\"on_doctype_name\");\n VALUE id_on_doctype_start = rb_intern(\"on_doctype_start\");\n VALUE id_on_doctype_type = rb_intern(\"on_doctype_type\");\n VALUE id_on_element_end = rb_intern(\"on_element_end\");\n VALUE id_on_element_name = rb_intern(\"on_element_name\");\n VALUE id_on_element_ns = rb_intern(\"on_element_ns\");\n VALUE id_on_element_open_end = rb_intern(\"on_element_open_end\");\n VALUE id_on_element_start = rb_intern(\"on_element_start\");\n VALUE id_on_proc_ins_end = rb_intern(\"on_proc_ins_end\");\n VALUE id_on_proc_ins_name = rb_intern(\"on_proc_ins_name\");\n VALUE id_on_proc_ins_start = rb_intern(\"on_proc_ins_start\");\n VALUE id_on_string_body = rb_intern(\"on_string_body\");\n VALUE id_on_string_dquote = rb_intern(\"on_string_dquote\");\n VALUE id_on_string_squote = rb_intern(\"on_string_squote\");\n VALUE id_on_text = rb_intern(\"on_text\");\n VALUE id_on_xml_decl_end = rb_intern(\"on_xml_decl_end\");\n VALUE id_on_xml_decl_start = rb_intern(\"on_xml_decl_start\");\n\n %% write exec;\n\n state->lines = lines;\n\n return Qnil;\n}\n\n\/**\n * Resets the internal state of the lexer.\n *\/\nVALUE oga_xml_lexer_reset(VALUE self)\n{\n OgaLexerState *state;\n\n Data_Get_Struct(self, OgaLexerState, state);\n\n state->act = 0;\n state->cs = c_lexer_start;\n state->lines = 0;\n state->top = 0;\n\n return Qnil;\n}\n\n\/**\n * Frees the associated lexer state struct.\n *\/\nvoid oga_xml_lexer_free(void *state)\n{\n free((OgaLexerState *) state);\n}\n\n\/**\n * Allocates and wraps the C lexer state struct. This state is used to keep\n * track of the current position, line numbers, etc.\n *\/\nVALUE oga_xml_lexer_allocate(VALUE klass)\n{\n OgaLexerState *state = malloc(sizeof(OgaLexerState));\n\n return Data_Wrap_Struct(klass, NULL, oga_xml_lexer_free, state);\n}\n\n%%{\n include base_lexer \"base_lexer.rl\";\n\n variable top state->top;\n variable stack state->stack;\n variable act state->act;\n variable cs state->cs;\n}%%\n\nvoid Init_liboga_xml_lexer()\n{\n VALUE mOga = rb_const_get(rb_cObject, rb_intern(\"Oga\"));\n VALUE mXML = rb_const_get(mOga, rb_intern(\"XML\"));\n VALUE cLexer = rb_define_class_under(mXML, \"Lexer\", rb_cObject);\n\n rb_define_method(cLexer, \"advance_native\", oga_xml_lexer_advance, 1);\n rb_define_method(cLexer, \"reset_native\", oga_xml_lexer_reset, 0);\n\n rb_define_alloc_func(cLexer, oga_xml_lexer_allocate);\n}\n","old_contents":"#include \"lexer.h\"\n\n\/*\nThe following two macros allow the Ragel grammar to use generic function calls\nwithout relying on the setup of the C or Java lexer. Using these macros we can\nalso pass along `self` to the callback functions without having to hard-code\nthis in to the Ragel grammar.\n\nIn the C lexer we don't need the `data` variable (since this is pulled in based\non `ts` and `te`) so the macro ignores this argument.\n*\/\n\n#define callback(name, data, encoding, start, stop) \\\n liboga_xml_lexer_callback(self, name, encoding, start, stop);\n\n#define callback_simple(name) \\\n liboga_xml_lexer_callback_simple(self, name);\n\n#define oga_ivar_get(owner, name) \\\n rb_ivar_get(owner, rb_intern(name))\n\n#define oga_ivar_set(owner, name, value) \\\n rb_ivar_set(owner, rb_intern(name), value)\n\n#define advance_line(amount) \\\n rb_funcall(self, rb_intern(\"advance_line\"), 1, INT2NUM(amount));\n\n%%machine c_lexer;\n\n\/**\n * Calls a method defined in the Ruby side of the lexer. The String value is\n * created based on the values of `ts` and `te` and uses the encoding specified\n * in `encoding`.\n *\n * @example\n * rb_encoding *encoding = rb_enc_get(...);\n * liboga_xml_lexer_callback(self, \"on_string\", encoding, ts, te);\n *\/\nvoid liboga_xml_lexer_callback(\n VALUE self,\n VALUE name,\n rb_encoding *encoding,\n const char *ts,\n const char *te\n)\n{\n VALUE value = rb_enc_str_new(ts, te - ts, encoding);\n\n rb_funcall(self, name, 1, value);\n}\n\n\/**\n * Calls a method defined in the Ruby side of the lexer without passing it any\n * arguments.\n *\n * @example\n * liboga_xml_lexer_callback_simple(self, \"on_cdata_start\");\n *\/\nvoid liboga_xml_lexer_callback_simple(VALUE self, VALUE name)\n{\n rb_funcall(self, name, 0);\n}\n\n%% write data;\n\n\/**\n * Lexes the String specifies as the method argument. Token values have the\n * same encoding as the input value.\n *\n * This method keeps track of an internal state using the instance variables\n * `@act` and `@cs`.\n *\/\nVALUE oga_xml_lexer_advance(VALUE self, VALUE data_block)\n{\n OgaLexerState *state;\n\n \/* Make sure that all data passed back to Ruby has the proper encoding. *\/\n rb_encoding *encoding = rb_enc_get(data_block);\n\n char *data_str_val = StringValueCStr(data_block);\n\n Data_Get_Struct(self, OgaLexerState, state);\n\n const char *p = data_str_val;\n const char *pe = data_str_val + strlen(data_str_val);\n const char *eof = pe;\n const char *ts = 0;\n const char *te = 0;\n const char *mark = 0;\n\n int lines = state->lines;\n\n VALUE id_advance_line = rb_intern(\"advance_line\");\n VALUE id_on_attribute = rb_intern(\"on_attribute\");\n VALUE id_on_attribute_ns = rb_intern(\"on_attribute_ns\");\n VALUE id_on_cdata = rb_intern(\"on_cdata\");\n VALUE id_on_comment = rb_intern(\"on_comment\");\n VALUE id_on_doctype_end = rb_intern(\"on_doctype_end\");\n VALUE id_on_doctype_inline = rb_intern(\"on_doctype_inline\");\n VALUE id_on_doctype_name = rb_intern(\"on_doctype_name\");\n VALUE id_on_doctype_start = rb_intern(\"on_doctype_start\");\n VALUE id_on_doctype_type = rb_intern(\"on_doctype_type\");\n VALUE id_on_element_end = rb_intern(\"on_element_end\");\n VALUE id_on_element_name = rb_intern(\"on_element_name\");\n VALUE id_on_element_ns = rb_intern(\"on_element_ns\");\n VALUE id_on_element_open_end = rb_intern(\"on_element_open_end\");\n VALUE id_on_element_start = rb_intern(\"on_element_start\");\n VALUE id_on_proc_ins_end = rb_intern(\"on_proc_ins_end\");\n VALUE id_on_proc_ins_name = rb_intern(\"on_proc_ins_name\");\n VALUE id_on_proc_ins_start = rb_intern(\"on_proc_ins_start\");\n VALUE id_on_string_body = rb_intern(\"on_string_body\");\n VALUE id_on_string_dquote = rb_intern(\"on_string_dquote\");\n VALUE id_on_string_squote = rb_intern(\"on_string_squote\");\n VALUE id_on_text = rb_intern(\"on_text\");\n VALUE id_on_xml_decl_end = rb_intern(\"on_xml_decl_end\");\n VALUE id_on_xml_decl_start = rb_intern(\"on_xml_decl_start\");\n\n %% write exec;\n\n state->lines = lines;\n\n return Qnil;\n}\n\n\/**\n * Resets the internal state of the lexer.\n *\/\nVALUE oga_xml_lexer_reset(VALUE self)\n{\n OgaLexerState *state;\n\n Data_Get_Struct(self, OgaLexerState, state);\n\n state->act = 0;\n state->cs = c_lexer_start;\n state->lines = 0;\n state->top = 0;\n\n return Qnil;\n}\n\n\/**\n * Frees the associated lexer state struct.\n *\/\nvoid oga_xml_lexer_free(void *state)\n{\n free((OgaLexerState *) state);\n}\n\n\/**\n * Allocates and wraps the C lexer state struct. This state is used to keep\n * track of the current position, line numbers, etc.\n *\/\nVALUE oga_xml_lexer_allocate(VALUE klass)\n{\n OgaLexerState *state = malloc(sizeof(OgaLexerState));\n\n return Data_Wrap_Struct(klass, NULL, oga_xml_lexer_free, state);\n}\n\n%%{\n include base_lexer \"base_lexer.rl\";\n\n variable top state->top;\n variable stack state->stack;\n variable act state->act;\n variable cs state->cs;\n}%%\n\nvoid Init_liboga_xml_lexer()\n{\n VALUE mOga = rb_const_get(rb_cObject, rb_intern(\"Oga\"));\n VALUE mXML = rb_const_get(mOga, rb_intern(\"XML\"));\n VALUE cLexer = rb_define_class_under(mXML, \"Lexer\", rb_cObject);\n\n rb_define_method(cLexer, \"advance_native\", oga_xml_lexer_advance, 1);\n rb_define_method(cLexer, \"reset_native\", oga_xml_lexer_reset, 0);\n\n rb_define_alloc_func(cLexer, oga_xml_lexer_allocate);\n}\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"a5fa12c18d8428c86313fc9b83df49ec0800fcec","subject":"[jnc_ct] opt: avoid escape-decode when there are no backslashes in string","message":"[jnc_ct] opt: avoid escape-decode when there are no backslashes in string\n","repos":"vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy","old_file":"src\/jnc_ct\/jnc_ct_Parser\/jnc_ct_Lexer.rl","new_file":"src\/jnc_ct\/jnc_ct_Parser\/jnc_ct_Lexer.rl","new_contents":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n\/\/ warning C4065: switch statement contains 'default' but no 'case' labels\n\n#pragma warning (disable: 4065)\n\nnamespace jnc {\nnamespace ct {\n\n\/\/..............................................................................\n\n%%{\n\nmachine jnc;\nwrite data;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# prepush \/ postpop (for fcall\/fret)\n#\n\nprepush\n{\n\tstack = prePush ();\n}\n\npostpop\n{\n\tpostPop ();\n}\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n' @{ newLine (p + 1); };\nlc_nl = '\\\\' '\\r'? nl;\nesc = '\\\\' [^\\n];\n\nlit_dq_wo_esc = '\"' [^\"\\n\\\\]* ([\"\\\\] | nl);\nlit_dq_w_esc = '\"' ([^\"\\n\\\\] | esc)* ([\"\\\\] | nl);\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* (['\\\\] | nl);\nraw_lit_dq = '\"' [^\"\\n]* ('\"' | nl);\nraw_lit_sq = \"'\" [^'\\n]* (\"'\" | nl);\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\n(nl ws?)? '\"\"\"'\n\t\t { createMlLiteralToken (); fgoto main; };\nnl ;\nany ;\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# formatting literal machines\n#\n\nlit_fmt := |*\n\nesc ;\n'$!' { createFmtLastErrorDescriptionTokens (); };\n'$' id { createFmtSimpleIdentifierTokens (); };\n'%' dec+ { createFmtIndexTokens (); };\n[$%] '(' { createFmtLiteralToken (TokenKind_FmtLiteral, *ts == '%'); m_parenthesesLevelStack.append (1); fcall main; };\n'\"' | nl { createFmtLiteralToken (TokenKind_Literal); fret; };\nany ;\n\n*|;\n\nfmt_spec := |*\n\n';' [^\")\\n]* { createFmtSpecifierToken (); fret; };\nany { ASSERT (false); fret; };\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# global declarations & pragmas\n\n'import' { createToken (TokenKind_Import); };\n'namespace' { createToken (TokenKind_Namespace); };\n'extension' { createToken (TokenKind_Extension); };\n'dynamiclib' { createToken (TokenKind_DynamicLib); };\n'using' { createToken (TokenKind_Using); };\n'friend' { createToken (TokenKind_Friend); };\n'public' { createToken (TokenKind_Public); };\n'protected' { createToken (TokenKind_Protected); };\n'alignment' { createToken (TokenKind_Alignment); };\n'setas' { createToken (TokenKind_SetAs); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# storage specifiers\n\n'typedef' { createToken (TokenKind_Typedef); };\n'alias' { createToken (TokenKind_Alias); };\n'static' { createToken (TokenKind_Static); };\n'threadlocal' { createToken (TokenKind_ThreadLocal); };\n'abstract' { createToken (TokenKind_Abstract); };\n'virtual' { createToken (TokenKind_Virtual); };\n'override' { createToken (TokenKind_Override); };\n'mutable' { createToken (TokenKind_Mutable); };\n'disposable' { createToken (TokenKind_Disposable); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# type modifiers\n\n'unsigned' { createToken (TokenKind_Unsigned); };\n'bigendian' { createToken (TokenKind_BigEndian); };\n'const' { createToken (TokenKind_Const); };\n'readonly' { createToken (TokenKind_ReadOnly); };\n'cmut' { createToken (TokenKind_CMut); };\n'volatile' { createToken (TokenKind_Volatile); };\n'weak' { createToken (TokenKind_Weak); };\n'thin' { createToken (TokenKind_Thin); };\n'safe' { createToken (TokenKind_Safe); };\n'unsafe' { createToken (TokenKind_Unsafe); };\n'errorcode' { createToken (TokenKind_ErrorCode); };\n'cdecl' { createToken (TokenKind_Cdecl); };\n'stdcall' { createToken (TokenKind_Stdcall); };\n'jnccall' { createToken (TokenKind_Jnccall); };\n'thiscall' { createToken (TokenKind_Thiscall); };\n'array' { createToken (TokenKind_Array); };\n'function' { createToken (TokenKind_Function); };\n'property' { createToken (TokenKind_Property); };\n'bindable' { createToken (TokenKind_Bindable); };\n'autoget' { createToken (TokenKind_AutoGet); };\n'indexed' { createToken (TokenKind_Indexed); };\n'multicast' { createToken (TokenKind_Multicast); };\n'event' { createToken (TokenKind_Event); };\n'reactor' { createToken (TokenKind_Reactor); };\n'async' { createToken (TokenKind_Async); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# type specifiers\n\n'anydata' { createToken (TokenKind_AnyData); };\n'void' { createToken (TokenKind_Void); };\n'variant' { createToken (TokenKind_Variant); };\n'bool' { createToken (TokenKind_Bool); };\n'int' { createToken (TokenKind_Int); };\n'intptr' { createToken (TokenKind_IntPtr); };\n'char' { createToken (TokenKind_Char); };\n'short' { createToken (TokenKind_Short); };\n'long' { createToken (TokenKind_Long); };\n'float' { createToken (TokenKind_Float); };\n'double' { createToken (TokenKind_Double); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# named type specifiers\n\n'enum' { createToken (TokenKind_Enum); };\n'struct' { createToken (TokenKind_Struct); };\n'union' { createToken (TokenKind_Union); };\n'class' { createToken (TokenKind_Class); };\n'opaque' { createToken (TokenKind_Opaque); };\n'exposed' { createToken (TokenKind_Exposed); };\n'bitflag' { createToken (TokenKind_BitFlag); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# special member methods\n\n'get' { createToken (TokenKind_Get); };\n'set' { createToken (TokenKind_Set); };\n'preconstruct' { createToken (TokenKind_PreConstruct); };\n'construct' { createToken (TokenKind_Construct); };\n'destruct' { createToken (TokenKind_Destruct); };\n'operator' { createToken (TokenKind_Operator); };\n'postfix' { createToken (TokenKind_Postfix); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# operators\n\n'new' { createToken (TokenKind_New); };\n'sizeof' { createToken (TokenKind_SizeOf); };\n'countof' { createToken (TokenKind_CountOf); };\n'offsetof' { createToken (TokenKind_OffsetOf); };\n'typeof' { createToken (TokenKind_TypeOf); };\n'bindingof' { createToken (TokenKind_BindingOf); };\n'dynamic' { createToken (TokenKind_Dynamic); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# statements\n\n'if' { createToken (TokenKind_If); };\n'else' { createToken (TokenKind_Else); };\n'for' { createToken (TokenKind_For); };\n'while' { createToken (TokenKind_While); };\n'do' { createToken (TokenKind_Do); };\n'break' { createKeywordTokenEx (TokenKind_Break, 1); };\n'break' [1-9] { createKeywordTokenEx (TokenKind_Break, te [-1] - '0'); };\n'continue' { createKeywordTokenEx (TokenKind_Continue, 1); };\n'continue' [1-9] { createKeywordTokenEx (TokenKind_Continue, te [-1] - '0'); };\n'return' { createToken (TokenKind_Return); };\n'switch' { createToken (TokenKind_Switch); };\n'reswitch' { createToken (TokenKind_ReSwitch); };\n'case' { createToken (TokenKind_Case); };\n'default' { createToken (TokenKind_Default); };\n'once' { createToken (TokenKind_Once); };\n'onevent' { createToken (TokenKind_OnEvent); };\n'try' { createToken (TokenKind_Try); };\n'throw' { createToken (TokenKind_Throw); };\n'catch' { createToken (TokenKind_Catch); };\n'finally' { createToken (TokenKind_Finally); };\n'nestedscope' { createToken (TokenKind_NestedScope); };\n'assert' { createToken (TokenKind_Assert); };\n'await' { createToken (TokenKind_Await); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# pre-defined values\n\n'basetype' { createKeywordTokenEx (TokenKind_BaseType, 1); };\n'basetype' [1-9] { createKeywordTokenEx (TokenKind_BaseType, te [-1] - '0'); };\n'this' { createToken (TokenKind_This); };\n'true' { createToken (TokenKind_True); };\n'false' { createToken (TokenKind_False); };\n'null' { createToken (TokenKind_Null); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# symbol tokens\n\n'++' { createToken (TokenKind_Inc); };\n'--' { createToken (TokenKind_Dec); };\n'->' { createToken (TokenKind_Ptr); };\n'=>' { createToken (TokenKind_Imply); };\n'<<' { createToken (TokenKind_Shl); };\n'>>' { createToken (TokenKind_Shr); };\n'&&' { createToken (TokenKind_LogAnd); };\n'||' { createToken (TokenKind_LogOr); };\n'==' { createToken (TokenKind_Eq); };\n'!=' { createToken (TokenKind_Ne); };\n'<=' { createToken (TokenKind_Le); };\n'>=' { createToken (TokenKind_Ge); };\n':=' { createToken (TokenKind_RefAssign); };\n'+=' { createToken (TokenKind_AddAssign); };\n'-=' { createToken (TokenKind_SubAssign); };\n'*=' { createToken (TokenKind_MulAssign); };\n'\/=' { createToken (TokenKind_DivAssign); };\n'%=' { createToken (TokenKind_ModAssign); };\n'<<=' { createToken (TokenKind_ShlAssign); };\n'>>=' { createToken (TokenKind_ShrAssign); };\n'&=' { createToken (TokenKind_AndAssign); };\n'^=' { createToken (TokenKind_XorAssign); };\n'|=' { createToken (TokenKind_OrAssign); };\n'@=' { createToken (TokenKind_AtAssign); };\n'...' { createToken (TokenKind_Ellipsis); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# literals\n\n[$fF] '\"' { preCreateFmtLiteralToken (); fcall lit_fmt; };\n'\"\"\"' (ws? '\\r'? nl)?\n\t\t\t\t { preCreateMlLiteralToken (); fgoto lit_ml; };\n\n'0' [xX] '\"\"\"' { preCreateMlLiteralToken (16); fgoto lit_ml; };\n'0' [oO] '\"\"\"' { preCreateMlLiteralToken (8); fgoto lit_ml; };\n'0' [bB] '\"\"\"' { preCreateMlLiteralToken (2); fgoto lit_ml; };\n'0' [nNdD] '\"\"\"' { preCreateMlLiteralToken (10); fgoto lit_ml; };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# lexer-time constants\n\n'__FILE__' { createSourceFileToken (); };\n'__DIR__' { createSourceDirToken (); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# common tokens\n\nid { createStringToken (TokenKind_Identifier); };\nlit_sq { createCharToken (TokenKind_Integer, 1, 1, true); };\nlit_dq_wo_esc { createStringToken (TokenKind_Literal, 1, 1, false); };\nlit_dq_w_esc { createStringToken (TokenKind_Literal, 1, 1, true); };\n[rR] raw_lit_sq { createCharToken (TokenKind_Integer, 2, 1, false); };\n[rR] raw_lit_dq { createStringToken (TokenKind_Literal, 2, 1, false); };\n'0' oct+ { createIntegerToken (8); };\ndec+ { createIntegerToken (10); };\n'0' [xX] hex+ { createIntegerToken (16, 2); };\n'0' [oO] oct+ { createIntegerToken (8, 2); };\n'0' [bB] bin+ { createIntegerToken (2, 2); };\n'0' [nNdD] dec+ { createIntegerToken (10, 2); };\n\n'0' [xX] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (16); };\n'0' [oO] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (8); };\n'0' [bB] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (2); };\n'0' [nNdD] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (10); };\ndec+ ('.' dec*) | ([eE] [+\\-]? dec+)\n\t\t\t\t { createFpToken (); };\n\n'\/\/\/' [^\\n]* { createDoxyCommentToken (TokenKind_DoxyComment1); };\n'\/\/!' [^\\n]* { createDoxyCommentToken (TokenKind_DoxyComment2); };\n'\/**' (any | nl)* :>> '*\/'\n\t\t\t\t { createDoxyCommentToken (TokenKind_DoxyComment3); };\n'\/*!' (any | nl)* :>> '*\/'\n\t\t\t\t { createDoxyCommentToken (TokenKind_DoxyComment4); };\n\n'\/\/' [^\\n]* ;\n'\/*' (any | nl)* :>> '*\/'\n\t\t\t\t ;\n\n'(' { onLeftParentheses (); };\n')' { if (!onRightParentheses ()) fret; };\n';' { if (!onSemicolon ()) fcall fmt_spec; };\n\nws | nl ;\nprint { createToken (ts [0]); };\nany { createErrorToken (ts [0]); };\n\n*|;\n\n}%%\n\n\/\/..............................................................................\n\nvoid\nLexer::init ()\n{\n\t%% write init;\n}\n\nvoid\nLexer::exec ()\n{\n\t%% write exec;\n}\n\n\/\/..............................................................................\n\n} \/\/ namespace ct\n} \/\/ namespace jnc\n","old_contents":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n\/\/ warning C4065: switch statement contains 'default' but no 'case' labels\n\n#pragma warning (disable: 4065)\n\nnamespace jnc {\nnamespace ct {\n\n\/\/..............................................................................\n\n%%{\n\nmachine jnc;\nwrite data;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# prepush \/ postpop (for fcall\/fret)\n#\n\nprepush\n{\n\tstack = prePush ();\n}\n\npostpop\n{\n\tpostPop ();\n}\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n' @{ newLine (p + 1); };\nlc_nl = '\\\\' '\\r'? nl;\nesc = '\\\\' [^\\n];\n\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* ([\"\\\\] | nl);\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* (['\\\\] | nl);\nraw_lit_dq = '\"' [^\"\\n]* ('\"' | nl);\nraw_lit_sq = \"'\" [^'\\n]* (\"'\" | nl);\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\n(nl ws?)? '\"\"\"'\n\t\t { createMlLiteralToken (); fgoto main; };\nnl ;\nany ;\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# formatting literal machines\n#\n\nlit_fmt := |*\n\nesc ;\n'$!' { createFmtLastErrorDescriptionTokens (); };\n'$' id { createFmtSimpleIdentifierTokens (); };\n'%' dec+ { createFmtIndexTokens (); };\n[$%] '(' { createFmtLiteralToken (TokenKind_FmtLiteral, *ts == '%'); m_parenthesesLevelStack.append (1); fcall main; };\n'\"' | nl { createFmtLiteralToken (TokenKind_Literal); fret; };\nany ;\n\n*|;\n\nfmt_spec := |*\n\n';' [^\")\\n]* { createFmtSpecifierToken (); fret; };\nany { ASSERT (false); fret; };\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# global declarations & pragmas\n\n'import' { createToken (TokenKind_Import); };\n'namespace' { createToken (TokenKind_Namespace); };\n'extension' { createToken (TokenKind_Extension); };\n'dynamiclib' { createToken (TokenKind_DynamicLib); };\n'using' { createToken (TokenKind_Using); };\n'friend' { createToken (TokenKind_Friend); };\n'public' { createToken (TokenKind_Public); };\n'protected' { createToken (TokenKind_Protected); };\n'alignment' { createToken (TokenKind_Alignment); };\n'setas' { createToken (TokenKind_SetAs); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# storage specifiers\n\n'typedef' { createToken (TokenKind_Typedef); };\n'alias' { createToken (TokenKind_Alias); };\n'static' { createToken (TokenKind_Static); };\n'threadlocal' { createToken (TokenKind_ThreadLocal); };\n'abstract' { createToken (TokenKind_Abstract); };\n'virtual' { createToken (TokenKind_Virtual); };\n'override' { createToken (TokenKind_Override); };\n'mutable' { createToken (TokenKind_Mutable); };\n'disposable' { createToken (TokenKind_Disposable); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# type modifiers\n\n'unsigned' { createToken (TokenKind_Unsigned); };\n'bigendian' { createToken (TokenKind_BigEndian); };\n'const' { createToken (TokenKind_Const); };\n'readonly' { createToken (TokenKind_ReadOnly); };\n'cmut' { createToken (TokenKind_CMut); };\n'volatile' { createToken (TokenKind_Volatile); };\n'weak' { createToken (TokenKind_Weak); };\n'thin' { createToken (TokenKind_Thin); };\n'safe' { createToken (TokenKind_Safe); };\n'unsafe' { createToken (TokenKind_Unsafe); };\n'errorcode' { createToken (TokenKind_ErrorCode); };\n'cdecl' { createToken (TokenKind_Cdecl); };\n'stdcall' { createToken (TokenKind_Stdcall); };\n'jnccall' { createToken (TokenKind_Jnccall); };\n'thiscall' { createToken (TokenKind_Thiscall); };\n'array' { createToken (TokenKind_Array); };\n'function' { createToken (TokenKind_Function); };\n'property' { createToken (TokenKind_Property); };\n'bindable' { createToken (TokenKind_Bindable); };\n'autoget' { createToken (TokenKind_AutoGet); };\n'indexed' { createToken (TokenKind_Indexed); };\n'multicast' { createToken (TokenKind_Multicast); };\n'event' { createToken (TokenKind_Event); };\n'reactor' { createToken (TokenKind_Reactor); };\n'async' { createToken (TokenKind_Async); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# type specifiers\n\n'anydata' { createToken (TokenKind_AnyData); };\n'void' { createToken (TokenKind_Void); };\n'variant' { createToken (TokenKind_Variant); };\n'bool' { createToken (TokenKind_Bool); };\n'int' { createToken (TokenKind_Int); };\n'intptr' { createToken (TokenKind_IntPtr); };\n'char' { createToken (TokenKind_Char); };\n'short' { createToken (TokenKind_Short); };\n'long' { createToken (TokenKind_Long); };\n'float' { createToken (TokenKind_Float); };\n'double' { createToken (TokenKind_Double); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# named type specifiers\n\n'enum' { createToken (TokenKind_Enum); };\n'struct' { createToken (TokenKind_Struct); };\n'union' { createToken (TokenKind_Union); };\n'class' { createToken (TokenKind_Class); };\n'opaque' { createToken (TokenKind_Opaque); };\n'exposed' { createToken (TokenKind_Exposed); };\n'bitflag' { createToken (TokenKind_BitFlag); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# special member methods\n\n'get' { createToken (TokenKind_Get); };\n'set' { createToken (TokenKind_Set); };\n'preconstruct' { createToken (TokenKind_PreConstruct); };\n'construct' { createToken (TokenKind_Construct); };\n'destruct' { createToken (TokenKind_Destruct); };\n'operator' { createToken (TokenKind_Operator); };\n'postfix' { createToken (TokenKind_Postfix); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# operators\n\n'new' { createToken (TokenKind_New); };\n'sizeof' { createToken (TokenKind_SizeOf); };\n'countof' { createToken (TokenKind_CountOf); };\n'offsetof' { createToken (TokenKind_OffsetOf); };\n'typeof' { createToken (TokenKind_TypeOf); };\n'bindingof' { createToken (TokenKind_BindingOf); };\n'dynamic' { createToken (TokenKind_Dynamic); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# statements\n\n'if' { createToken (TokenKind_If); };\n'else' { createToken (TokenKind_Else); };\n'for' { createToken (TokenKind_For); };\n'while' { createToken (TokenKind_While); };\n'do' { createToken (TokenKind_Do); };\n'break' { createKeywordTokenEx (TokenKind_Break, 1); };\n'break' [1-9] { createKeywordTokenEx (TokenKind_Break, te [-1] - '0'); };\n'continue' { createKeywordTokenEx (TokenKind_Continue, 1); };\n'continue' [1-9] { createKeywordTokenEx (TokenKind_Continue, te [-1] - '0'); };\n'return' { createToken (TokenKind_Return); };\n'switch' { createToken (TokenKind_Switch); };\n'reswitch' { createToken (TokenKind_ReSwitch); };\n'case' { createToken (TokenKind_Case); };\n'default' { createToken (TokenKind_Default); };\n'once' { createToken (TokenKind_Once); };\n'onevent' { createToken (TokenKind_OnEvent); };\n'try' { createToken (TokenKind_Try); };\n'throw' { createToken (TokenKind_Throw); };\n'catch' { createToken (TokenKind_Catch); };\n'finally' { createToken (TokenKind_Finally); };\n'nestedscope' { createToken (TokenKind_NestedScope); };\n'assert' { createToken (TokenKind_Assert); };\n'await' { createToken (TokenKind_Await); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# pre-defined values\n\n'basetype' { createKeywordTokenEx (TokenKind_BaseType, 1); };\n'basetype' [1-9] { createKeywordTokenEx (TokenKind_BaseType, te [-1] - '0'); };\n'this' { createToken (TokenKind_This); };\n'true' { createToken (TokenKind_True); };\n'false' { createToken (TokenKind_False); };\n'null' { createToken (TokenKind_Null); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# symbol tokens\n\n'++' { createToken (TokenKind_Inc); };\n'--' { createToken (TokenKind_Dec); };\n'->' { createToken (TokenKind_Ptr); };\n'=>' { createToken (TokenKind_Imply); };\n'<<' { createToken (TokenKind_Shl); };\n'>>' { createToken (TokenKind_Shr); };\n'&&' { createToken (TokenKind_LogAnd); };\n'||' { createToken (TokenKind_LogOr); };\n'==' { createToken (TokenKind_Eq); };\n'!=' { createToken (TokenKind_Ne); };\n'<=' { createToken (TokenKind_Le); };\n'>=' { createToken (TokenKind_Ge); };\n':=' { createToken (TokenKind_RefAssign); };\n'+=' { createToken (TokenKind_AddAssign); };\n'-=' { createToken (TokenKind_SubAssign); };\n'*=' { createToken (TokenKind_MulAssign); };\n'\/=' { createToken (TokenKind_DivAssign); };\n'%=' { createToken (TokenKind_ModAssign); };\n'<<=' { createToken (TokenKind_ShlAssign); };\n'>>=' { createToken (TokenKind_ShrAssign); };\n'&=' { createToken (TokenKind_AndAssign); };\n'^=' { createToken (TokenKind_XorAssign); };\n'|=' { createToken (TokenKind_OrAssign); };\n'@=' { createToken (TokenKind_AtAssign); };\n'...' { createToken (TokenKind_Ellipsis); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# literals\n\n[$fF] '\"' { preCreateFmtLiteralToken (); fcall lit_fmt; };\n'\"\"\"' (ws? '\\r'? nl)?\n\t\t\t\t { preCreateMlLiteralToken (); fgoto lit_ml; };\n\n'0' [xX] '\"\"\"' { preCreateMlLiteralToken (16); fgoto lit_ml; };\n'0' [oO] '\"\"\"' { preCreateMlLiteralToken (8); fgoto lit_ml; };\n'0' [bB] '\"\"\"' { preCreateMlLiteralToken (2); fgoto lit_ml; };\n'0' [nNdD] '\"\"\"' { preCreateMlLiteralToken (10); fgoto lit_ml; };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# lexer-time constants\n\n'__FILE__' { createSourceFileToken (); };\n'__DIR__' { createSourceDirToken (); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n# common tokens\n\nid { createStringToken (TokenKind_Identifier); };\nlit_sq { createCharToken (TokenKind_Integer, 1, 1, true); };\nlit_dq { createStringToken (TokenKind_Literal, 1, 1, true); };\n[rR] raw_lit_sq { createCharToken (TokenKind_Integer, 2, 1, false); };\n[rR] raw_lit_dq { createStringToken (TokenKind_Literal, 2, 1, false); };\n'0' oct+ { createIntegerToken (8); };\ndec+ { createIntegerToken (10); };\n'0' [xX] hex+ { createIntegerToken (16, 2); };\n'0' [oO] oct+ { createIntegerToken (8, 2); };\n'0' [bB] bin+ { createIntegerToken (2, 2); };\n'0' [nNdD] dec+ { createIntegerToken (10, 2); };\n\n'0' [xX] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (16); };\n'0' [oO] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (8); };\n'0' [bB] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (2); };\n'0' [nNdD] raw_lit_dq\n\t\t\t\t { createBinLiteralToken (10); };\ndec+ ('.' dec*) | ([eE] [+\\-]? dec+)\n\t\t\t\t { createFpToken (); };\n\n'\/\/\/' [^\\n]* { createDoxyCommentToken (TokenKind_DoxyComment1); };\n'\/\/!' [^\\n]* { createDoxyCommentToken (TokenKind_DoxyComment2); };\n'\/**' (any | nl)* :>> '*\/'\n\t\t\t\t { createDoxyCommentToken (TokenKind_DoxyComment3); };\n'\/*!' (any | nl)* :>> '*\/'\n\t\t\t\t { createDoxyCommentToken (TokenKind_DoxyComment4); };\n\n'\/\/' [^\\n]* ;\n'\/*' (any | nl)* :>> '*\/'\n\t\t\t\t ;\n\n'(' { onLeftParentheses (); };\n')' { if (!onRightParentheses ()) fret; };\n';' { if (!onSemicolon ()) fcall fmt_spec; };\n\nws | nl ;\nprint { createToken (ts [0]); };\nany { createErrorToken (ts [0]); };\n\n*|;\n\n}%%\n\n\/\/..............................................................................\n\nvoid\nLexer::init ()\n{\n\t%% write init;\n}\n\nvoid\nLexer::exec ()\n{\n\t%% write exec;\n}\n\n\/\/..............................................................................\n\n} \/\/ namespace ct\n} \/\/ namespace jnc\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"362d5cc58f88cd6e86736b9e71bcac11e929594d","subject":"Tell ruby that parsed strings are external (for encoding)","message":"Tell ruby that parsed strings are external (for encoding)","repos":"elabs\/stomp_parser,elabs\/stompede,elabs\/stomp_parser,elabs\/stompede","old_file":"ext\/stompede\/c_parser.c.rl","new_file":"ext\/stompede\/c_parser.c.rl","new_contents":"#include \n\n#if DEBUG_H\n# define DEBUG(fmt, ...) do { fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__); } while(0)\n#else\n# define DEBUG(...)\n#endif\n\n#define UNUSED(x) (void)(x)\n#define MARK_LEN (p - mark)\n#define MARK_STR_NEW() rb_external_str_new(mark, MARK_LEN)\n\n#define true 1\n#define false 0\n\ntypedef struct {\n VALUE error;\n\n size_t max_message_size;\n\n const char *chunk;\n const char *p;\n int cs;\n const char *mark;\n const char *mark_key;\n VALUE mark_message;\n size_t mark_message_size;\n size_t mark_message_content_length;\n} parser_state_t;\n\nVALUE mStomp = Qnil;\nVALUE cMessage = Qnil;\nID g_new;\nID g_write_command;\nID g_write_body;\nID g_build_parse_error;\nID g_max_message_size;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = rb_funcall(cMessage, g_new, 2, Qnil, Qnil);\n mark_message_size = 0;\n }\n\n action write_command {\n rb_funcall(mark_message, g_write_command, 1, MARK_STR_NEW());\n mark = NULL;\n }\n\n action mark_key {\n \/*\n mk = MARK_STR_NEW;\n mark = NULL;\n *\/\n }\n\n action write_header {\n \/*\n VALUE value = MARK_STR_NEW;\n mark = NULL;\n\n rb_funcall(message, rb_intern(\"write_header\"), 2, mk, value);\n mk = Qnil;\n *\/\n }\n\n action finish_headers {\n \/*\n VALUE length = rb_funcall(message, rb_intern(\"content_length\"), 0);\n if (FIXNUM_P(length)) {\n content_length = FIX2LONG(length);\n } else {\n content_length = -1;\n }\n *\/\n }\n\n action write_body {\n rb_funcall(mark_message, g_write_body, 1, MARK_STR_NEW());\n mark = NULL;\n }\n\n action consume_null {\n false\n \/* ((content_length != -1) && (MARK_LEN < content_length)) *\/\n }\n\n action consume_octet {\n true\n \/* ((content_length == -1) || (MARK_LEN < content_length)) *\/\n }\n\n action check_message_size {\n mark_message_size += 1;\n }\n\n action finish_message {\n rb_yield(mark_message);\n mark_message = Qnil;\n }\n\n include message_common \"parser_common.rl\";\n\n write data noprefix;\n}%%\n\nstatic void parser_free(parser_state_t *state) {\n \/\/ TODO: free memory inside struct!\n xfree(state);\n}\n\nstatic void parser_mark(parser_state_t *state) {\n rb_gc_mark(state->mark_message);\n rb_gc_mark(state->error);\n}\n\nstatic VALUE parser_alloc(VALUE klass) {\n parser_state_t *state = ALLOC(parser_state_t);\n return Data_Wrap_Struct(klass, parser_mark, parser_free, state);\n}\n\nstatic VALUE parser_initialize(int argc, VALUE *argv, VALUE self) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n VALUE max_message_size;\n rb_scan_args(argc, argv, \"01\", &max_message_size);\n\n if (max_message_size == Qnil) {\n max_message_size = rb_funcall(mStomp, g_max_message_size, 0);\n }\n\n state->error = Qnil;\n state->max_message_size = FIX2LONG(max_message_size);\n state->chunk = NULL;\n state->p = NULL;\n state->cs = start;\n state->mark = NULL;\n state->mark_key = NULL;\n state->mark_message = Qnil;\n state->mark_message_size = 0;\n state->mark_message_content_length = 0;\n\n return self;\n}\n\nstatic VALUE parser_parse(VALUE self, VALUE chunk) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n if (NIL_P(state->error)) {\n \/*\n if state.chunk\n p = state.chunk.bytesize\n chunk = state.chunk << chunk\n else\n p = 0\n end\n\n pe = chunk.bytesize # special\n *\/\n\n \/\/ size_t max_message_size = state->max_message_size;\n const char *p = RSTRING_PTR(chunk);\n const char *pe = p + RSTRING_LEN(chunk);\n\n int cs = state->cs;\n const char *mark = state->mark;\n \/\/ mark_key = state->mark_key;\n VALUE mark_message = state->mark_message;\n size_t mark_message_size = state->mark_message_size;\n \/\/ mark_content_length = state->mark_content_length;\n\n %% write exec;\n\n \/*\n if mark\n state.p = chunk.bytesize\n state.chunk = chunk\n else\n state.p = 0\n state.chunk = nil\n end\n *\/\n\n state->cs = cs;\n state->mark = mark;\n \/\/ state->mark_key = mark_key;\n state->mark_message = mark_message;\n state->mark_message_size = mark_message_size;\n \/\/ state->mark_content_length = mark_content_length;\n\n if (cs == error) {\n long index = p - RSTRING_PTR(chunk);\n state->error = rb_funcall(mStomp, g_build_parse_error, 2, chunk, LONG2NUM(index));\n }\n }\n\n if ( ! NIL_P(state->error)) {\n rb_exc_raise(state->error);\n }\n\n return Qnil;\n}\n\nvoid Init_c_parser(void) {\n VALUE mStompede = rb_const_get(rb_cObject, rb_intern(\"Stompede\"));\n\n mStomp = rb_const_get(mStompede, rb_intern(\"Stomp\"));\n cMessage = rb_const_get(mStomp, rb_intern(\"Message\"));\n\n g_new = rb_intern(\"new\");\n g_write_command = rb_intern(\"write_command\");\n g_write_body = rb_intern(\"write_body\");\n g_build_parse_error = rb_intern(\"build_parse_error\");\n g_max_message_size = rb_intern(\"max_message_size\");\n\n VALUE cParser = rb_define_class_under(mStomp, \"CParser\", rb_cObject);\n rb_define_alloc_func(cParser, parser_alloc);\n\n rb_define_method(cParser, \"initialize\", parser_initialize, -1);\n rb_define_method(cParser, \"parse\", parser_parse, 1);\n}\n","old_contents":"#include \n\n#if DEBUG_H\n# define DEBUG(fmt, ...) do { fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__); } while(0)\n#else\n# define DEBUG(...)\n#endif\n\n#define UNUSED(x) (void)(x)\n#define MARK_LEN (p - mark)\n#define MARK_STR_NEW() rb_str_new(mark, MARK_LEN)\n\n#define true 1\n#define false 0\n\ntypedef struct {\n VALUE error;\n\n size_t max_message_size;\n\n const char *chunk;\n const char *p;\n int cs;\n const char *mark;\n const char *mark_key;\n VALUE mark_message;\n size_t mark_message_size;\n size_t mark_message_content_length;\n} parser_state_t;\n\nVALUE mStomp = Qnil;\nVALUE cMessage = Qnil;\nID g_new;\nID g_write_command;\nID g_write_body;\nID g_build_parse_error;\nID g_max_message_size;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = rb_funcall(cMessage, g_new, 2, Qnil, Qnil);\n mark_message_size = 0;\n }\n\n action write_command {\n rb_funcall(mark_message, g_write_command, 1, MARK_STR_NEW());\n mark = NULL;\n }\n\n action mark_key {\n \/*\n mk = MARK_STR_NEW;\n mark = NULL;\n *\/\n }\n\n action write_header {\n \/*\n VALUE value = MARK_STR_NEW;\n mark = NULL;\n\n rb_funcall(message, rb_intern(\"write_header\"), 2, mk, value);\n mk = Qnil;\n *\/\n }\n\n action finish_headers {\n \/*\n VALUE length = rb_funcall(message, rb_intern(\"content_length\"), 0);\n if (FIXNUM_P(length)) {\n content_length = FIX2LONG(length);\n } else {\n content_length = -1;\n }\n *\/\n }\n\n action write_body {\n rb_funcall(mark_message, g_write_body, 1, MARK_STR_NEW());\n mark = NULL;\n }\n\n action consume_null {\n false\n \/* ((content_length != -1) && (MARK_LEN < content_length)) *\/\n }\n\n action consume_octet {\n true\n \/* ((content_length == -1) || (MARK_LEN < content_length)) *\/\n }\n\n action check_message_size {\n mark_message_size += 1;\n }\n\n action finish_message {\n rb_yield(mark_message);\n mark_message = Qnil;\n }\n\n include message_common \"parser_common.rl\";\n\n write data noprefix;\n}%%\n\nstatic void parser_free(parser_state_t *state) {\n \/\/ TODO: free memory inside struct!\n xfree(state);\n}\n\nstatic void parser_mark(parser_state_t *state) {\n rb_gc_mark(state->mark_message);\n rb_gc_mark(state->error);\n}\n\nstatic VALUE parser_alloc(VALUE klass) {\n parser_state_t *state = ALLOC(parser_state_t);\n return Data_Wrap_Struct(klass, parser_mark, parser_free, state);\n}\n\nstatic VALUE parser_initialize(int argc, VALUE *argv, VALUE self) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n VALUE max_message_size;\n rb_scan_args(argc, argv, \"01\", &max_message_size);\n\n if (max_message_size == Qnil) {\n max_message_size = rb_funcall(mStomp, g_max_message_size, 0);\n }\n\n state->error = Qnil;\n state->max_message_size = FIX2LONG(max_message_size);\n state->chunk = NULL;\n state->p = NULL;\n state->cs = start;\n state->mark = NULL;\n state->mark_key = NULL;\n state->mark_message = Qnil;\n state->mark_message_size = 0;\n state->mark_message_content_length = 0;\n\n return self;\n}\n\nstatic VALUE parser_parse(VALUE self, VALUE chunk) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n if (NIL_P(state->error)) {\n \/*\n if state.chunk\n p = state.chunk.bytesize\n chunk = state.chunk << chunk\n else\n p = 0\n end\n\n pe = chunk.bytesize # special\n *\/\n\n \/\/ size_t max_message_size = state->max_message_size;\n const char *p = RSTRING_PTR(chunk);\n const char *pe = p + RSTRING_LEN(chunk);\n\n int cs = state->cs;\n const char *mark = state->mark;\n \/\/ mark_key = state->mark_key;\n VALUE mark_message = state->mark_message;\n size_t mark_message_size = state->mark_message_size;\n \/\/ mark_content_length = state->mark_content_length;\n\n %% write exec;\n\n \/*\n if mark\n state.p = chunk.bytesize\n state.chunk = chunk\n else\n state.p = 0\n state.chunk = nil\n end\n *\/\n\n state->cs = cs;\n state->mark = mark;\n \/\/ state->mark_key = mark_key;\n state->mark_message = mark_message;\n state->mark_message_size = mark_message_size;\n \/\/ state->mark_content_length = mark_content_length;\n\n if (cs == error) {\n long index = p - RSTRING_PTR(chunk);\n state->error = rb_funcall(mStomp, g_build_parse_error, 2, chunk, LONG2NUM(index));\n }\n }\n\n if ( ! NIL_P(state->error)) {\n rb_exc_raise(state->error);\n }\n\n return Qnil;\n}\n\nvoid Init_c_parser(void) {\n VALUE mStompede = rb_const_get(rb_cObject, rb_intern(\"Stompede\"));\n\n mStomp = rb_const_get(mStompede, rb_intern(\"Stomp\"));\n cMessage = rb_const_get(mStomp, rb_intern(\"Message\"));\n\n g_new = rb_intern(\"new\");\n g_write_command = rb_intern(\"write_command\");\n g_write_body = rb_intern(\"write_body\");\n g_build_parse_error = rb_intern(\"build_parse_error\");\n g_max_message_size = rb_intern(\"max_message_size\");\n\n VALUE cParser = rb_define_class_under(mStomp, \"CParser\", rb_cObject);\n rb_define_alloc_func(cParser, parser_alloc);\n\n rb_define_method(cParser, \"initialize\", parser_initialize, -1);\n rb_define_method(cParser, \"parse\", parser_parse, 1);\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"ec391e019c917cbbfa0f9d9902042bf01b09afce","subject":"interpret two single quotes ('') as a single one (')","message":"interpret two single quotes ('') as a single one (')\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner.rl","new_file":"src\/mfilescanner.rl","new_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << '\"';\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << '\"';\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","old_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << '\"';\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << '\"';\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"f8eb255dd3c5b2172498900340b42c35e90c2f8e","subject":"[mfilescanner] implement Feature #222","message":"[mfilescanner] implement Feature #222\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner_parser.rl","new_file":"src\/mfilescanner_parser.rl","new_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n @{ fout_ << \"\\n\";\n fout_.write(tmp_p, p - tmp_p);\n tmp_p = p+1; fout_ << \" *\";\n }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p); }\n )*\n $!{\n fout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n fhold;\n while (*p == ' ')\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # RAGEL comment: else: a regular comment\n ( (default - '|')\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( ([ \\t]+ \n @{\n {\n int i=0;\n if (*(p+1) != ' ' && *(p+1) != '\\t')\n {\n while (*(p-i) == ' ' || *(p-i) == '\\t')\n i++;\n if (*(p-i) == '\\n')\n fout_ << std::string(i, ' ');\n }\n }\n })\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # white space or line continuation\n WS =\n ( [ \\t]+\n | ('...'.[\\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | ',' | EOL\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n if (s==std::string(\"~\"))\n {\n param_list_[s].push_back(\"This parameter is marked as \\\"~\\\" in the original m-File and thus not used.\");\n }\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n \n matrix_or_cell := (\n '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n ( (WSOC | EOL )+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n if (s==std::string(\"~\"))\n {\n return_list_[s].push_back(\"This parameter is marked as \\\"~\\\" in the original m-File and thus not used.\");\n }\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n if (s==std::string(\"~\"))\n {\n return_list_[s].push_back(\"This parameter is marked as \\\"~\\\" in the original m-File and thus not used.\");\n }\n\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (IDENT %{tmp_string.assign(ts,p-ts);})\n . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n varargin_parser_candidate_ = tmp_string;\n };\n\n ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n\n\n ('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n ('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL ) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n \n ('\\'')\n => { fout_ << \"^t\"; };\n\n # simply output all other characters\n (default - [\\n{}\\'])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # things that could end the function body {{{4\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n tmp_string.assign(ts,p-ts+1);\n p = ts-1;\n\n if (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # RAGEL comment: ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # RAGEL comment: ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.abstr = true;\n } )\n | ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.abortSet = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n fout_ << string(ts, ts+funcindent_);\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n fgoto methods;\n }\n );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n {\n char *i = tmp_p-1;\n for (; *i == ' ' || *i == '\\t'; --i)\n fout_ << *i;\n }\n \n end_of_property_doc();\n string s(tmp_p, p - tmp_p);\n if (s == \"end\")\n fgoto classbody;\n if (propertyparams_.dependent)\n specifier_[s].dependent = true;\n property_list_.push_back(s);\n \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n undoced_prop_ = true;\n }\n )\n . WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n |\n ( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n @{\n defaultprop_ = string(tmp_p2, p - tmp_p2);\n string::size_type last_elem = defaultprop_.length() -1;\n if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n {\n defaultprop_[0] = '\\\"';\n defaultprop_[last_elem] = '\\\"';\n }\n string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n string::size_type last_paren;\n if (first_paren == string::npos)\n {\n first_paren = 1;\n last_paren = last_elem;\n }\n else\n {\n last_paren = defaultprop_.find_last_of(\")]}\");\n if (last_paren == string::npos)\n last_paren=last_elem-1;\n else\n {\n if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n {\n first_paren++;\n last_paren--;\n }\n defaultprop_.insert(first_paren, 1,'\"');\n defaultprop_.insert(last_paren+2, 1,'\"');\n first_paren++;\n last_paren++;\n }\n }\n for (unsigned int i = first_paren; i < last_paren; ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = ' ';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n else if(defaultprop_[i] == '\\\"')\n defaultprop_[i] = '\\'';\n else if(defaultprop_[i] == '@')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n else if(defaultprop_[i] == '\\n')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n }\n }\n )\n );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n (prop)\n |\n ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (WSOC); # => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n std::map::iterator specIt;\n for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n {\n fout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n if ( (*specIt).second.dependent)\n {\n if( (*specIt).second.getter && ! (*specIt).second.setter )\n {\n fout_ << \"@note [readonly]\\n *\";\n }\n }\n else\n {\n fout_ << \"@note This property has custom functionality when its value is \";\n if ((*specIt).second.getter)\n {\n fout_ << \"retrieved\";\n if ((*specIt).second.setter)\n fout_ << \" or changed\";\n }\n else if ((*specIt).second.setter)\n fout_ << \"changed\";\n fout_ << \".\";\n }\n fout_ << \"\\n *\/\\n\";\n }\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Event;\n fgoto properties;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n {\n int i = 0;\n for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n ;\n std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any\n @{\n fhold;\n tmp_p = p;\n }\n .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p-=8;\n char *tp;\n for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n ;\n funcindent_ = (int)(p - tp);\n#if DEBUG\n {\n ostringstream oss;\n oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n debug_output(oss.str(), p);\n }\n#endif\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p-=8;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string, tmp_string2, tmp_string3;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","old_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n @{ fout_ << \"\\n\";\n fout_.write(tmp_p, p - tmp_p);\n tmp_p = p+1; fout_ << \" *\";\n }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p); }\n )*\n $!{\n fout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n fhold;\n while (*p == ' ')\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # RAGEL comment: else: a regular comment\n ( (default - '|')\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( ([ \\t]+ \n @{\n {\n int i=0;\n if (*(p+1) != ' ' && *(p+1) != '\\t')\n {\n while (*(p-i) == ' ' || *(p-i) == '\\t')\n i++;\n if (*(p-i) == '\\n')\n fout_ << std::string(i, ' ');\n }\n }\n })\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # white space or line continuation\n WS =\n ( [ \\t]+\n | ('...'.[\\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | ',' | EOL\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n \n matrix_or_cell := (\n '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n ( (WSOC | EOL )+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (IDENT %{tmp_string.assign(ts,p-ts);})\n . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n varargin_parser_candidate_ = tmp_string;\n };\n\n ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n }\n };\n\n\n ('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);} ) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n ('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL ) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n \n ((IDENT %{tmp_string.assign(ts, p - ts);})\n . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\''\n . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok) %{tmp_string3.assign(tmp_p, p - tmp_p);}) . (';' | EOL) )\n => {\n fout_.write(ts, te-ts);\n if (tmp_string == varargin_parser_candidate_ )\n {\n extract_default_argument_of_inputparser(tmp_string3);\n varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n }\n if (*p == '\\n')\n fgoto funcbody;\n };\n\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n \n ('\\'')\n => { fout_ << \"^t\"; };\n\n # simply output all other characters\n (default - [\\n{}\\'])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n => {\n assert(p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # things that could end the function body {{{4\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n tmp_string.assign(ts,p-ts+1);\n p = ts-1;\n\n if (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # RAGEL comment: ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # RAGEL comment: ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.abstr = true;\n } )\n | ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n @{\n propertyparams_.abortSet = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n fout_ << string(ts, ts+funcindent_);\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n fgoto methods;\n }\n );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n {\n char *i = tmp_p-1;\n for (; *i == ' ' || *i == '\\t'; --i)\n fout_ << *i;\n }\n \n end_of_property_doc();\n string s(tmp_p, p - tmp_p);\n if (s == \"end\")\n fgoto classbody;\n if (propertyparams_.dependent)\n specifier_[s].dependent = true;\n property_list_.push_back(s);\n \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n undoced_prop_ = true;\n }\n )\n . WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n |\n ( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n @{\n defaultprop_ = string(tmp_p2, p - tmp_p2);\n string::size_type last_elem = defaultprop_.length() -1;\n if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n {\n defaultprop_[0] = '\\\"';\n defaultprop_[last_elem] = '\\\"';\n }\n string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n string::size_type last_paren;\n if (first_paren == string::npos)\n {\n first_paren = 1;\n last_paren = last_elem;\n }\n else\n {\n last_paren = defaultprop_.find_last_of(\")]}\");\n if (last_paren == string::npos)\n last_paren=last_elem-1;\n else\n {\n if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n {\n first_paren++;\n last_paren--;\n }\n defaultprop_.insert(first_paren, 1,'\"');\n defaultprop_.insert(last_paren+2, 1,'\"');\n first_paren++;\n last_paren++;\n }\n }\n for (unsigned int i = first_paren; i < last_paren; ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = ' ';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n else if(defaultprop_[i] == '\\\"')\n defaultprop_[i] = '\\'';\n else if(defaultprop_[i] == '@')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n else if(defaultprop_[i] == '\\n')\n {\n defaultprop_.insert(i, 1, '\\\\');\n ++i;\n }\n }\n }\n )\n );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n (prop)\n |\n ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full, methodparams_, propertyparams_);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p);\n fcall in_comment_block;\n };\n\n (WSOC); # => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n std::map::iterator specIt;\n for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n {\n fout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n if ( (*specIt).second.dependent)\n {\n if( (*specIt).second.getter && ! (*specIt).second.setter )\n {\n fout_ << \"@note [readonly]\\n *\";\n }\n }\n else\n {\n fout_ << \"@note This property has custom functionality when its value is \";\n if ((*specIt).second.getter)\n {\n fout_ << \"retrieved\";\n if ((*specIt).second.setter)\n fout_ << \" or changed\";\n }\n else if ((*specIt).second.setter)\n fout_ << \"changed\";\n fout_ << \".\";\n }\n fout_ << \"\\n *\/\\n\";\n }\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Event;\n fgoto properties;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n {\n int i = 0;\n for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n ;\n std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property || class_part_ == Event)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fout_ << whitespaces;\n fgoto funcbody;\n }\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any\n @{\n fhold;\n tmp_p = p;\n }\n .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p-=8;\n char *tp;\n for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n ;\n funcindent_ = (int)(p - tp);\n#if DEBUG\n {\n ostringstream oss;\n oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n debug_output(oss.str(), p);\n }\n#endif\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p-=8;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string, tmp_string2, tmp_string3;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"e40f51bdd7e4ca53c57dae45dd7bfbe14bbab103","subject":"Set the method just when it has finished to parse.","message":"Set the method just when it has finished to parse.\n","repos":"lscube\/feng,lscube\/feng,winlinvip\/feng,lscube\/feng,winlinvip\/feng,winlinvip\/feng","old_file":"src\/network\/ragel_request.rl","new_file":"src\/network\/ragel_request.rl","new_contents":"\/* -*- c -*- *\/\n\n%% machine rtsp_request;\n\nstatic void ragel_parse_request(RTSP_Request *req, const char *msg) {\n int cs;\n const char *p = msg, *pe = p + strlen(msg), *eof, *s;\n\n \/* Variables used for adding headers to the hash table *\/\n const char *hdr, *hdr_val;\n size_t hdr_size, hdr_val_size;\n\n \/* We want to express clearly which versions we support, so that we\n * can return right away if an unsupported one is found.\n *\/\n\n %%{\n SP = ' ';\n CRLF = \"\\r\\n\";\n\n action set_s {\n s = p;\n }\n\n action end_method {\n req->method = g_strndup(s, p-s);\n }\n \n Supported_Method =\n \"DESCRIBE\" % { req->method_id = RTSP_ID_DESCRIBE; } |\n \"OPTIONS\" % { req->method_id = RTSP_ID_OPTIONS; } |\n \"PAUSE\" % { req->method_id = RTSP_ID_PAUSE; } |\n \"PLAY\" % { req->method_id = RTSP_ID_PLAY; } |\n \"SETUP\" % { req->method_id = RTSP_ID_SETUP; } |\n \"TEARDOWN\" % { req->method_id = RTSP_ID_TEARDOWN; };\n\n Method = (Supported_Method | alpha+ )\n > set_s % end_method;\n\n action end_version {\n req->version = g_strndup(s, p-s);\n }\n\n Version = (alpha+ . '\/' . [0-9] '.' [0-9]);\n\n action end_object {\n req->object = g_strndup(s, p-s);\n }\n \n Request_Line = (Supported_Method | Method) . SP \n (print*) > set_s % end_object . SP\n Version > set_s % end_version . CRLF;\n\n action hdr_start {\n hdr = p;\n }\n\n action hdr_end {\n hdr_size = p-hdr;\n }\n\n action hdr_val_start {\n hdr_val = p;\n }\n\n action hdr_val_end {\n hdr_val_size = p-hdr_val;\n }\n\n Header = (alpha|'-')+ > hdr_start % hdr_end \n . ':' . SP . print+ > hdr_val_start % hdr_val_end . CRLF;\n\n action save_header {\n {\n g_hash_table_insert(req->headers,\n g_strndup(hdr, hdr_size),\n g_strndup(hdr_val, hdr_val_size));\n }\n }\n\n main := Request_Line . ( Header @ save_header )+;\n\n write data;\n write init;\n write exec;\n }%%\n\n \/** @todo this should return a boolean false when parsing fails *\/\n}\n","old_contents":"\/* -*- c -*- *\/\n\n%% machine rtsp_request;\n\nstatic void ragel_parse_request(RTSP_Request *req, const char *msg) {\n int cs;\n const char *p = msg, *pe = p + strlen(msg), *eof, *s;\n\n \/* Variables used for adding headers to the hash table *\/\n const char *hdr, *hdr_val;\n size_t hdr_size, hdr_val_size;\n\n \/* We want to express clearly which versions we support, so that we\n * can return right away if an unsupported one is found.\n *\/\n\n %%{\n SP = ' ';\n CRLF = \"\\r\\n\";\n\n action set_s {\n s = p;\n }\n\n action end_method {\n req->method = g_strndup(s, p-s);\n }\n \n Supported_Method =\n \"DESCRIBE\" @ { req->method_id = RTSP_ID_DESCRIBE; } |\n \"OPTIONS\" @ { req->method_id = RTSP_ID_OPTIONS; } |\n \"PAUSE\" @ { req->method_id = RTSP_ID_PAUSE; } |\n \"PLAY\" @ { req->method_id = RTSP_ID_PLAY; } |\n \"SETUP\" @ { req->method_id = RTSP_ID_SETUP; } |\n \"TEARDOWN\" @ { req->method_id = RTSP_ID_TEARDOWN; };\n\n Method = (Supported_Method | alpha+ )\n > set_s % end_method;\n\n action end_version {\n req->version = g_strndup(s, p-s);\n }\n\n Version = (alpha+ . '\/' . [0-9] '.' [0-9]);\n\n action end_object {\n req->object = g_strndup(s, p-s);\n }\n \n Request_Line = (Supported_Method | Method) . SP \n (print*) > set_s % end_object . SP\n Version > set_s % end_version . CRLF;\n\n action hdr_start {\n hdr = p;\n }\n\n action hdr_end {\n hdr_size = p-hdr;\n }\n\n action hdr_val_start {\n hdr_val = p;\n }\n\n action hdr_val_end {\n hdr_val_size = p-hdr_val;\n }\n\n Header = (alpha|'-')+ > hdr_start % hdr_end \n . ':' . SP . print+ > hdr_val_start % hdr_val_end . CRLF;\n\n action save_header {\n {\n g_hash_table_insert(req->headers,\n g_strndup(hdr, hdr_size),\n g_strndup(hdr_val, hdr_val_size));\n }\n }\n\n main := Request_Line . ( Header @ save_header )+;\n\n write data;\n write init;\n write exec;\n }%%\n\n \/** @todo this should return a boolean false when parsing fails *\/\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"5d0abfa1e3541cf1d894bb546ee92d52e4690a12","subject":"changed xyclassEnum to xyclassInstances for enum support","message":"changed xyclassEnum to xyclassInstances for enum support\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner_parser.rl","new_file":"src\/mfilescanner_parser.rl","new_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n\t @{ fout_ << \"\\n\";\n\t\tfout_.write(tmp_p, p - tmp_p);\n\t\ttmp_p = p+1; fout_ << \" *\";\n\t }\n # and then some default characters\n . ( ( (default - [\\r\\n])* )\n\t %{ fout_.write(tmp_p, p - tmp_p); } )\n\t . EOL\n )*\n $!{\n\tfout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n\tfhold;\n\twhile (*p == ' ')\n\t fhold;\n\tif (extra_hold_in_cblock)\n\t{\n\t fhold;\n\t --line;\n\t extra_hold_in_cblock = false;\n\t}\n\tfret;\n };\n\n action end_doxy_block\n {\n\tif(!docline)\n\t{\n\t p = ts-1;\n\t \/* go backward until first non-whitespace is found *\/\n\t for(p=p-1; *p==' ' || *p == '\\t'; --p)\n\t\t;\n\n\t if(is_class_)\n\t {\n\t\tif(class_part_ == Header)\n\t\t{\n\t\t end_of_class_doc();\n\t\t fgoto classbody;\n\t\t} else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t\telse if(class_part_ == MethodDeclaration)\n\t\t{\n\t\t fgoto funcdef;\n\t\t}\n\t\telse if(class_part_ == Property || class_part_ == Event)\n\t\t{\n\t\t fgoto propertybody;\n\t\t}\n\t\telse if(class_part_ == Enumeration)\n\t\t{\n\t\t fgoto enumerationbody;\n\t\t}\n\t\telse if(class_part_ == InClassComment)\n\t\t{\n\t\t class_part_ = Method;\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n\t\t}\n\t }\n\t else\n\t {\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tprint_function_synopsis();\n\t\tfgoto funcbody;\n\t }\n\t}\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n\tend_function();\n\tfor( list::iterator it = namespaces_.begin();\n\t\t it != namespaces_.end(); ++it)\n\t{\n\t fout_ << \"};\\n\";\n\t}\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n\tassert(p >= tmp_p-1);\n\tif (*p == '\\r')\n\t fout_.write(tmp_p, p-tmp_p);\n\telse\n\t fout_.write(tmp_p, p-tmp_p+1);\n\tfcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action st_tok2 { tmp_p2 = p; }\n\n action echo_tok {\n\tassert (p >= tmp_p);\n\tfout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n\tassert ( p >= tmp_p );\n\ttmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n\t(\n\t# RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n\t# comment\n\t '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n\t\t\tfout_ << \"\/**\"; tmp_p = p+1;\n\t\t }\n\t . (default - [\\r\\n])*\n\t . ( EOL . [ \\t]*\n\t . '%' @{\n\t\t\t\tassert(p >= tmp_p -1);\n\t\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t\t\tfout_ << \" * \";\n\t\t\t\ttmp_p = p+1;\n\t\t\t }\n\t . (default - [\\r\\n])* )* . EOL\n\t |\n\t# RAGEL comment: else: a regular comment\n\t ( (default - '|')\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\t if (string(p, 8) != string(\"@@remove\"))\n\t\t fout_ << \"\/* \";\n\t\t tmp_p = p;\n\t\t } )\n\t . (default - [\\r\\n])* . EOL\n\t);\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin pattern: if found, automatically set the character pointer to the current position (plus one)\n doc_begin = [\\t ]* . '%' @{\n\tif (!docline) {\n\t\ttmp_p = p + 1;\n\t}\n };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n\t( (default - [\\r\\n])* . EOL )\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\tfout_ << \"\/* \";\n\t\tassert( p >= tmp_p );\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n\t };\n garble_comment_line_wo_eol =\n\t(default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n\t( ([ \\t]+ \n\t @{\n\t\t {\n\t\t\tint i=0;\n\t\t\tif (*(p+1) != ' ' && *(p+1) != '\\t')\n\t\t\t{\n\t\t\t while (*(p-i) == ' ' || *(p-i) == '\\t')\n\t\t\t\ti++;\n\t\t\t if (*(p-i) == '\\n')\n\t\t\t\tfout_ << std::string(i, ' ');\n\t\t\t}\n\t\t }\n\t\t})\n\t | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n\t | ('...'.[ \\t]*.EOL)\n\t);\n\n # white space or line continuation\n WS =\n\t( [ \\t]+\n\t | ('...'.[\\t]*.EOL)\n\t);\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n\t(\n\t (WSOC | ',' | EOL\n\t | ( '=' . default_arg ) )+\n\t |\n\t # matlab identifier (parameter)\n\t (IDENT | '~' )\n\t >st_tok\n\t %{\n\t\t assert(p >= tmp_p);\n\t\t string s(tmp_p, p - tmp_p);\n\t\t bool addBlock = true;\n\t\t \/\/ do not print this pointer\n\t\t if( is_class_ && ( !methodparams_.statical\n\t\t\t\t\t\t\t&& (\n\t\t\t\t\t\t\t\t( class_part_ == Method\n\t\t\t\t\t\t\t\t && cfuncname_ != classname_\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t|| class_part_ == AtMethod\n\t\t\t\t\t\t\t\t|| class_part_ == MethodDeclaration\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t\t\t\t && ( ! (\n\t\t\t\t\t\t\t methodparams_.abstr\n\t\t\t\t\t\t\t && !runMode_.remove_first_arg_in_abstract_methods\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t )\n\t\t {\n\t\t\tif(paramlist_.empty())\n\t\t\t{\n\t\t\t addBlock = false;\n\t\t\t paramlist_.push_back(string(\"this\"));\n\t\t\t}\n\t\t\telse if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n\t\t\t paramlist_.clear();\n\t\t }\n\n\t\t if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t postprocess_unused_params(s, param_list_);\n\t\t \/\/ add an empty docu block for parameter \\a s\n\t\t if(param_list_.find(s) == param_list_.end())\n\t\t {\n\t\t\t param_list_[s] = DocuBlock();\n\t\t }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t paramlist_.push_back(s);\n\t\t }\n\t }\n\t)**;\n\n \n matrix_or_cell := (\n\t '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n\t |\n\t '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n\t );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n\t( (WSOC | EOL )+\n\t | ','\n\t # matlab identifier (return value)\n\t | ( (IDENT | '~') > st_tok\n\t\t %{\n\t\t\tassert(p >= tmp_p);\n\t\t\tstring s(tmp_p, p - tmp_p);\n\t\t\tpostprocess_unused_params(s, return_list_);\n\t\t\treturnlist_.push_back(s);\n\t\t\t\/\/ add an empty docu block for return value \\a s\n\t\t\tif(return_list_.find(s) == return_list_.end())\n\t\t\t{\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t}\n\t\t }\n\t\t)\n\t)**;\n\n # return parameter or return parameter list\n lparams =\n\t(\n\t (\n\t\t(\n\t\t # matlab identifier\n\t\t ( IDENT | '~' )\n\t\t >st_tok\n\t\t %{\n\t\t\t assert(p >= tmp_p);\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t postprocess_unused_params(s, return_list_);\n\t\t\t returnlist_.push_back(s);\n\t\t\t \/\/ add an empty docu block for single return value \\a s\n\n\t\t\t if(return_list_.find(s) == return_list_.end())\n\t\t\t {\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n\t\t }\n\t\t)\n\t\t| ( '['\n\t\t . lparamlist\n\t\t . ']'\n\t\t )\n\t )\n\t . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n\t :> '=' . WSOC*\n\t);\n\t# }}}2\n\n # a line in the function body {{{2\n funcline := |*\n\t# empty line\n\t([ \\t]+)\n\t => { fout_.write(ts, te-ts); };\n\n\t# line continuation\n\t('...' . [ \\t]* . EOL)\n\t => { fout_.write(ts, te-ts); };\n\n\t# two single quote in a row need to be changed to nothing\n\t('\\'\\'');\n\n\t# a string should not be parsed for comment blocks, so we handle it separately.\n\t('\\'' . [^'\\n]+ . '\\'')\n\t => {\n\t\t \/\/ change double quotes to quotes and vice versa...\n\t\t fout_ << \"\\\" \";\n\t\t string s(ts+1, te-ts-2);\n\t\t std::replace(s.begin(), s.end(), '\\\"', '\\'');\n\t\t fout_ << s;\n\t\t fout_ << \" \\\"\";\n\t\t };\n\n\t# ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n\t(comment_block)\n\t => {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\t fout_.write(tmp_p, p - tmp_p-1);\n\t\t else\n\t\t\t fout_.write(tmp_p, p - tmp_p);\n\t\t extra_hold_in_cblock = true;\n\t\t fcall in_comment_block;\n\t\t };\n\n\t (IDENT %{tmp_string.assign(ts,p-ts);})\n\t . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n\t {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n\t varargin_parser_candidate_ = tmp_string;\n\t };\n\n\t ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\t \n\t ((IDENT %{tmp_string.assign(ts, p - ts);})\n\t\t . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n\t\t . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\n\n\t('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL ) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t# automatically add return value fields to retval_list_\n\t(\n\t # matlab identifier (which can be a return value and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n\t # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n\t . [ \\t]* . '=' . (^'=')\n\t)\n\t=> {\n\t fhold;\n\t \/\/ store fieldname\n\t assert(tmp_p2 >= tmp_p);\n\t string s(tmp_p, tmp_p2 - tmp_p);\n\t fout_ << tmp_string << \".\" << s << \"=\";\n\t \/\/ typedef of iterators\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a return value\n\t iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n\t if(it != returnlist_.end())\n\t {\n\t\t\/\/ if it is a return value...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ retval list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ if it is missing, add an empty docu block\n\t\tif(missing)\n\t\t{\n\t\t retval_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# automatically add parameter fields to required_list_\n\t(\n\t # matlab identifier (which can be a parameter and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT\n\t\t >(st_tok)\n\t )\n\t)\n\t=> {\n\t \/\/ store fieldname\n\t assert(p >= tmp_p);\n\t string s(tmp_p, p - tmp_p+1);\n\t fout_ << tmp_string << \".\" << s;\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a parameter\n\t iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n\t if(it != paramlist_.end())\n\t {\n\t\t\/\/ if it is a parameter ...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ return, optional and the required list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t \/\/ found match in retval list\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator moit = optional_list_.find(tmp_string);\n\t\tif(moit != optional_list_.end())\n\t\t{\n\t\t \/\/ found match in optional list\n\t\t list_iterator lit = (*moit).second.find(s);\n\t\t if(lit != (*moit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator roit = required_list_.find(tmp_string);\n\t\tif(roit != required_list_.end())\n\t\t{\n\t\t \/\/ found match in required list\n\t\t list_iterator lit = (*roit).second.find(s);\n\t\t if(lit != (*roit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ in case it IS missing, add an empty field to the required block.\n\t\tif(missing)\n\t\t{\n\t\t required_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# add a @deprecated command to function declaration if disp_deprecated is\n\t# used in function body\n\t('disp_deprecated' . [ \\t]*\n\t . (\n\t\t ';'\n\t\t\t@{tmp_string.assign(\"\");}\n\t\t |\n\t\t '(' . [\\t ]* . \"'\"\n\t\t . ([^\\n']*\n\t\t\t >(st_tok)\n\t\t\t %(string_tok)\n\t\t\t)\n\t\t . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n\t\t)\n\t . [\\t ]* . EOL\n\t)\n\t => {\n\t\tstring s;\n\t\tif(tmp_string.empty())\n\t\t{\n\t\t s.assign(\"@deprecated function deprecated\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n\t\t}\n\t\tdocuextra_.push_back(s);\n\t\tfhold;\n\t };\n\n\t# simple matlab identifier\n\t(IDENT)\n\t => { fout_.write(ts, te-ts); };\n\n\t# translate curly brackets in edgy brackets, because otherwise the doxygen\n\t# parser breaks.\n\t('{')\n\t => { fout_ << '['; };\n\n\t('}')\n\t => { fout_ << ']'; };\n\t\n\t('\\'')\n\t => { fout_ << \"^t\"; };\n\n\t# simply output all other characters\n\t(default - [\\r\\n{}\\'])\n\t => { fout_ << fc; };\n\n\t# after EOL try to check for new function\n\tEOL\n\t => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n\t # things that got replaced in function body {{{4\n\t ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n\t\t=> {\n\t\t new_syntax_ = true;\n\t\t fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n\t\t};\n\n\t ([ \\t]* . '%@@remove' . ((default - '%') | ('%' . (default - '@')) | ('%' . '@' . (default -'@')))* . '%@@endremove');\n\n\t # a comment block\n\t ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n\t\t=> {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\tfout_.write(tmp_p, p - tmp_p - 1);\n\t\t else\n\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t fcall in_comment_block;\n\t\t};\n\n\t # empty line\n\t ([ \\t]* . EOL)\n\t\t=> { fout_ << '\\n'; };\n\n\t #}}}4\n\n\t # line not beginning with words 'function' or 'end'\n\t ([ \\t]*\n\t . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n\t )\n\t\t=> {\n\t\t p = ts-1;\n\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n\t\t fgoto funcline;\n\t\t};\n\n\t # things that could end the function body {{{4\n\t # line only containing word 'end'\n\t # the keyword needs to be in the same indentation level as beginning function\n\t ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n\t\t => {\n\t\t\t if(is_class_ && class_part_ == Method)\n\t\t\t {\n\t\t\t\ttmp_string.assign(ts,p-ts+1);\n\n\t\t\t\tif(tmp_string.find(\"e\") == funcindent_)\n\t\t\t\t{\n\t\t\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n\t\t\t\t fgoto methods;\n\t\t\t\t}\n\t\t\t }\n\t\t\t \/\/ else\n\t\t\t p=ts-1;\n\t\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n\t\t\t fgoto funcline;\n\t\t };\n\n\t # line beginning with word 'function'\n\t ([ \\t]*. 'function ')\n\t {\n\t\ttmp_string.assign(ts,p-ts+1);\n\t\tp = ts-1;\n\n\t\tif (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n\t\t{\n\t\t \/\/ end the previous function if existent\n\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n\t\t fgoto main;\n\t\t}\n\t\telse\n\t\t{\n\t\t fgoto funcline;\n\t\t}\n\t };\n\n\t (EOF) $eof(end_of_file);\n\n\t # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n\t. \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n\t. ( default - [\\r\\n] )* . EOL\n )\n\t=> {\n\t assert(tmp_p2 >= tmp_p3);\n\t tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n\t \/\/ std::fout_ << tmp_string << '\\n';\n\t assert(p >= tmp_p);\n\t (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n\t};\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n\t# at least one word (non white-space characters and no double-colon)\n\t. ( default - [ \\r\\t:\\n] )+ .\n\t# followed by something that is a white-space or a new-line, i.e *no*\n\t# double-colon\n\t(\n\t EOL\n\t |\n\t [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - [\\r\\n])* . EOL)\n\t # [ \\t] . (default - '\\n')* . EOL\n\t)\n )\n\t=> {\n\t assert(p+1 >= tmp_p);\n\t string s(tmp_p, p - tmp_p + 1);\n\t (*clist_)[tmp_string].push_back(s);\n\t \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n\t};\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n\t=> { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n\t=> {\n\t p =ts-1;\n\t \/\/ fout_ << \"*\/\\n\";\n\t fret;\n\t};\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n\t# special lists {{{4\n\n\t# begin required_list\n\t( doc_begin . [ \\t]*\n\t . \/required fields of \/i\n\t . (IDENT >(st_tok) %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL\n\t)\n\t => {\n\t\t\/\/fout_ << tmp_string << '\\n';\n\t\tclist_ = &(required_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/optional fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(optional_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/generated fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(retval_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin parameter list\n\t( doc_begin . [ \\t]*\n\t . \/parameters\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = ¶m_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin return list\n\t( doc_begin . [ \\t]*\n\t . \/return values\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &return_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\t#}}}4\n\n\t# default substitutions {{{4\n\n\t# empty line\n\t( doc_begin . [ \\t]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n \";*\/\n\t\tdocubody_.push_back(\"\\n\");\n\t\tdocline = false;\n\t };\n\n\t# paragraph line with second % in text (matlab comment in comment)\n\t( [ \\t]* . '%' . [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docubody_.push_back(\"%\");\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line\n\t( [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line with \"see also\" substituted by \"@sa\"\n\t( \/see also\/i . ':'? )\n\t => {\n\t\tstring s;\n\t\tassert(ts > tmp_p);\n\t\ts.assign(tmp_p+1, ts - tmp_p-1);\n\t\tdocubody_.push_back(s+\"@sa\");\n\t\ttmp_p = p;\n\t };\n\n\t# verbatim or code switches\n\t( [\\\\@] .\n\t\t(\/verbatim\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@verbatim\");\n\t\t}\n\t\t|\n\t\t\/code\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@code\");\n\t\t}\n\t\t));\n\t( [\\\\@] .\n\t\t(\/endverbatim\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endverbatim\");\n\t\t}\n\t\t|\n\t\t\/endcode\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endcode\");\n\t\t}\n\t\t) );\n\n\t# lines that could end doxyblock {{{6\n\t# words\n\t# RAGEL comment: ( default - [ \\t:%'`\\n] )+\n\t( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n\t# non-words\/non-whitespace\n\t# RAGEL comment: ([:'`]) => {\n\t(':') @(end_doxy_block) ;\n\n\t# whitespace only\n\t( [ \\t] );\n\n\t# titled paragraph\n\t( ':' . EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t assert(ts > tmp_p);\n\t\t docubody_.push_back((!is_voc ? \"@par \":\"\") + string(tmp_p+1, ts - tmp_p-1)+(is_voc ? \":\":\"\")+\"\\n\");\n\t\t docline = false;\n\t\t }\n\t };\n\t# }}}6\n\t# }}}4\n\n\t# end of line {{{4\n\t( EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t\tint offset = ( latex_begin ? 0 : 1 );\n\t\t\tassert(p >= tmp_p + offset);\n\t\t\tdocubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n\t\t\tdocline = false;\n\t\t }\n\t\t};\n\t # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n\tgarbage = ( (default - [\\r\\n] )* -- '...' );\n\n\t( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n\t( doc_begin . (garbage . '...')* . garbage . EOL )\n\t => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n\t# read in one comment line\n\t( doc_begin . [\\t ]*\n\t . (default - [\\r\\n\\t ]) . (default - [\\r\\n])* . EOL\n\t)\n\t => {\n\t\t\/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n\t\tassert(p >= tmp_p);\n\t\tdocuheader_.push_back(string(tmp_p, p - tmp_p+1));\n\t };\n\n\t# empty line\n\t( doc_begin . [\\t ]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n\t\tfgoto doxy_get_body;\n\t };\n\n\t# end of comment block;\n\t( [\\t ]* . [^%] )\n\t => {\n\t\tp=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n\t\t\/\/fout_ << \"*\/\\n\";\n\t\tif(is_class_)\n\t\t{\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n\t\t if(class_part_ == Header)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n\t\t\tend_of_class_doc();\n\t\t\tfgoto classbody;\n\t\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n\t\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t\t return 1;\n\t\t\tprint_function_synopsis();\n\t\t\tfgoto funcbody;\n\t\t }\n\t\t else if(class_part_ == MethodDeclaration)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n\t\t\tfgoto funcdef;\n\t\t }\n\t\t else if(class_part_ == Property || class_part_ == Event)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n\t\t\tfgoto propertybody;\n\t\t }\n\t\t else if(class_part_ == InClassComment)\n\t\t {\n\t\t\tclass_part_ = Method;\n\t\t\tfgoto methods;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n\t'%' . [ \\t]* .\n\t (\n\t\t('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n\t )\n\t $!{\n#ifdef DEBUG\n\t\tdebug_output(\"doxy_get_brief\",p);\n#endif\n\t\tp = tmp_p - 2;\n\t\tfgoto doxy_get_brief;\n\t }\n ); #}}}2\n\n # access specifier expressions\n spec_public = ( 'public'i | \"'public'\"i );\n spec_protected = ( 'protected'i | \"'protected'\"i );\n spec_private = ( 'private'i | \"'private'\"i );\n \n spec_class_single = \n\t (\n\t ('?' . (IDENT_W_DOT**) >st_tok )\n\t %{\n\t\t\ttmp_string.assign(tmp_p, p - tmp_p);\n\t\t\t\/\/cerr << \"Detected \" << access_.state << \" modifier by class \" << tmp_string << \"\\n\";\n\t\t\taccess_.classMemberAccess.push_back(make_pair(access_.state, tmp_string));\n\t\t}\n\t ) . WS*;\n \n spec_class_multi = '{' . WS* . spec_class_single . ( [,; ] . WS* . spec_class_single )* . '}';\n \n spec_classes = ( spec_class_single | spec_class_multi );\n\t\n # helper for setting the access specifier {{{2\n paramaccess =\n\t( ('SetAccess' @{ access_.state = SetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public \n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'GetAccess' @{ access_.state = GetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'Access' @{ access_.state = Access; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = Protected; access_.get = Protected; access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = Private; access_.get = Private; access_.set = Private;\n\t\t\t } )\n\t\t )\n\t )\n\t); #}}}2\n\n eventparam =\n\t( ('ListenAccess' @{ access_.state = ListenAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'NotifyAccess' @{ access_.state = NotifyAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t );\n\n # method and property params {{{2\n methodparam =\n (\n\t( paramaccess )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.abstr = true;\n\t\t } )\n\t| ( ( 'Static' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.statical = true;\n\t\t } )\n\t| ( ('Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.hidden = true;\n\t\t } )\n\t| ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.sealed = true;\n\t\t } )\n\t| ( ( 'Test' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.test = true;\n\t\t } )\n\t| ( ( 'TestMethodSetup' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodSetup = true;\n\t\t } )\n\t| ( ( 'TestMethodTeardown' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodTeardown = true;\n\t\t } )\n );\n\n propertyparam =\n (\n\t( paramaccess )\n\t| ( ( 'Constant' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.constant = true;\n\t\t } )\n\t| ( ( 'Transient' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.transient = true;\n\t\t } )\n\t| ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.dependent = true;\n\t\t } )\n\t| ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t| ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.setObservable = true;\n\t\t } )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abstr = true;\n\t\t } )\n\t| ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abortSet = true;\n\t\t } )\n );\n\n methodparams =\n (\n\t'(' . WSOC*\n\t. methodparam\n\t. ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n eventparams =\n (\n\t'(' . WSOC*\n\t. eventparam\n\t. ( WSOC* . ',' . WSOC* . eventparam )* . WSOC* . ')'\n ); #}}}2\n\n propertyparams =\n (\n\t'(' . WSOC*\n\t. propertyparam\n\t. ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n\t(empty_line) => {\n\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t {\n\t\tend_method();\n\t\tfout_ << \"\\n\";\n\t }\n\t};\n\n\t# default: method definition\n\t([ \\t]* . 'function' )\n\t => {\n\t\ttmp_string.assign(ts, te - ts+1);\n\t\tfuncindent_ = tmp_string.find_first_not_of(\" \\t\");\n\t\tfout_ << string(ts, ts+funcindent_);\n\t\t#if DEBUG\n\t\t\t{\n\t\t\t ostringstream oss;\n\t\t\t oss << \"in methods: funcindent: \" << funcindent_;\n\t\t\t debug_output(oss.str(), p);\n\t\t\t}\n\t\t#endif\n\t\tp=ts+funcindent_-1;\n\t\tfgoto funct;\n\t };\n\n\t# end of methods block\n\t([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n\t => {\n\t\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t\t {\n\t\t\t end_method();\n\t\t\t #if DEBUG\n\t\t\t debug_output(\"in methods: found end keyword, goto classbody\",p);\n\t\t\t #endif\n\t\t }\n\t\t fgoto classbody;\n\t\t };\n\n\t# comment between two methods\n\t([ \\t]* . '%' ) => {\n\t #if DEBUG\n\t\tdebug_output(\"in methods: garble comment line\",p);\n\t #endif\n\n\t p = ts-1;\n\t class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n\t fgoto expect_doxyblock;\n\t};\n\n\t# if we reach this: method declaration without definition is found\n\t([ \\t]* . [^% \\t\\n]) =>\n\t{\n\t #if DEBUG\n\t\tdebug_output(\"in methods: found method declaration, going to funcdef\",p);\n\t #endif\n\t class_part_ = MethodDeclaration;\n\t p = ts-1;\n\t fgoto funcdef;\n\t};\n\n\t *|;\n\n\n methodsheader := (\n\t[ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n\t\t @{\n\t\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t\tfgoto methods;\n\t\t }\n\t\t );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_property_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\")\n\t\t\t\tfgoto classbody;\n\t\t\t if (propertyparams_.dependent)\n\t\t\t\tspecifier_[s].dependent = true;\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t )\n\t\t. WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n\t\t\t|\n\t\t\t( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n\t\t\t@{\n\t\t\t defaultprop_ = string(tmp_p2, p - tmp_p2);\n\t\t\t string::size_type last_elem = defaultprop_.length() -1;\n\t\t\t if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n\t\t\t {\n\t\t\t\tdefaultprop_[0] = '\\\"';\n\t\t\t\tdefaultprop_[last_elem] = '\\\"';\n\t\t\t }\n\t\t\t string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n\t\t\t string::size_type last_paren;\n\t\t\t if (first_paren == string::npos)\n\t\t\t {\n\t\t\t\tfirst_paren = 1;\n\t\t\t\tlast_paren = last_elem;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tlast_paren = defaultprop_.find_last_of(\")]}\");\n\t\t\t\tif (last_paren == string::npos)\n\t\t\t\t last_paren=last_elem-1;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n\t\t\t\t {\n\t\t\t\t\tfirst_paren++;\n\t\t\t\t\tlast_paren--;\n\t\t\t\t }\n\t\t\t\t defaultprop_.insert(first_paren, 1,'\"');\n\t\t\t\t defaultprop_.insert(last_paren+2, 1,'\"');\n\t\t\t\t first_paren++;\n\t\t\t\t last_paren++;\n\t\t\t\t}\n\t\t\t }\n\t\t\t for (unsigned int i = first_paren; i < last_paren; ++i)\n\t\t\t {\n\t\t\t\tif(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n\t\t\t\t{\n\t\t\t\t defaultprop_[i] = ' ';\n\t\t\t\t defaultprop_[i+1] = ' ';\n\t\t\t\t defaultprop_[i+2] = ' ';\n\t\t\t\t}\n\/* else if(defaultprop_[i] == '[')\n\t\t\t\t defaultprop_[i] = '{';\n\t\t\t\telse if(defaultprop_[i] == ']')\n\t\t\t\t defaultprop_[i] = '}'; *\/\n\t\t\t\telse if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n\t\t\t\t defaultprop_[i] = ',';\n\t\t\t\telse if(defaultprop_[i] == '\\\"')\n\t\t\t\t defaultprop_[i] = '\\'';\n\t\t\t\telse if(defaultprop_[i] == '@')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t\telse if(defaultprop_[i] == '\\n')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t }\n\t\t\t }\n\t\t )\n\t );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n properties := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. propertybody* )\n\t );\n\n #property body {{{4\n eventbody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n events := ((\n\tWSOC* . eventparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. eventbody* )\n\t );\n\n enum = ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_enum_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\") {\n\t\t\t\tfout_ << \"\\n} \" << classname_ << \"Instances;\\n\";\n\t\t\t\tfgoto classbody;\n\t\t\t }\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t . WS* . ( '%' @{ fhold; } | ';' | ',' | EOL )\n\t\t );\n\n enumerationbody = (\n\t(enum)\n\t|\n\t( (empty_line) @{ end_of_enum_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n enumeration := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\tfout_ << \"typedef enum {\\n\";\n\t\t}\n\t. enumerationbody* )\n\t );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n\t# a comment block\n\t(comment_block)\n\t => {\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p - 1);\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p);\n\t\tfcall in_comment_block;\n\t };\n\n\t(WSOC); # => { fout_.write(ts, te-ts); };\n\n\t(EOL) => { fout_ << \"\\n\"; };\n\n\t('end' . [ \\t]* ';'?) => {\n\t std::map::iterator specIt;\n\t for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n\t {\n\t\tfout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n\t\tif ( (*specIt).second.dependent)\n\t\t{\n\t\t if( (*specIt).second.getter && ! (*specIt).second.setter )\n\t\t {\n\t\t\tfout_ << \"@note [readonly]\\n *\";\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t fout_ << \"@note This property has custom functionality when its value is \";\n\t\t if ((*specIt).second.getter)\n\t\t {\n\t\t\tfout_ << \"retrieved\";\n\t\t\tif ((*specIt).second.setter)\n\t\t\t fout_ << \" or changed\";\n\t\t }\n\t\t else if ((*specIt).second.setter)\n\t\t\tfout_ << \"changed\";\n\t\t fout_ << \".\";\n\t\t}\n\t\tfout_ << \"\\n *\/\\n\";\n\t }\n\t fout_ << \"\\n};\\n\";\n\t for( list::iterator it = namespaces_.begin();\n\t\t\tit != namespaces_.end(); ++it)\n\t {\n\t\tfout_ << \"}\\n\";\n\t }\n\t};\n\n\t([ \\t]* . 'properties')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Property;\n\t\tfgoto properties;\n\t };\n\t([ \\t]* . 'methods')\n\t => {\n\t\tmethodparams_ = MethodParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Method;\n\t\tfgoto methodsheader;\n\t };\n\t([ \\t]* . 'events')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\tpropertyparams_.event = true;\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Event;\n\t\tfgoto events;\n\t };\n\t([ \\t]* . 'enumeration')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Enumeration;\n\t\tfgoto enumeration;\n\t };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n\tdoc_begin\n\t @{\n\t\t\/\/fout_ << \"\/*\";\n\t\tp--;\n\t\tfgoto doxyheader;\n\t }\n )\n $!{\n\tfhold;\n\t{\n\t int i = 0;\n\t for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n\t\t;\n\t std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n\tdebug_output(\"stopping expect_doxyblock\", p);\n#endif\n\tif(is_class_)\n\t{\n\t if(class_part_ == Header)\n\t {\n\t\tend_of_class_doc();\n\t\tfgoto classbody;\n\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t {\n\t\tstring endstringtest;\n\t\tendstringtest.assign(p, 100);\n\t\tstring::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tif (endstringtest.substr(first_char, 3) == \"end\")\n\t\t{\n\t\t p += first_char+4;\n\t\t print_function_synopsis();\n\t\t end_function();\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t print_function_synopsis();\n\t\t fout_ << whitespaces;\n\t\t fgoto funcbody;\n\t\t}\n\t }\n\t else if(class_part_ == Property || class_part_ == Event)\n\t {\n\t\tfgoto propertybody;\n\t }\n\t else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n\t {\n\t\tclass_part_ = Method;\n\t\tfgoto methods;\n\t }\n\t else{\n\t\tcerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n\t }\n\t}\n\telse\n\t{\n\t if(runMode_.mode == RunMode::ParseParams)\n\t\treturn 1;\n\t print_function_synopsis();\n\t fout_ << whitespaces;\n\t fgoto funcbody;\n\t}\n\t}\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n\t (WSOC)* .\n\t # return values (if found opt = true)\n\t (lparams)? .\n\t # matlab identifier (function name stored in cfuncname_)\n\t ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n\t\tIDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tcfuncname_.assign(tmp_p, p - tmp_p);\n\t\t\t#ifdef DEBUG\n\t\t\t cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n\t\t\t#endif\n\t\t\t\/\/ in ParseMethodParams mode, we only check for the method\n\t\t\t\/\/ parameters of a specific method.\n\t\t\tif(is_class_ && class_part_ == MethodDeclaration\n\t\t\t && runMode_.mode == RunMode::ParseMethodParams)\n\t\t\t{\n\t\t\t if(runMode_.methodname == cfuncname_)\n\t\t\t {\n\t\t\t\treturn 0;\n\t\t\t }\n\t\t\t}\n\t\t\tif(runMode_.mode == RunMode::Normal\n\t\t\t && is_class_ && class_part_ == AtMethod)\n\t\t\t{\n\t\t\t update_method_params(cfuncname_);\n\t\t\t}\n\t\t\tis_script_ = false;\n\t\t }\n\t )\n\t . WSOC*\n\t . (\n\t\t '('\n\t\t # parameter list\n\t\t . ( paramlist\n\t\t\t %{\n\t\t\t\t if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n\t\t\t\t { paramlist_.clear(); }\n\t\t\t }\n\t\t\t )\n\t\t . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )*\n\t\t . EOL\n\t\t @{\n\t\t\t if(comment_found)\n\t\t\t {\n\t\t\t\ttmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\ttmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\ttmp_string = \"\";\n\t\t\t }\n\t\t\t comment_found = false;\n\t\t\t if(is_class_ && class_part_ == MethodDeclaration )\n\t\t\t {\n\t\t\t class_part_ = Method;\n\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n\t\t\t #endif\n\t\t\t fgoto methods;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t \/\/ fout_ << tmp_string << \"{\\n\";\n\t\t\t \/\/ check for documentation block\n\t\t\t fgoto expect_doxyblock;\n\t\t\t }\n\t\t }\n\t\t# no parameter list && first function => ( script || method )\n\t\t| (( [ \\t]\n\t\t\t |\n\t\t\t ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n\t\t\t@{\n\t\t\t\t if(comment_found)\n\t\t\t\t {\n\t\t\t\t tmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\t tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t tmp_string = \"\";\n\t\t\t\t }\n\t\t\t\t comment_found = false;\n\t\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n\t\t\t\t #endif\n\t\t\t\t if(is_class_ && class_part_ == MethodDeclaration)\n\t\t\t\t {\n\t\t\t\t\tclass_part_ = Method;\n\t\t\t\t\tfgoto methods;\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t fgoto expect_doxyblock;\n\t\t\t\t }\n\t\t\t }\n\t\t)\n\t );\n\n funct :=\n (\n\t(\n\t comment_block @in_c_block\n\t | [ \\t]*. EOL\n\t)*\n\t. ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n\t@{\n\t string :: size_type found = filename_.rfind(\"\/\");\n\t if(found == string :: npos)\n\t\t found = -1;\n\t string funcname = filename_.substr(found+1, filename_.size()-3-found);\n\t cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n\t if(!is_first_function_)\n\t\t fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\t fout_ << funcname << \"() {\\n\";*\/\n\t is_script_ = true;\n\t fhold;\n\t fgoto expect_doxyblock;\n\t }; #}}}2\n\n # class definitions {{{2\n classparams =\n\t '(' . [^)]* . ')';\n\n superclass =\n\t( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n\t\t\t\t\t @{ if(*p == '.')\n\t\t\t\t\t\t fout_ << \"::\";\n\t\t\t\t\t\t else fout_ << *p; } );\n\n superclasses = (\n\t '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n\t\t . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n\t 'classdef' . WSOC* . ('(' . WSOC*\n\t\t. (( 'Sealed'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n\t\t }\n\t\t )\n\n\t\t |( 'Hidden'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Hidden' and is invisible.\"));\n\t\t }\n\t\t )\n\t\t |( 'Abstract'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Abstract' and needs to be inherited in order to be instantiable.\"));\n\t\t }\n\t\t )) . [^)]* . ')')? . WSOC* .\n\t # matlab identifier (class name stored in classname_)\n\t ( IDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tclassname_.assign(tmp_p, p - tmp_p);\n\t\t\tis_class_ = true;\n\t\t\tfout_ << \"class \" << classname_;\n\t\t }\n\t )\n\t . WSOC*\n\t . classparams?\n\t . WSOC*\n\t . superclasses?\n\t . [ \\t;]*\n\t . ( '%'. garble_comment_line_wo_eol )?\n\t EOL\n\t @{\n\t\tfout_ << \" {\\n\";\n\t\tfgoto expect_doxyblock;\n\t } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n\t# either we find a function or classdef definition with a possibly\n\t# preceding comment block or we have a script\n\t( any\n\t @{\n\t\t fhold;\n\t\t tmp_p = p;\n\t\t}\n\t .\n\t(\n\t [ \\t]*. '%' . (any - '\\n')* . EOL\n\t | [ \\t]*. EOL\n\t)*\n\t. [\\t]*\n\t. ( 'function' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t char *tp;\n\t\t\t\t\t for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n\t\t\t\t\t ;\n\t\t\t\t\t funcindent_ = (int)(p - tp);\n#if DEBUG\n\t\t\t\t\t {\n\t\t\t\t\t ostringstream oss;\n\t\t\t\t\t oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n\t\t\t\t\t debug_output(oss.str(), p);\n\t\t\t\t\t }\n#endif\n\t\t\t\t\t if(is_class_ && class_part_ == Header)\n\t\t\t\t\t class_part_ = AtMethod;\n\t\t\t\t\t fgoto funct;\n\t\t\t\t\t}\n\t | 'classdef' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t fgoto classdef;\n\t\t\t\t\t}\n\t ) )\n $!{\n#ifdef DEBUG\n\tdebug_output(\"goto script\",p);\n#endif\n\tp=tmp_p;\n\tfgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n\tchar *p = buf + have;\n\tchar *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n\tstring tmp_string, tmp_string2, tmp_string3;\n\tbool docline = false;\n\tbool latex_begin = true;\n\tbool comment_found = false;\n\tint space = BUFSIZE - have;\n\n\tif ( space == 0 )\n\t{\n\t \/* We filled up the buffer trying to scan a token. *\/\n\t cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n\t exit(-1);\n\t}\n\n\tfin_.read( p, space );\n\tint len = fin_.gcount();\n\tchar *pe = p + len;\n\tchar *rpe = pe;\n\tchar *eof = 0;\n\n\t\/* If we see eof then append the EOF char. *\/\n\tif ( fin_.eof() )\n\t{\n\t char eof_c = *pe;\n\t *pe = '\\n';\n\t pe++;\n\t *pe = eof_c;\n\t eof = pe;\n\t rpe = pe;\n\n\t done = true;\n\t}\n\telse\n\t{\n\t \/* Find the last newline by searching backwards. This is where\n\t * we will stop processing on this iteration. *\/\n\t while ( pe >= p )\n\t {\n\t\tif( *pe != '\\n')\n\t\t pe--;\n\t\telse\n\t\t{\n\t\t if(pe >= p+3\n\t\t\t && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n\t\t\tpe-=3;\n\t\t else\n\t\t\tbreak;\n\t\t}\n\t }\n\t}\n\n\t%% write exec;\n\n\t\/* Check if we failed. *\/\n\tif ( cs == MFileScanner_error )\n\t{\n\t \/* Machine failed before finding a token. *\/\n\t cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n\t debug_output(\"Grrrr!!!!\", p);\n\t exit(-1);\n\t}\n\n\t\/* Now set up the prefix. *\/\n\tif ( ts == 0 )\n\t{\n\t have = rpe - pe;\n\t \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n\t memmove( buf, pe, have );\n\t}\n\telse\n\t{\n\t have = rpe - ts;\n\t \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n\t memmove( buf, ts, have );\n\t}\n\n\tif ( ts != 0 )\n\t{\n\t te -= (ts-buf);\n\t ts = buf;\n\t}\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","old_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n\t @{ fout_ << \"\\n\";\n\t\tfout_.write(tmp_p, p - tmp_p);\n\t\ttmp_p = p+1; fout_ << \" *\";\n\t }\n # and then some default characters\n . ( ( (default - [\\r\\n])* )\n\t %{ fout_.write(tmp_p, p - tmp_p); } )\n\t . EOL\n )*\n $!{\n\tfout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n\tfhold;\n\twhile (*p == ' ')\n\t fhold;\n\tif (extra_hold_in_cblock)\n\t{\n\t fhold;\n\t --line;\n\t extra_hold_in_cblock = false;\n\t}\n\tfret;\n };\n\n action end_doxy_block\n {\n\tif(!docline)\n\t{\n\t p = ts-1;\n\t \/* go backward until first non-whitespace is found *\/\n\t for(p=p-1; *p==' ' || *p == '\\t'; --p)\n\t\t;\n\n\t if(is_class_)\n\t {\n\t\tif(class_part_ == Header)\n\t\t{\n\t\t end_of_class_doc();\n\t\t fgoto classbody;\n\t\t} else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t\telse if(class_part_ == MethodDeclaration)\n\t\t{\n\t\t fgoto funcdef;\n\t\t}\n\t\telse if(class_part_ == Property || class_part_ == Event)\n\t\t{\n\t\t fgoto propertybody;\n\t\t}\n\t\telse if(class_part_ == Enumeration)\n\t\t{\n\t\t fgoto enumerationbody;\n\t\t}\n\t\telse if(class_part_ == InClassComment)\n\t\t{\n\t\t class_part_ = Method;\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n\t\t}\n\t }\n\t else\n\t {\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tprint_function_synopsis();\n\t\tfgoto funcbody;\n\t }\n\t}\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n\tend_function();\n\tfor( list::iterator it = namespaces_.begin();\n\t\t it != namespaces_.end(); ++it)\n\t{\n\t fout_ << \"};\\n\";\n\t}\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n\tassert(p >= tmp_p-1);\n\tif (*p == '\\r')\n\t fout_.write(tmp_p, p-tmp_p);\n\telse\n\t fout_.write(tmp_p, p-tmp_p+1);\n\tfcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action st_tok2 { tmp_p2 = p; }\n\n action echo_tok {\n\tassert (p >= tmp_p);\n\tfout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n\tassert ( p >= tmp_p );\n\ttmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n\t(\n\t# RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n\t# comment\n\t '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n\t\t\tfout_ << \"\/**\"; tmp_p = p+1;\n\t\t }\n\t . (default - [\\r\\n])*\n\t . ( EOL . [ \\t]*\n\t . '%' @{\n\t\t\t\tassert(p >= tmp_p -1);\n\t\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t\t\tfout_ << \" * \";\n\t\t\t\ttmp_p = p+1;\n\t\t\t }\n\t . (default - [\\r\\n])* )* . EOL\n\t |\n\t# RAGEL comment: else: a regular comment\n\t ( (default - '|')\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\t if (string(p, 8) != string(\"@@remove\"))\n\t\t fout_ << \"\/* \";\n\t\t tmp_p = p;\n\t\t } )\n\t . (default - [\\r\\n])* . EOL\n\t);\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin pattern: if found, automatically set the character pointer to the current position (plus one)\n doc_begin = [\\t ]* . '%' @{\n\tif (!docline) {\n\t\ttmp_p = p + 1;\n\t}\n };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n\t( (default - [\\r\\n])* . EOL )\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\tfout_ << \"\/* \";\n\t\tassert( p >= tmp_p );\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n\t };\n garble_comment_line_wo_eol =\n\t(default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n\t( ([ \\t]+ \n\t @{\n\t\t {\n\t\t\tint i=0;\n\t\t\tif (*(p+1) != ' ' && *(p+1) != '\\t')\n\t\t\t{\n\t\t\t while (*(p-i) == ' ' || *(p-i) == '\\t')\n\t\t\t\ti++;\n\t\t\t if (*(p-i) == '\\n')\n\t\t\t\tfout_ << std::string(i, ' ');\n\t\t\t}\n\t\t }\n\t\t})\n\t | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n\t | ('...'.[ \\t]*.EOL)\n\t);\n\n # white space or line continuation\n WS =\n\t( [ \\t]+\n\t | ('...'.[\\t]*.EOL)\n\t);\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n\t(\n\t (WSOC | ',' | EOL\n\t | ( '=' . default_arg ) )+\n\t |\n\t # matlab identifier (parameter)\n\t (IDENT | '~' )\n\t >st_tok\n\t %{\n\t\t assert(p >= tmp_p);\n\t\t string s(tmp_p, p - tmp_p);\n\t\t bool addBlock = true;\n\t\t \/\/ do not print this pointer\n\t\t if( is_class_ && ( !methodparams_.statical\n\t\t\t\t\t\t\t&& (\n\t\t\t\t\t\t\t\t( class_part_ == Method\n\t\t\t\t\t\t\t\t && cfuncname_ != classname_\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t|| class_part_ == AtMethod\n\t\t\t\t\t\t\t\t|| class_part_ == MethodDeclaration\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t\t\t\t && ( ! (\n\t\t\t\t\t\t\t methodparams_.abstr\n\t\t\t\t\t\t\t && !runMode_.remove_first_arg_in_abstract_methods\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t )\n\t\t {\n\t\t\tif(paramlist_.empty())\n\t\t\t{\n\t\t\t addBlock = false;\n\t\t\t paramlist_.push_back(string(\"this\"));\n\t\t\t}\n\t\t\telse if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n\t\t\t paramlist_.clear();\n\t\t }\n\n\t\t if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t postprocess_unused_params(s, param_list_);\n\t\t \/\/ add an empty docu block for parameter \\a s\n\t\t if(param_list_.find(s) == param_list_.end())\n\t\t {\n\t\t\t param_list_[s] = DocuBlock();\n\t\t }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t paramlist_.push_back(s);\n\t\t }\n\t }\n\t)**;\n\n \n matrix_or_cell := (\n\t '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n\t |\n\t '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n\t );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n\t( (WSOC | EOL )+\n\t | ','\n\t # matlab identifier (return value)\n\t | ( (IDENT | '~') > st_tok\n\t\t %{\n\t\t\tassert(p >= tmp_p);\n\t\t\tstring s(tmp_p, p - tmp_p);\n\t\t\tpostprocess_unused_params(s, return_list_);\n\t\t\treturnlist_.push_back(s);\n\t\t\t\/\/ add an empty docu block for return value \\a s\n\t\t\tif(return_list_.find(s) == return_list_.end())\n\t\t\t{\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t}\n\t\t }\n\t\t)\n\t)**;\n\n # return parameter or return parameter list\n lparams =\n\t(\n\t (\n\t\t(\n\t\t # matlab identifier\n\t\t ( IDENT | '~' )\n\t\t >st_tok\n\t\t %{\n\t\t\t assert(p >= tmp_p);\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t postprocess_unused_params(s, return_list_);\n\t\t\t returnlist_.push_back(s);\n\t\t\t \/\/ add an empty docu block for single return value \\a s\n\n\t\t\t if(return_list_.find(s) == return_list_.end())\n\t\t\t {\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n\t\t }\n\t\t)\n\t\t| ( '['\n\t\t . lparamlist\n\t\t . ']'\n\t\t )\n\t )\n\t . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n\t :> '=' . WSOC*\n\t);\n\t# }}}2\n\n # a line in the function body {{{2\n funcline := |*\n\t# empty line\n\t([ \\t]+)\n\t => { fout_.write(ts, te-ts); };\n\n\t# line continuation\n\t('...' . [ \\t]* . EOL)\n\t => { fout_.write(ts, te-ts); };\n\n\t# two single quote in a row need to be changed to nothing\n\t('\\'\\'');\n\n\t# a string should not be parsed for comment blocks, so we handle it separately.\n\t('\\'' . [^'\\n]+ . '\\'')\n\t => {\n\t\t \/\/ change double quotes to quotes and vice versa...\n\t\t fout_ << \"\\\" \";\n\t\t string s(ts+1, te-ts-2);\n\t\t std::replace(s.begin(), s.end(), '\\\"', '\\'');\n\t\t fout_ << s;\n\t\t fout_ << \" \\\"\";\n\t\t };\n\n\t# ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n\t(comment_block)\n\t => {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\t fout_.write(tmp_p, p - tmp_p-1);\n\t\t else\n\t\t\t fout_.write(tmp_p, p - tmp_p);\n\t\t extra_hold_in_cblock = true;\n\t\t fcall in_comment_block;\n\t\t };\n\n\t (IDENT %{tmp_string.assign(ts,p-ts);})\n\t . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n\t {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n\t varargin_parser_candidate_ = tmp_string;\n\t };\n\n\t ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\t \n\t ((IDENT %{tmp_string.assign(ts, p - ts);})\n\t\t . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n\t\t . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\n\n\t('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL ) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t# automatically add return value fields to retval_list_\n\t(\n\t # matlab identifier (which can be a return value and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n\t # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n\t . [ \\t]* . '=' . (^'=')\n\t)\n\t=> {\n\t fhold;\n\t \/\/ store fieldname\n\t assert(tmp_p2 >= tmp_p);\n\t string s(tmp_p, tmp_p2 - tmp_p);\n\t fout_ << tmp_string << \".\" << s << \"=\";\n\t \/\/ typedef of iterators\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a return value\n\t iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n\t if(it != returnlist_.end())\n\t {\n\t\t\/\/ if it is a return value...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ retval list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ if it is missing, add an empty docu block\n\t\tif(missing)\n\t\t{\n\t\t retval_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# automatically add parameter fields to required_list_\n\t(\n\t # matlab identifier (which can be a parameter and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT\n\t\t >(st_tok)\n\t )\n\t)\n\t=> {\n\t \/\/ store fieldname\n\t assert(p >= tmp_p);\n\t string s(tmp_p, p - tmp_p+1);\n\t fout_ << tmp_string << \".\" << s;\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a parameter\n\t iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n\t if(it != paramlist_.end())\n\t {\n\t\t\/\/ if it is a parameter ...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ return, optional and the required list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t \/\/ found match in retval list\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator moit = optional_list_.find(tmp_string);\n\t\tif(moit != optional_list_.end())\n\t\t{\n\t\t \/\/ found match in optional list\n\t\t list_iterator lit = (*moit).second.find(s);\n\t\t if(lit != (*moit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator roit = required_list_.find(tmp_string);\n\t\tif(roit != required_list_.end())\n\t\t{\n\t\t \/\/ found match in required list\n\t\t list_iterator lit = (*roit).second.find(s);\n\t\t if(lit != (*roit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ in case it IS missing, add an empty field to the required block.\n\t\tif(missing)\n\t\t{\n\t\t required_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# add a @deprecated command to function declaration if disp_deprecated is\n\t# used in function body\n\t('disp_deprecated' . [ \\t]*\n\t . (\n\t\t ';'\n\t\t\t@{tmp_string.assign(\"\");}\n\t\t |\n\t\t '(' . [\\t ]* . \"'\"\n\t\t . ([^\\n']*\n\t\t\t >(st_tok)\n\t\t\t %(string_tok)\n\t\t\t)\n\t\t . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n\t\t)\n\t . [\\t ]* . EOL\n\t)\n\t => {\n\t\tstring s;\n\t\tif(tmp_string.empty())\n\t\t{\n\t\t s.assign(\"@deprecated function deprecated\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n\t\t}\n\t\tdocuextra_.push_back(s);\n\t\tfhold;\n\t };\n\n\t# simple matlab identifier\n\t(IDENT)\n\t => { fout_.write(ts, te-ts); };\n\n\t# translate curly brackets in edgy brackets, because otherwise the doxygen\n\t# parser breaks.\n\t('{')\n\t => { fout_ << '['; };\n\n\t('}')\n\t => { fout_ << ']'; };\n\t\n\t('\\'')\n\t => { fout_ << \"^t\"; };\n\n\t# simply output all other characters\n\t(default - [\\r\\n{}\\'])\n\t => { fout_ << fc; };\n\n\t# after EOL try to check for new function\n\tEOL\n\t => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n\t # things that got replaced in function body {{{4\n\t ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n\t\t=> {\n\t\t new_syntax_ = true;\n\t\t fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n\t\t};\n\n\t ([ \\t]* . '%@@remove' . ((default - '%') | ('%' . (default - '@')) | ('%' . '@' . (default -'@')))* . '%@@endremove');\n\n\t # a comment block\n\t ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n\t\t=> {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\tfout_.write(tmp_p, p - tmp_p - 1);\n\t\t else\n\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t fcall in_comment_block;\n\t\t};\n\n\t # empty line\n\t ([ \\t]* . EOL)\n\t\t=> { fout_ << '\\n'; };\n\n\t #}}}4\n\n\t # line not beginning with words 'function' or 'end'\n\t ([ \\t]*\n\t . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n\t )\n\t\t=> {\n\t\t p = ts-1;\n\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n\t\t fgoto funcline;\n\t\t};\n\n\t # things that could end the function body {{{4\n\t # line only containing word 'end'\n\t # the keyword needs to be in the same indentation level as beginning function\n\t ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n\t\t => {\n\t\t\t if(is_class_ && class_part_ == Method)\n\t\t\t {\n\t\t\t\ttmp_string.assign(ts,p-ts+1);\n\n\t\t\t\tif(tmp_string.find(\"e\") == funcindent_)\n\t\t\t\t{\n\t\t\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n\t\t\t\t fgoto methods;\n\t\t\t\t}\n\t\t\t }\n\t\t\t \/\/ else\n\t\t\t p=ts-1;\n\t\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n\t\t\t fgoto funcline;\n\t\t };\n\n\t # line beginning with word 'function'\n\t ([ \\t]*. 'function ')\n\t {\n\t\ttmp_string.assign(ts,p-ts+1);\n\t\tp = ts-1;\n\n\t\tif (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n\t\t{\n\t\t \/\/ end the previous function if existent\n\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n\t\t fgoto main;\n\t\t}\n\t\telse\n\t\t{\n\t\t fgoto funcline;\n\t\t}\n\t };\n\n\t (EOF) $eof(end_of_file);\n\n\t # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n\t. \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n\t. ( default - [\\r\\n] )* . EOL\n )\n\t=> {\n\t assert(tmp_p2 >= tmp_p3);\n\t tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n\t \/\/ std::fout_ << tmp_string << '\\n';\n\t assert(p >= tmp_p);\n\t (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n\t};\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n\t# at least one word (non white-space characters and no double-colon)\n\t. ( default - [ \\r\\t:\\n] )+ .\n\t# followed by something that is a white-space or a new-line, i.e *no*\n\t# double-colon\n\t(\n\t EOL\n\t |\n\t [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - [\\r\\n])* . EOL)\n\t # [ \\t] . (default - '\\n')* . EOL\n\t)\n )\n\t=> {\n\t assert(p+1 >= tmp_p);\n\t string s(tmp_p, p - tmp_p + 1);\n\t (*clist_)[tmp_string].push_back(s);\n\t \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n\t};\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n\t=> { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n\t=> {\n\t p =ts-1;\n\t \/\/ fout_ << \"*\/\\n\";\n\t fret;\n\t};\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n\t# special lists {{{4\n\n\t# begin required_list\n\t( doc_begin . [ \\t]*\n\t . \/required fields of \/i\n\t . (IDENT >(st_tok) %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL\n\t)\n\t => {\n\t\t\/\/fout_ << tmp_string << '\\n';\n\t\tclist_ = &(required_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/optional fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(optional_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/generated fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(retval_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin parameter list\n\t( doc_begin . [ \\t]*\n\t . \/parameters\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = ¶m_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin return list\n\t( doc_begin . [ \\t]*\n\t . \/return values\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &return_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\t#}}}4\n\n\t# default substitutions {{{4\n\n\t# empty line\n\t( doc_begin . [ \\t]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n \";*\/\n\t\tdocubody_.push_back(\"\\n\");\n\t\tdocline = false;\n\t };\n\n\t# paragraph line with second % in text (matlab comment in comment)\n\t( [ \\t]* . '%' . [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docubody_.push_back(\"%\");\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line\n\t( [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line with \"see also\" substituted by \"@sa\"\n\t( \/see also\/i . ':'? )\n\t => {\n\t\tstring s;\n\t\tassert(ts > tmp_p);\n\t\ts.assign(tmp_p+1, ts - tmp_p-1);\n\t\tdocubody_.push_back(s+\"@sa\");\n\t\ttmp_p = p;\n\t };\n\n\t# verbatim or code switches\n\t( [\\\\@] .\n\t\t(\/verbatim\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@verbatim\");\n\t\t}\n\t\t|\n\t\t\/code\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@code\");\n\t\t}\n\t\t));\n\t( [\\\\@] .\n\t\t(\/endverbatim\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endverbatim\");\n\t\t}\n\t\t|\n\t\t\/endcode\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endcode\");\n\t\t}\n\t\t) );\n\n\t# lines that could end doxyblock {{{6\n\t# words\n\t# RAGEL comment: ( default - [ \\t:%'`\\n] )+\n\t( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n\t# non-words\/non-whitespace\n\t# RAGEL comment: ([:'`]) => {\n\t(':') @(end_doxy_block) ;\n\n\t# whitespace only\n\t( [ \\t] );\n\n\t# titled paragraph\n\t( ':' . EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t assert(ts > tmp_p);\n\t\t docubody_.push_back((!is_voc ? \"@par \":\"\") + string(tmp_p+1, ts - tmp_p-1)+(is_voc ? \":\":\"\")+\"\\n\");\n\t\t docline = false;\n\t\t }\n\t };\n\t# }}}6\n\t# }}}4\n\n\t# end of line {{{4\n\t( EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t\tint offset = ( latex_begin ? 0 : 1 );\n\t\t\tassert(p >= tmp_p + offset);\n\t\t\tdocubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n\t\t\tdocline = false;\n\t\t }\n\t\t};\n\t # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n\tgarbage = ( (default - [\\r\\n] )* -- '...' );\n\n\t( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n\t( doc_begin . (garbage . '...')* . garbage . EOL )\n\t => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n\t# read in one comment line\n\t( doc_begin . [\\t ]*\n\t . (default - [\\r\\n\\t ]) . (default - [\\r\\n])* . EOL\n\t)\n\t => {\n\t\t\/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n\t\tassert(p >= tmp_p);\n\t\tdocuheader_.push_back(string(tmp_p, p - tmp_p+1));\n\t };\n\n\t# empty line\n\t( doc_begin . [\\t ]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n\t\tfgoto doxy_get_body;\n\t };\n\n\t# end of comment block;\n\t( [\\t ]* . [^%] )\n\t => {\n\t\tp=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n\t\t\/\/fout_ << \"*\/\\n\";\n\t\tif(is_class_)\n\t\t{\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n\t\t if(class_part_ == Header)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n\t\t\tend_of_class_doc();\n\t\t\tfgoto classbody;\n\t\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n\t\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t\t return 1;\n\t\t\tprint_function_synopsis();\n\t\t\tfgoto funcbody;\n\t\t }\n\t\t else if(class_part_ == MethodDeclaration)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n\t\t\tfgoto funcdef;\n\t\t }\n\t\t else if(class_part_ == Property || class_part_ == Event)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n\t\t\tfgoto propertybody;\n\t\t }\n\t\t else if(class_part_ == InClassComment)\n\t\t {\n\t\t\tclass_part_ = Method;\n\t\t\tfgoto methods;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n\t'%' . [ \\t]* .\n\t (\n\t\t('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n\t )\n\t $!{\n#ifdef DEBUG\n\t\tdebug_output(\"doxy_get_brief\",p);\n#endif\n\t\tp = tmp_p - 2;\n\t\tfgoto doxy_get_brief;\n\t }\n ); #}}}2\n\n # access specifier expressions\n spec_public = ( 'public'i | \"'public'\"i );\n spec_protected = ( 'protected'i | \"'protected'\"i );\n spec_private = ( 'private'i | \"'private'\"i );\n \n spec_class_single = \n\t (\n\t ('?' . (IDENT_W_DOT**) >st_tok )\n\t %{\n\t\t\ttmp_string.assign(tmp_p, p - tmp_p);\n\t\t\t\/\/cerr << \"Detected \" << access_.state << \" modifier by class \" << tmp_string << \"\\n\";\n\t\t\taccess_.classMemberAccess.push_back(make_pair(access_.state, tmp_string));\n\t\t}\n\t ) . WS*;\n \n spec_class_multi = '{' . WS* . spec_class_single . ( [,; ] . WS* . spec_class_single )* . '}';\n \n spec_classes = ( spec_class_single | spec_class_multi );\n\t\n # helper for setting the access specifier {{{2\n paramaccess =\n\t( ('SetAccess' @{ access_.state = SetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public \n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'GetAccess' @{ access_.state = GetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'Access' @{ access_.state = Access; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = Protected; access_.get = Protected; access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = Private; access_.get = Private; access_.set = Private;\n\t\t\t } )\n\t\t )\n\t )\n\t); #}}}2\n\n eventparam =\n\t( ('ListenAccess' @{ access_.state = ListenAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'NotifyAccess' @{ access_.state = NotifyAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t );\n\n # method and property params {{{2\n methodparam =\n (\n\t( paramaccess )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.abstr = true;\n\t\t } )\n\t| ( ( 'Static' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.statical = true;\n\t\t } )\n\t| ( ('Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.hidden = true;\n\t\t } )\n\t| ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.sealed = true;\n\t\t } )\n\t| ( ( 'Test' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.test = true;\n\t\t } )\n\t| ( ( 'TestMethodSetup' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodSetup = true;\n\t\t } )\n\t| ( ( 'TestMethodTeardown' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodTeardown = true;\n\t\t } )\n );\n\n propertyparam =\n (\n\t( paramaccess )\n\t| ( ( 'Constant' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.constant = true;\n\t\t } )\n\t| ( ( 'Transient' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.transient = true;\n\t\t } )\n\t| ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.dependent = true;\n\t\t } )\n\t| ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t| ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.setObservable = true;\n\t\t } )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abstr = true;\n\t\t } )\n\t| ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abortSet = true;\n\t\t } )\n );\n\n methodparams =\n (\n\t'(' . WSOC*\n\t. methodparam\n\t. ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n eventparams =\n (\n\t'(' . WSOC*\n\t. eventparam\n\t. ( WSOC* . ',' . WSOC* . eventparam )* . WSOC* . ')'\n ); #}}}2\n\n propertyparams =\n (\n\t'(' . WSOC*\n\t. propertyparam\n\t. ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n\t(empty_line) => {\n\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t {\n\t\tend_method();\n\t\tfout_ << \"\\n\";\n\t }\n\t};\n\n\t# default: method definition\n\t([ \\t]* . 'function' )\n\t => {\n\t\ttmp_string.assign(ts, te - ts+1);\n\t\tfuncindent_ = tmp_string.find_first_not_of(\" \\t\");\n\t\tfout_ << string(ts, ts+funcindent_);\n\t\t#if DEBUG\n\t\t\t{\n\t\t\t ostringstream oss;\n\t\t\t oss << \"in methods: funcindent: \" << funcindent_;\n\t\t\t debug_output(oss.str(), p);\n\t\t\t}\n\t\t#endif\n\t\tp=ts+funcindent_-1;\n\t\tfgoto funct;\n\t };\n\n\t# end of methods block\n\t([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n\t => {\n\t\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t\t {\n\t\t\t end_method();\n\t\t\t #if DEBUG\n\t\t\t debug_output(\"in methods: found end keyword, goto classbody\",p);\n\t\t\t #endif\n\t\t }\n\t\t fgoto classbody;\n\t\t };\n\n\t# comment between two methods\n\t([ \\t]* . '%' ) => {\n\t #if DEBUG\n\t\tdebug_output(\"in methods: garble comment line\",p);\n\t #endif\n\n\t p = ts-1;\n\t class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n\t fgoto expect_doxyblock;\n\t};\n\n\t# if we reach this: method declaration without definition is found\n\t([ \\t]* . [^% \\t\\n]) =>\n\t{\n\t #if DEBUG\n\t\tdebug_output(\"in methods: found method declaration, going to funcdef\",p);\n\t #endif\n\t class_part_ = MethodDeclaration;\n\t p = ts-1;\n\t fgoto funcdef;\n\t};\n\n\t *|;\n\n\n methodsheader := (\n\t[ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n\t\t @{\n\t\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t\tfgoto methods;\n\t\t }\n\t\t );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_property_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\")\n\t\t\t\tfgoto classbody;\n\t\t\t if (propertyparams_.dependent)\n\t\t\t\tspecifier_[s].dependent = true;\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t )\n\t\t. WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n\t\t\t|\n\t\t\t( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n\t\t\t@{\n\t\t\t defaultprop_ = string(tmp_p2, p - tmp_p2);\n\t\t\t string::size_type last_elem = defaultprop_.length() -1;\n\t\t\t if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n\t\t\t {\n\t\t\t\tdefaultprop_[0] = '\\\"';\n\t\t\t\tdefaultprop_[last_elem] = '\\\"';\n\t\t\t }\n\t\t\t string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n\t\t\t string::size_type last_paren;\n\t\t\t if (first_paren == string::npos)\n\t\t\t {\n\t\t\t\tfirst_paren = 1;\n\t\t\t\tlast_paren = last_elem;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tlast_paren = defaultprop_.find_last_of(\")]}\");\n\t\t\t\tif (last_paren == string::npos)\n\t\t\t\t last_paren=last_elem-1;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n\t\t\t\t {\n\t\t\t\t\tfirst_paren++;\n\t\t\t\t\tlast_paren--;\n\t\t\t\t }\n\t\t\t\t defaultprop_.insert(first_paren, 1,'\"');\n\t\t\t\t defaultprop_.insert(last_paren+2, 1,'\"');\n\t\t\t\t first_paren++;\n\t\t\t\t last_paren++;\n\t\t\t\t}\n\t\t\t }\n\t\t\t for (unsigned int i = first_paren; i < last_paren; ++i)\n\t\t\t {\n\t\t\t\tif(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n\t\t\t\t{\n\t\t\t\t defaultprop_[i] = ' ';\n\t\t\t\t defaultprop_[i+1] = ' ';\n\t\t\t\t defaultprop_[i+2] = ' ';\n\t\t\t\t}\n\/* else if(defaultprop_[i] == '[')\n\t\t\t\t defaultprop_[i] = '{';\n\t\t\t\telse if(defaultprop_[i] == ']')\n\t\t\t\t defaultprop_[i] = '}'; *\/\n\t\t\t\telse if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n\t\t\t\t defaultprop_[i] = ',';\n\t\t\t\telse if(defaultprop_[i] == '\\\"')\n\t\t\t\t defaultprop_[i] = '\\'';\n\t\t\t\telse if(defaultprop_[i] == '@')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t\telse if(defaultprop_[i] == '\\n')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t }\n\t\t\t }\n\t\t )\n\t );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n properties := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. propertybody* )\n\t );\n\n #property body {{{4\n eventbody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n events := ((\n\tWSOC* . eventparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. eventbody* )\n\t );\n\n enum = ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_enum_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\") {\n\t\t\t\tfout_ << \"\\n} \" << classname_ << \"Enum;\\n\";\n\t\t\t\tfgoto classbody;\n\t\t\t }\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t . WS* . ( '%' @{ fhold; } | ';' | ',' | EOL )\n\t\t );\n\n enumerationbody = (\n\t(enum)\n\t|\n\t( (empty_line) @{ end_of_enum_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n enumeration := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\tfout_ << \"typedef enum {\\n\";\n\t\t}\n\t. enumerationbody* )\n\t );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n\t# a comment block\n\t(comment_block)\n\t => {\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p - 1);\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p);\n\t\tfcall in_comment_block;\n\t };\n\n\t(WSOC); # => { fout_.write(ts, te-ts); };\n\n\t(EOL) => { fout_ << \"\\n\"; };\n\n\t('end' . [ \\t]* ';'?) => {\n\t std::map::iterator specIt;\n\t for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n\t {\n\t\tfout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n\t\tif ( (*specIt).second.dependent)\n\t\t{\n\t\t if( (*specIt).second.getter && ! (*specIt).second.setter )\n\t\t {\n\t\t\tfout_ << \"@note [readonly]\\n *\";\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t fout_ << \"@note This property has custom functionality when its value is \";\n\t\t if ((*specIt).second.getter)\n\t\t {\n\t\t\tfout_ << \"retrieved\";\n\t\t\tif ((*specIt).second.setter)\n\t\t\t fout_ << \" or changed\";\n\t\t }\n\t\t else if ((*specIt).second.setter)\n\t\t\tfout_ << \"changed\";\n\t\t fout_ << \".\";\n\t\t}\n\t\tfout_ << \"\\n *\/\\n\";\n\t }\n\t fout_ << \"\\n};\\n\";\n\t for( list::iterator it = namespaces_.begin();\n\t\t\tit != namespaces_.end(); ++it)\n\t {\n\t\tfout_ << \"}\\n\";\n\t }\n\t};\n\n\t([ \\t]* . 'properties')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Property;\n\t\tfgoto properties;\n\t };\n\t([ \\t]* . 'methods')\n\t => {\n\t\tmethodparams_ = MethodParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Method;\n\t\tfgoto methodsheader;\n\t };\n\t([ \\t]* . 'events')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\tpropertyparams_.event = true;\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Event;\n\t\tfgoto events;\n\t };\n\t([ \\t]* . 'enumeration')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Enumeration;\n\t\tfgoto enumeration;\n\t };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n\tdoc_begin\n\t @{\n\t\t\/\/fout_ << \"\/*\";\n\t\tp--;\n\t\tfgoto doxyheader;\n\t }\n )\n $!{\n\tfhold;\n\t{\n\t int i = 0;\n\t for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n\t\t;\n\t std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n\tdebug_output(\"stopping expect_doxyblock\", p);\n#endif\n\tif(is_class_)\n\t{\n\t if(class_part_ == Header)\n\t {\n\t\tend_of_class_doc();\n\t\tfgoto classbody;\n\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t {\n\t\tstring endstringtest;\n\t\tendstringtest.assign(p, 100);\n\t\tstring::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tif (endstringtest.substr(first_char, 3) == \"end\")\n\t\t{\n\t\t p += first_char+4;\n\t\t print_function_synopsis();\n\t\t end_function();\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t print_function_synopsis();\n\t\t fout_ << whitespaces;\n\t\t fgoto funcbody;\n\t\t}\n\t }\n\t else if(class_part_ == Property || class_part_ == Event)\n\t {\n\t\tfgoto propertybody;\n\t }\n\t else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n\t {\n\t\tclass_part_ = Method;\n\t\tfgoto methods;\n\t }\n\t else{\n\t\tcerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n\t }\n\t}\n\telse\n\t{\n\t if(runMode_.mode == RunMode::ParseParams)\n\t\treturn 1;\n\t print_function_synopsis();\n\t fout_ << whitespaces;\n\t fgoto funcbody;\n\t}\n\t}\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n\t (WSOC)* .\n\t # return values (if found opt = true)\n\t (lparams)? .\n\t # matlab identifier (function name stored in cfuncname_)\n\t ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n\t\tIDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tcfuncname_.assign(tmp_p, p - tmp_p);\n\t\t\t#ifdef DEBUG\n\t\t\t cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n\t\t\t#endif\n\t\t\t\/\/ in ParseMethodParams mode, we only check for the method\n\t\t\t\/\/ parameters of a specific method.\n\t\t\tif(is_class_ && class_part_ == MethodDeclaration\n\t\t\t && runMode_.mode == RunMode::ParseMethodParams)\n\t\t\t{\n\t\t\t if(runMode_.methodname == cfuncname_)\n\t\t\t {\n\t\t\t\treturn 0;\n\t\t\t }\n\t\t\t}\n\t\t\tif(runMode_.mode == RunMode::Normal\n\t\t\t && is_class_ && class_part_ == AtMethod)\n\t\t\t{\n\t\t\t update_method_params(cfuncname_);\n\t\t\t}\n\t\t\tis_script_ = false;\n\t\t }\n\t )\n\t . WSOC*\n\t . (\n\t\t '('\n\t\t # parameter list\n\t\t . ( paramlist\n\t\t\t %{\n\t\t\t\t if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n\t\t\t\t { paramlist_.clear(); }\n\t\t\t }\n\t\t\t )\n\t\t . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )*\n\t\t . EOL\n\t\t @{\n\t\t\t if(comment_found)\n\t\t\t {\n\t\t\t\ttmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\ttmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\ttmp_string = \"\";\n\t\t\t }\n\t\t\t comment_found = false;\n\t\t\t if(is_class_ && class_part_ == MethodDeclaration )\n\t\t\t {\n\t\t\t class_part_ = Method;\n\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n\t\t\t #endif\n\t\t\t fgoto methods;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t \/\/ fout_ << tmp_string << \"{\\n\";\n\t\t\t \/\/ check for documentation block\n\t\t\t fgoto expect_doxyblock;\n\t\t\t }\n\t\t }\n\t\t# no parameter list && first function => ( script || method )\n\t\t| (( [ \\t]\n\t\t\t |\n\t\t\t ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n\t\t\t@{\n\t\t\t\t if(comment_found)\n\t\t\t\t {\n\t\t\t\t tmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\t tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t tmp_string = \"\";\n\t\t\t\t }\n\t\t\t\t comment_found = false;\n\t\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n\t\t\t\t #endif\n\t\t\t\t if(is_class_ && class_part_ == MethodDeclaration)\n\t\t\t\t {\n\t\t\t\t\tclass_part_ = Method;\n\t\t\t\t\tfgoto methods;\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t fgoto expect_doxyblock;\n\t\t\t\t }\n\t\t\t }\n\t\t)\n\t );\n\n funct :=\n (\n\t(\n\t comment_block @in_c_block\n\t | [ \\t]*. EOL\n\t)*\n\t. ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n\t@{\n\t string :: size_type found = filename_.rfind(\"\/\");\n\t if(found == string :: npos)\n\t\t found = -1;\n\t string funcname = filename_.substr(found+1, filename_.size()-3-found);\n\t cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n\t if(!is_first_function_)\n\t\t fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\t fout_ << funcname << \"() {\\n\";*\/\n\t is_script_ = true;\n\t fhold;\n\t fgoto expect_doxyblock;\n\t }; #}}}2\n\n # class definitions {{{2\n classparams =\n\t '(' . [^)]* . ')';\n\n superclass =\n\t( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n\t\t\t\t\t @{ if(*p == '.')\n\t\t\t\t\t\t fout_ << \"::\";\n\t\t\t\t\t\t else fout_ << *p; } );\n\n superclasses = (\n\t '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n\t\t . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n\t 'classdef' . WSOC* . ('(' . WSOC*\n\t\t. (( 'Sealed'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n\t\t }\n\t\t )\n\n\t\t |( 'Hidden'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Hidden' and is invisible.\"));\n\t\t }\n\t\t )\n\t\t |( 'Abstract'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Abstract' and needs to be inherited in order to be instantiable.\"));\n\t\t }\n\t\t )) . [^)]* . ')')? . WSOC* .\n\t # matlab identifier (class name stored in classname_)\n\t ( IDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tclassname_.assign(tmp_p, p - tmp_p);\n\t\t\tis_class_ = true;\n\t\t\tfout_ << \"class \" << classname_;\n\t\t }\n\t )\n\t . WSOC*\n\t . classparams?\n\t . WSOC*\n\t . superclasses?\n\t . [ \\t;]*\n\t . ( '%'. garble_comment_line_wo_eol )?\n\t EOL\n\t @{\n\t\tfout_ << \" {\\n\";\n\t\tfgoto expect_doxyblock;\n\t } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n\t# either we find a function or classdef definition with a possibly\n\t# preceding comment block or we have a script\n\t( any\n\t @{\n\t\t fhold;\n\t\t tmp_p = p;\n\t\t}\n\t .\n\t(\n\t [ \\t]*. '%' . (any - '\\n')* . EOL\n\t | [ \\t]*. EOL\n\t)*\n\t. [\\t]*\n\t. ( 'function' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t char *tp;\n\t\t\t\t\t for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n\t\t\t\t\t ;\n\t\t\t\t\t funcindent_ = (int)(p - tp);\n#if DEBUG\n\t\t\t\t\t {\n\t\t\t\t\t ostringstream oss;\n\t\t\t\t\t oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n\t\t\t\t\t debug_output(oss.str(), p);\n\t\t\t\t\t }\n#endif\n\t\t\t\t\t if(is_class_ && class_part_ == Header)\n\t\t\t\t\t class_part_ = AtMethod;\n\t\t\t\t\t fgoto funct;\n\t\t\t\t\t}\n\t | 'classdef' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t fgoto classdef;\n\t\t\t\t\t}\n\t ) )\n $!{\n#ifdef DEBUG\n\tdebug_output(\"goto script\",p);\n#endif\n\tp=tmp_p;\n\tfgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n\tchar *p = buf + have;\n\tchar *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n\tstring tmp_string, tmp_string2, tmp_string3;\n\tbool docline = false;\n\tbool latex_begin = true;\n\tbool comment_found = false;\n\tint space = BUFSIZE - have;\n\n\tif ( space == 0 )\n\t{\n\t \/* We filled up the buffer trying to scan a token. *\/\n\t cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n\t exit(-1);\n\t}\n\n\tfin_.read( p, space );\n\tint len = fin_.gcount();\n\tchar *pe = p + len;\n\tchar *rpe = pe;\n\tchar *eof = 0;\n\n\t\/* If we see eof then append the EOF char. *\/\n\tif ( fin_.eof() )\n\t{\n\t char eof_c = *pe;\n\t *pe = '\\n';\n\t pe++;\n\t *pe = eof_c;\n\t eof = pe;\n\t rpe = pe;\n\n\t done = true;\n\t}\n\telse\n\t{\n\t \/* Find the last newline by searching backwards. This is where\n\t * we will stop processing on this iteration. *\/\n\t while ( pe >= p )\n\t {\n\t\tif( *pe != '\\n')\n\t\t pe--;\n\t\telse\n\t\t{\n\t\t if(pe >= p+3\n\t\t\t && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n\t\t\tpe-=3;\n\t\t else\n\t\t\tbreak;\n\t\t}\n\t }\n\t}\n\n\t%% write exec;\n\n\t\/* Check if we failed. *\/\n\tif ( cs == MFileScanner_error )\n\t{\n\t \/* Machine failed before finding a token. *\/\n\t cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n\t debug_output(\"Grrrr!!!!\", p);\n\t exit(-1);\n\t}\n\n\t\/* Now set up the prefix. *\/\n\tif ( ts == 0 )\n\t{\n\t have = rpe - pe;\n\t \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n\t memmove( buf, pe, have );\n\t}\n\telse\n\t{\n\t have = rpe - ts;\n\t \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n\t memmove( buf, ts, have );\n\t}\n\n\tif ( ts != 0 )\n\t{\n\t te -= (ts-buf);\n\t ts = buf;\n\t}\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"f5de769f9d5cff5ee0746b3b67251dde49c867aa","subject":"Fix cut and paste error","message":"Fix cut and paste error\n\nshould be subtitle not audio\n","repos":"yanfali\/gomkv","old_file":"src\/handbrake\/handbrake.rl","new_file":"src\/handbrake\/handbrake.rl","new_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"strconv\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\ntype Section int\nconst (\n\tNONE Section = iota\n\tCHAPTER\n\tAUDIO\n\tSUBTITLE\n)\n\nfunc parseTime(timestring string) float64 {\n\trawTime := strings.Trim(timestring, \" \\n\");\n\tsplitTime := strings.Split(rawTime, \":\")\n\tvar length float64\n\thours, err := strconv.ParseInt(splitTime[0], 10, 8)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlength += float64(hours * 60 * 60)\n\tminutes, err := strconv.ParseInt(splitTime[1], 10, 8)\n\tlength += float64(minutes * 60)\n\tseconds, err := strconv.ParseInt(splitTime[2], 10, 8)\n\tlength += float64(seconds)\n\treturn length\n}\n\nfunc parseInt(value string) int {\n\tif result, err := strconv.ParseInt(value, 10, 32); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\treturn int(result)\n\t}\n\treturn 0\n}\n\nfunc getLastAudioMeta(meta HandBrakeMeta) *AudioMeta {\n\tif len(meta.Audio) == 0 {\n\t\tpanic(\"No audio available!\")\n\t}\n\treturn &meta.Audio[len(meta.Audio)-1]\n}\n\nfunc getLastSubtitleMeta(meta HandBrakeMeta) *SubtitleMeta {\n\tif len(meta.Subtitle) == 0 {\n\t\tpanic(\"No subtitle available!\")\n\t}\n\treturn &meta.Subtitle[len(meta.Subtitle)-1]\n}\n\nfunc parseOutput(data string) HandBrakeMeta {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\tvar stack = []int{0}\n\tvar section = NONE\n\tvar meta = HandBrakeMeta{}\n\tline := 1\n\tfmt.Printf(\"%02d: \", line)\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\tstitle := |*\n\t\t\t([^.])+[.]alnum+ => {\n\t\t\t\tmeta.Title = strings.Trim(data[ts:te], \" \\n\");\n\t\t\t\tfmt.Printf(\"%s\", meta.Title);\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tsduration := |*\n\t\t\tspace+;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => {\n\t\t\t\tmeta.Duration = parseTime(data[ts:te])\n\t\t\t\tfmt.Printf(\"%f\", meta.Duration);\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} \",\" => {\n\t\t\t\traw := data[ts:te-1];\n\t\t\t\tvalues := strings.Split(raw, \"x\");\n\t\t\t\tmeta.Width = parseInt(values[0]);\n\t\t\t\tmeta.Height = parseInt(values[1]);\n\t\t\t\tfmt.Printf(\"1-%s:\", data[ts:te-1]);\n\t\t\t};\n\t\t\tspace*;\n\t\t\t\"pixel\" space+ \"aspect:\";\n\t\t\tdigit{1,4} \"\/\" digit{1,4} \",\" => {\n\t\t\t\tmeta.Pixelaspect = data[ts:te-1]\n\t\t\t\tfmt.Printf(\"2-%s:\", meta.Pixelaspect);\n\t\t\t};\n\t\t\tspace*;\n\t\t\t\"display\" space+ \"aspect:\" space*;\n\t\t\tdigit . \".\" . digit{1,3} \",\" => {\n\t\t\t\tmeta.Aspect = data[ts:te-1]\n\t\t\t\tfmt.Printf(\"3-%s:\", data[ts:te-1])\n\t\t\t};\n\t\t\tspace*;\n\t\t\tdigit{2} . \".\" digit{3} space+ \"fps\" \"\\n\" => {\n\t\t\t\traw := data[ts:te-5]\n\t\t\t\tmeta.Fps = raw\n\t\t\t\tfmt.Printf(\"4-%s\", meta.Fps)\n\t\t\t\tp -= 1; fret;\n\t\t\t};\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tatrack := |*\n# Language\n\t\t\t[A-Z] alpha+ => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Language = data[ts:te]\n\t\t\t\tfmt.Printf(\"a-%s:\", audio.Language)\n\t\t\t};\n\t\t\tspace;\n# Codec\n\t\t\t\"(\" (\"AC3\" | \"DTS\" | \"aac\") \")\" => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Codec = data[ts+1:te-1]\n\t\t\t\tfmt.Printf(\"b-%s:\", audio.Codec);\n\t\t\t};\n\n\t\t\tspace;\n# Channels\n\t\t\t\"(\" digit . \".\" . digit space \"ch)\" space => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Channels = data[ts-1:te-5]\n\t\t\t\tfmt.Printf(\"c-%s:\", audio.Channels)\n\t\t\t};\n# Ignore this bit\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \"),\";\n# Hertz\n\t\t\tspace;\n\t\t\tdigit+ \"Hz,\" => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Frequency = parseInt(data[ts:te-3])\n\t\t\t\tfmt.Printf(\"d-%s:\", audio.Frequency)\n\t\t\t};\n\t\t\tspace;\n# Bps\n\t\t\tdigit+ \"bps\" => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Bps = parseInt(data[ts:te-3])\n\t\t \t\tfmt.Printf(\"e-%s\", audio.Bps)\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tsubtype = \"Bitmap\" | \"Text\";\n\t\tformat = \"VOBSUB\" | \"UTF-8\";\n\t\tsubtitle := |*\n\t\t\t[A-Z] alpha+ - subtype - format => {\n\t\t\t\tsubtitle := getLastSubtitleMeta(meta)\n\t\t\t\tsubtitle.Language = data[ts:te];\n\t\t\t\tfmt.Printf(\"a-%s:\", subtitle.Language);\n\t\t\t};\n\t\t\tspace;\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \")\";\n\t\t\tspace;\n\t\t\t\"(\" subtype \")\" => {\n\t\t\t\tsubtitle := getLastSubtitleMeta(meta)\n\t\t\t\tsubtitle.Type = data[ts+1:te-1]\n\t\t\t\tfmt.Printf(\"b-%s:\", subtitle.Type)\n\t\t\t};\n\t\t\t\"(\" format \")\" => {\n\t\t\t\tsubtitle := getLastSubtitleMeta(meta)\n\t\t\t\tsubtitle.Format = data[ts+1:te-1]\n\t\t\t\tfmt.Printf(\"c-%s\", subtitle.Format)\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tword = [a-z]+;\n\t\tprefix = space+ \"+\";\n\t\tprefixsp = prefix space;\n\t\tstream = prefixsp \"stream:\";\n\t\tduration = prefixsp \"duration:\";\n\t\tvideo = prefixsp \"size:\";\n\t\tautocrop = prefixsp \"autocrop:\";\n\t\ttrack = prefixsp digit \",\" space;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tstream @{ fcall stitle; } |\n\t\t\tduration @{ fcall sduration; } |\n\t\t\tvideo @{ fcall picture; } |\n\t\t\tautocrop @{ fcall crop; } |\n\t\t\tprefixsp \"chapters:\" @{ section = CHAPTER; fmt.Printf(\"chapter\"); } |\n\t\t\tprefixsp \"audio tracks:\" @{ section = AUDIO; fmt.Printf(\"audio\"); } |\n\t\t\tprefixsp \"subtitle tracks:\" @{ section = SUBTITLE; fmt.Printf(\"subtitle\"); } |\n\t\t\ttrack @{\n\t\t\t\tswitch section {\n\t\t\t\tcase AUDIO:\n\t\t\t\t\taudio := AudioMeta{}\n\t\t\t\t\tmeta.Audio = append(meta.Audio, audio)\n\t\t\t\t\tfcall atrack;\n\t\t\t\tcase SUBTITLE:\n\t\t\t\t\tsubtitle := SubtitleMeta{}\n\t\t\t\t\tmeta.Subtitle = append(meta.Subtitle, subtitle)\n\t\t\t\t\tfcall subtitle;\n\t\t\t\t}\n\t\t\t}\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","old_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"strconv\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\ntype Section int\nconst (\n\tNONE Section = iota\n\tCHAPTER\n\tAUDIO\n\tSUBTITLE\n)\n\nfunc parseTime(timestring string) float64 {\n\trawTime := strings.Trim(timestring, \" \\n\");\n\tsplitTime := strings.Split(rawTime, \":\")\n\tvar length float64\n\thours, err := strconv.ParseInt(splitTime[0], 10, 8)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlength += float64(hours * 60 * 60)\n\tminutes, err := strconv.ParseInt(splitTime[1], 10, 8)\n\tlength += float64(minutes * 60)\n\tseconds, err := strconv.ParseInt(splitTime[2], 10, 8)\n\tlength += float64(seconds)\n\treturn length\n}\n\nfunc parseInt(value string) int {\n\tif result, err := strconv.ParseInt(value, 10, 32); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\treturn int(result)\n\t}\n\treturn 0\n}\n\nfunc getLastAudioMeta(meta HandBrakeMeta) *AudioMeta {\n\tif len(meta.Audio) == 0 {\n\t\tpanic(\"No audio available!\")\n\t}\n\treturn &meta.Audio[len(meta.Audio)-1]\n}\n\nfunc getLastSubtitleMeta(meta HandBrakeMeta) *SubtitleMeta {\n\tif len(meta.Subtitle) == 0 {\n\t\tpanic(\"No audio available!\")\n\t}\n\treturn &meta.Subtitle[len(meta.Subtitle)-1]\n}\n\nfunc parseOutput(data string) HandBrakeMeta {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\tvar stack = []int{0}\n\tvar section = NONE\n\tvar meta = HandBrakeMeta{}\n\tline := 1\n\tfmt.Printf(\"%02d: \", line)\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\tstitle := |*\n\t\t\t([^.])+[.]alnum+ => {\n\t\t\t\tmeta.Title = strings.Trim(data[ts:te], \" \\n\");\n\t\t\t\tfmt.Printf(\"%s\", meta.Title);\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tsduration := |*\n\t\t\tspace+;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => {\n\t\t\t\tmeta.Duration = parseTime(data[ts:te])\n\t\t\t\tfmt.Printf(\"%f\", meta.Duration);\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} \",\" => {\n\t\t\t\traw := data[ts:te-1];\n\t\t\t\tvalues := strings.Split(raw, \"x\");\n\t\t\t\tmeta.Width = parseInt(values[0]);\n\t\t\t\tmeta.Height = parseInt(values[1]);\n\t\t\t\tfmt.Printf(\"1-%s:\", data[ts:te-1]);\n\t\t\t};\n\t\t\tspace*;\n\t\t\t\"pixel\" space+ \"aspect:\";\n\t\t\tdigit{1,4} \"\/\" digit{1,4} \",\" => {\n\t\t\t\tmeta.Pixelaspect = data[ts:te-1]\n\t\t\t\tfmt.Printf(\"2-%s:\", meta.Pixelaspect);\n\t\t\t};\n\t\t\tspace*;\n\t\t\t\"display\" space+ \"aspect:\" space*;\n\t\t\tdigit . \".\" . digit{1,3} \",\" => {\n\t\t\t\tmeta.Aspect = data[ts:te-1]\n\t\t\t\tfmt.Printf(\"3-%s:\", data[ts:te-1])\n\t\t\t};\n\t\t\tspace*;\n\t\t\tdigit{2} . \".\" digit{3} space+ \"fps\" \"\\n\" => {\n\t\t\t\traw := data[ts:te-5]\n\t\t\t\tmeta.Fps = raw\n\t\t\t\tfmt.Printf(\"4-%s\", meta.Fps)\n\t\t\t\tp -= 1; fret;\n\t\t\t};\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tatrack := |*\n# Language\n\t\t\t[A-Z] alpha+ => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Language = data[ts:te]\n\t\t\t\tfmt.Printf(\"a-%s:\", audio.Language)\n\t\t\t};\n\t\t\tspace;\n# Codec\n\t\t\t\"(\" (\"AC3\" | \"DTS\" | \"aac\") \")\" => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Codec = data[ts+1:te-1]\n\t\t\t\tfmt.Printf(\"b-%s:\", audio.Codec);\n\t\t\t};\n\n\t\t\tspace;\n# Channels\n\t\t\t\"(\" digit . \".\" . digit space \"ch)\" space => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Channels = data[ts-1:te-5]\n\t\t\t\tfmt.Printf(\"c-%s:\", audio.Channels)\n\t\t\t};\n# Ignore this bit\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \"),\";\n# Hertz\n\t\t\tspace;\n\t\t\tdigit+ \"Hz,\" => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Frequency = parseInt(data[ts:te-3])\n\t\t\t\tfmt.Printf(\"d-%s:\", audio.Frequency)\n\t\t\t};\n\t\t\tspace;\n# Bps\n\t\t\tdigit+ \"bps\" => {\n\t\t\t\taudio := getLastAudioMeta(meta)\n\t\t\t\taudio.Bps = parseInt(data[ts:te-3])\n\t\t \t\tfmt.Printf(\"e-%s\", audio.Bps)\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tsubtype = \"Bitmap\" | \"Text\";\n\t\tformat = \"VOBSUB\" | \"UTF-8\";\n\t\tsubtitle := |*\n\t\t\t[A-Z] alpha+ - subtype - format => {\n\t\t\t\tsubtitle := getLastSubtitleMeta(meta)\n\t\t\t\tsubtitle.Language = data[ts:te];\n\t\t\t\tfmt.Printf(\"a-%s:\", subtitle.Language);\n\t\t\t};\n\t\t\tspace;\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \")\";\n\t\t\tspace;\n\t\t\t\"(\" subtype \")\" => {\n\t\t\t\tsubtitle := getLastSubtitleMeta(meta)\n\t\t\t\tsubtitle.Type = data[ts+1:te-1]\n\t\t\t\tfmt.Printf(\"b-%s:\", subtitle.Type)\n\t\t\t};\n\t\t\t\"(\" format \")\" => {\n\t\t\t\tsubtitle := getLastSubtitleMeta(meta)\n\t\t\t\tsubtitle.Format = data[ts+1:te-1]\n\t\t\t\tfmt.Printf(\"c-%s\", subtitle.Format)\n\t\t\t\tfret;\n\t\t\t};\n\t\t*|;\n\t\tword = [a-z]+;\n\t\tprefix = space+ \"+\";\n\t\tprefixsp = prefix space;\n\t\tstream = prefixsp \"stream:\";\n\t\tduration = prefixsp \"duration:\";\n\t\tvideo = prefixsp \"size:\";\n\t\tautocrop = prefixsp \"autocrop:\";\n\t\ttrack = prefixsp digit \",\" space;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tstream @{ fcall stitle; } |\n\t\t\tduration @{ fcall sduration; } |\n\t\t\tvideo @{ fcall picture; } |\n\t\t\tautocrop @{ fcall crop; } |\n\t\t\tprefixsp \"chapters:\" @{ section = CHAPTER; fmt.Printf(\"chapter\"); } |\n\t\t\tprefixsp \"audio tracks:\" @{ section = AUDIO; fmt.Printf(\"audio\"); } |\n\t\t\tprefixsp \"subtitle tracks:\" @{ section = SUBTITLE; fmt.Printf(\"subtitle\"); } |\n\t\t\ttrack @{\n\t\t\t\tswitch section {\n\t\t\t\tcase AUDIO:\n\t\t\t\t\taudio := AudioMeta{}\n\t\t\t\t\tmeta.Audio = append(meta.Audio, audio)\n\t\t\t\t\tfcall atrack;\n\t\t\t\tcase SUBTITLE:\n\t\t\t\t\tsubtitle := SubtitleMeta{}\n\t\t\t\t\tmeta.Subtitle = append(meta.Subtitle, subtitle)\n\t\t\t\t\tfcall subtitle;\n\t\t\t\t}\n\t\t\t}\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"2df14964347f5064e4e31179554059bc8fcbda70","subject":"cleanup","message":"cleanup\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner_parser.rl","new_file":"src\/mfilescanner_parser.rl","new_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n\t @{ fout_ << \"\\n\";\n\t\tfout_.write(tmp_p, p - tmp_p);\n\t\ttmp_p = p+1; fout_ << \" *\";\n\t }\n # and then some default characters\n . ( ( (default - [\\r\\n])* )\n\t %{ fout_.write(tmp_p, p - tmp_p); } )\n\t . EOL\n )*\n $!{\n\tfout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n\tfhold;\n\twhile (*p == ' ')\n\t fhold;\n\tif (extra_hold_in_cblock)\n\t{\n\t fhold;\n\t --line;\n\t extra_hold_in_cblock = false;\n\t}\n\tfret;\n };\n\n action end_doxy_block\n {\n\tif(!docline)\n\t{\n\t p = ts-1;\n\t \/* go backward until first non-whitespace is found *\/\n\t for(p=p-1; *p==' ' || *p == '\\t'; --p)\n\t\t;\n\n\t if(is_class_)\n\t {\n\t\tif(class_part_ == Header)\n\t\t{\n\t\t end_of_class_doc();\n\t\t fgoto classbody;\n\t\t} else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t\telse if(class_part_ == MethodDeclaration)\n\t\t{\n\t\t fgoto funcdef;\n\t\t}\n\t\telse if(class_part_ == Property || class_part_ == Event)\n\t\t{\n\t\t fgoto propertybody;\n\t\t}\n\t\telse if(class_part_ == Enumeration)\n\t\t{\n\t\t fgoto enumerationbody;\n\t\t}\n\t\telse if(class_part_ == InClassComment)\n\t\t{\n\t\t class_part_ = Method;\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n\t\t}\n\t }\n\t else\n\t {\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tprint_function_synopsis();\n\t\tfgoto funcbody;\n\t }\n\t}\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n\tend_function();\n\tfor( list::iterator it = namespaces_.begin();\n\t\t it != namespaces_.end(); ++it)\n\t{\n\t fout_ << \"};\\n\";\n\t}\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n\tassert(p >= tmp_p-1);\n\tif (*p == '\\r')\n\t fout_.write(tmp_p, p-tmp_p);\n\telse\n\t fout_.write(tmp_p, p-tmp_p+1);\n\tfcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action st_tok2 { tmp_p2 = p; }\n\n action echo_tok {\n\tassert (p >= tmp_p);\n\tfout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n\tassert ( p >= tmp_p );\n\ttmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n\t(\n\t# RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n\t# comment\n\t '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n\t\t\tfout_ << \"\/**\"; tmp_p = p+1;\n\t\t }\n\t . (default - [\\r\\n])*\n\t . ( EOL . [ \\t]*\n\t . '%' @{\n\t\t\t\tassert(p >= tmp_p -1);\n\t\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t\t\tfout_ << \" * \";\n\t\t\t\ttmp_p = p+1;\n\t\t\t }\n\t . (default - [\\r\\n])* )* . EOL\n\t |\n\t# RAGEL comment: else: a regular comment\n\t ( (default - '|')\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\t if (string(p, 8) != string(\"@@remove\"))\n\t\t fout_ << \"\/* \";\n\t\t tmp_p = p;\n\t\t } )\n\t . (default - [\\r\\n])* . EOL\n\t);\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin pattern: if found, automatically set the character pointer to the current position (plus one)\n doc_begin = [\\t ]* . '%' @{\n\tif (!docline) {\n\t\ttmp_p = p + 1;\n\t}\n };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n\t( (default - [\\r\\n])* . EOL )\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\tfout_ << \"\/* \";\n\t\tassert( p >= tmp_p );\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n\t };\n garble_comment_line_wo_eol =\n\t(default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n\t( ([ \\t]+ \n\t @{\n\t\t {\n\t\t\tint i=0;\n\t\t\tif (*(p+1) != ' ' && *(p+1) != '\\t')\n\t\t\t{\n\t\t\t while (*(p-i) == ' ' || *(p-i) == '\\t')\n\t\t\t\ti++;\n\t\t\t if (*(p-i) == '\\n')\n\t\t\t\tfout_ << std::string(i, ' ');\n\t\t\t}\n\t\t }\n\t\t})\n\t | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n\t | ('...'.[ \\t]*.EOL)\n\t);\n\n # white space or line continuation\n WS =\n\t( [ \\t]+\n\t | ('...'.[\\t]*.EOL)\n\t);\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n\t(\n\t (WSOC | ',' | EOL\n\t | ( '=' . default_arg ) )+\n\t |\n\t # matlab identifier (parameter)\n\t (IDENT | '~' )\n\t >st_tok\n\t %{\n\t\t assert(p >= tmp_p);\n\t\t string s(tmp_p, p - tmp_p);\n\t\t bool addBlock = true;\n\t\t \/\/ do not print this pointer\n\t\t if( is_class_ && ( !methodparams_.statical\n\t\t\t\t\t\t\t&& (\n\t\t\t\t\t\t\t\t( class_part_ == Method\n\t\t\t\t\t\t\t\t && cfuncname_ != classname_\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t|| class_part_ == AtMethod\n\t\t\t\t\t\t\t\t|| class_part_ == MethodDeclaration\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t\t\t\t && ( ! (\n\t\t\t\t\t\t\t methodparams_.abstr\n\t\t\t\t\t\t\t && !runMode_.remove_first_arg_in_abstract_methods\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t )\n\t\t {\n\t\t\tif(paramlist_.empty())\n\t\t\t{\n\t\t\t addBlock = false;\n\t\t\t paramlist_.push_back(string(\"this\"));\n\t\t\t}\n\t\t\telse if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n\t\t\t paramlist_.clear();\n\t\t }\n\n\t\t if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t postprocess_unused_params(s, param_list_);\n\t\t \/\/ add an empty docu block for parameter \\a s\n\t\t if(param_list_.find(s) == param_list_.end())\n\t\t {\n\t\t\t param_list_[s] = DocuBlock();\n\t\t }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t paramlist_.push_back(s);\n\t\t }\n\t }\n\t)**;\n\n \n matrix_or_cell := (\n\t '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n\t |\n\t '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n\t );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n\t( (WSOC | EOL )+\n\t | ','\n\t # matlab identifier (return value)\n\t | ( (IDENT | '~') > st_tok\n\t\t %{\n\t\t\tassert(p >= tmp_p);\n\t\t\tstring s(tmp_p, p - tmp_p);\n\t\t\tpostprocess_unused_params(s, return_list_);\n\t\t\treturnlist_.push_back(s);\n\t\t\t\/\/ add an empty docu block for return value \\a s\n\t\t\tif(return_list_.find(s) == return_list_.end())\n\t\t\t{\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t}\n\t\t }\n\t\t)\n\t)**;\n\n # return parameter or return parameter list\n lparams =\n\t(\n\t (\n\t\t(\n\t\t # matlab identifier\n\t\t ( IDENT | '~' )\n\t\t >st_tok\n\t\t %{\n\t\t\t assert(p >= tmp_p);\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t postprocess_unused_params(s, return_list_);\n\t\t\t returnlist_.push_back(s);\n\t\t\t \/\/ add an empty docu block for single return value \\a s\n\n\t\t\t if(return_list_.find(s) == return_list_.end())\n\t\t\t {\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n\t\t }\n\t\t)\n\t\t| ( '['\n\t\t . lparamlist\n\t\t . ']'\n\t\t )\n\t )\n\t . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n\t :> '=' . WSOC*\n\t);\n\t# }}}2\n\n # a line in the function body {{{2\n funcline := |*\n\t# empty line\n\t([ \\t]+)\n\t => { fout_.write(ts, te-ts); };\n\n\t# line continuation\n\t('...' . [ \\t]* . EOL)\n\t => { fout_.write(ts, te-ts); };\n\n\t# two single quote in a row need to be changed to nothing\n\t('\\'\\'');\n\n\t# a string should not be parsed for comment blocks, so we handle it separately.\n\t('\\'' . [^'\\n]+ . '\\'')\n\t => {\n\t\t \/\/ change double quotes to quotes and vice versa...\n\t\t fout_ << \"\\\" \";\n\t\t string s(ts+1, te-ts-2);\n\t\t std::replace(s.begin(), s.end(), '\\\"', '\\'');\n\t\t fout_ << s;\n\t\t fout_ << \" \\\"\";\n\t\t };\n\n\t# ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n\t(comment_block)\n\t => {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\t fout_.write(tmp_p, p - tmp_p-1);\n\t\t else\n\t\t\t fout_.write(tmp_p, p - tmp_p);\n\t\t extra_hold_in_cblock = true;\n\t\t fcall in_comment_block;\n\t\t };\n\n\t (IDENT %{tmp_string.assign(ts,p-ts);})\n\t . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n\t {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n\t varargin_parser_candidate_ = tmp_string;\n\t };\n\n\t ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\t \n\t ((IDENT %{tmp_string.assign(ts, p - ts);})\n\t\t . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n\t\t . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\n\n\t('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL ) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t# automatically add return value fields to retval_list_\n\t(\n\t # matlab identifier (which can be a return value and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n\t # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n\t . [ \\t]* . '=' . (^'=')\n\t)\n\t=> {\n\t fhold;\n\t \/\/ store fieldname\n\t assert(tmp_p2 >= tmp_p);\n\t string s(tmp_p, tmp_p2 - tmp_p);\n\t fout_ << tmp_string << \".\" << s << \"=\";\n\t \/\/ typedef of iterators\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a return value\n\t iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n\t if(it != returnlist_.end())\n\t {\n\t\t\/\/ if it is a return value...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ retval list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ if it is missing, add an empty docu block\n\t\tif(missing)\n\t\t{\n\t\t retval_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# automatically add parameter fields to required_list_\n\t(\n\t # matlab identifier (which can be a parameter and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT\n\t\t >(st_tok)\n\t )\n\t)\n\t=> {\n\t \/\/ store fieldname\n\t assert(p >= tmp_p);\n\t string s(tmp_p, p - tmp_p+1);\n\t fout_ << tmp_string << \".\" << s;\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a parameter\n\t iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n\t if(it != paramlist_.end())\n\t {\n\t\t\/\/ if it is a parameter ...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ return, optional and the required list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t \/\/ found match in retval list\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator moit = optional_list_.find(tmp_string);\n\t\tif(moit != optional_list_.end())\n\t\t{\n\t\t \/\/ found match in optional list\n\t\t list_iterator lit = (*moit).second.find(s);\n\t\t if(lit != (*moit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator roit = required_list_.find(tmp_string);\n\t\tif(roit != required_list_.end())\n\t\t{\n\t\t \/\/ found match in required list\n\t\t list_iterator lit = (*roit).second.find(s);\n\t\t if(lit != (*roit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ in case it IS missing, add an empty field to the required block.\n\t\tif(missing)\n\t\t{\n\t\t required_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# add a @deprecated command to function declaration if disp_deprecated is\n\t# used in function body\n\t('disp_deprecated' . [ \\t]*\n\t . (\n\t\t ';'\n\t\t\t@{tmp_string.assign(\"\");}\n\t\t |\n\t\t '(' . [\\t ]* . \"'\"\n\t\t . ([^\\n']*\n\t\t\t >(st_tok)\n\t\t\t %(string_tok)\n\t\t\t)\n\t\t . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n\t\t)\n\t . [\\t ]* . EOL\n\t)\n\t => {\n\t\tstring s;\n\t\tif(tmp_string.empty())\n\t\t{\n\t\t s.assign(\"@deprecated function deprecated\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n\t\t}\n\t\tdocuextra_.push_back(s);\n\t\tfhold;\n\t };\n\n\t# simple matlab identifier\n\t(IDENT)\n\t => { fout_.write(ts, te-ts); };\n\n\t# translate curly brackets in edgy brackets, because otherwise the doxygen\n\t# parser breaks.\n\t('{')\n\t => { fout_ << '['; };\n\n\t('}')\n\t => { fout_ << ']'; };\n\t\n\t('\\'')\n\t => { fout_ << \"^t\"; };\n\n\t# simply output all other characters\n\t(default - [\\r\\n{}\\'])\n\t => { fout_ << fc; };\n\n\t# after EOL try to check for new function\n\tEOL\n\t => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n\t # things that got replaced in function body {{{4\n\t ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n\t\t=> {\n\t\t new_syntax_ = true;\n\t\t fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n\t\t};\n\n\t ([ \\t]* . '%@@remove' . ((default - '%') | ('%' . (default - '@')) | ('%' . '@' . (default -'@')))* . '%@@endremove');\n\n\t # a comment block\n\t ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n\t\t=> {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\tfout_.write(tmp_p, p - tmp_p - 1);\n\t\t else\n\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t fcall in_comment_block;\n\t\t};\n\n\t # empty line\n\t ([ \\t]* . EOL)\n\t\t=> { fout_ << '\\n'; };\n\n\t #}}}4\n\n\t # line not beginning with words 'function' or 'end'\n\t ([ \\t]*\n\t . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n\t )\n\t\t=> {\n\t\t p = ts-1;\n\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n\t\t fgoto funcline;\n\t\t};\n\n\t # things that could end the function body {{{4\n\t # line only containing word 'end'\n\t # the keyword needs to be in the same indentation level as beginning function\n\t ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n\t\t => {\n\t\t\t if(is_class_ && class_part_ == Method)\n\t\t\t {\n\t\t\t\ttmp_string.assign(ts,p-ts+1);\n\n\t\t\t\tif(tmp_string.find(\"e\") == funcindent_)\n\t\t\t\t{\n\t\t\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n\t\t\t\t fgoto methods;\n\t\t\t\t}\n\t\t\t }\n\t\t\t \/\/ else\n\t\t\t p=ts-1;\n\t\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n\t\t\t fgoto funcline;\n\t\t };\n\n\t # line beginning with word 'function'\n\t ([ \\t]*. 'function ')\n\t {\n\t\ttmp_string.assign(ts,p-ts+1);\n\t\tp = ts-1;\n\n\t\tif (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n\t\t{\n\t\t \/\/ end the previous function if existent\n\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n\t\t fgoto main;\n\t\t}\n\t\telse\n\t\t{\n\t\t fgoto funcline;\n\t\t}\n\t };\n\n\t (EOF) $eof(end_of_file);\n\n\t # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n\t. \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n\t. ( default - [\\r\\n] )* . EOL\n )\n\t=> {\n\t assert(tmp_p2 >= tmp_p3);\n\t tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n\t \/\/ std::fout_ << tmp_string << '\\n';\n\t assert(p >= tmp_p);\n\t (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n\t};\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n\t# at least one word (non white-space characters and no double-colon)\n\t. ( default - [ \\r\\t:\\n] )+ .\n\t# followed by something that is a white-space or a new-line, i.e *no*\n\t# double-colon\n\t(\n\t EOL\n\t |\n\t [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - [\\r\\n])* . EOL)\n\t # [ \\t] . (default - '\\n')* . EOL\n\t)\n )\n\t=> {\n\t assert(p+1 >= tmp_p);\n\t string s(tmp_p, p - tmp_p + 1);\n\t (*clist_)[tmp_string].push_back(s);\n\t \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n\t};\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n\t=> { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n\t=> {\n\t p =ts-1;\n\t \/\/ fout_ << \"*\/\\n\";\n\t fret;\n\t};\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n\t# special lists {{{4\n\n\t# begin required_list\n\t( doc_begin . [ \\t]*\n\t . \/required fields of \/i\n\t . (IDENT >(st_tok) %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL\n\t)\n\t => {\n\t\t\/\/fout_ << tmp_string << '\\n';\n\t\tclist_ = &(required_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/optional fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(optional_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/generated fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(retval_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin parameter list\n\t( doc_begin . [ \\t]*\n\t . \/parameters\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = ¶m_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin return list\n\t( doc_begin . [ \\t]*\n\t . \/return values\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &return_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\t#}}}4\n\n\t# default substitutions {{{4\n\n\t# empty line\n\t( doc_begin . [ \\t]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n \";*\/\n\t\tdocubody_.push_back(\"\\n\");\n\t\tdocline = false;\n\t };\n\n\t# paragraph line with second % in text (matlab comment in comment)\n\t( [ \\t]* . '%' . [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docubody_.push_back(\"%\");\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line\n\t( [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line with \"see also\" substituted by \"@sa\"\n\t( \/see also\/i . ':'? )\n\t => {\n\t\tstring s;\n\t\tassert(ts > tmp_p);\n\t\ts.assign(tmp_p+1, ts - tmp_p-1);\n\t\tdocubody_.push_back(s+\"@sa\");\n\t\ttmp_p = p;\n\t };\n\n\t# verbatim or code switches\n\t( [\\\\@] .\n\t\t(\/verbatim\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@verbatim\");\n\t\t}\n\t\t|\n\t\t\/code\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@code\");\n\t\t}\n\t\t));\n\t( [\\\\@] .\n\t\t(\/endverbatim\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endverbatim\");\n\t\t}\n\t\t|\n\t\t\/endcode\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endcode\");\n\t\t}\n\t\t) );\n\n\t# lines that could end doxyblock {{{6\n\t# words\n\t# RAGEL comment: ( default - [ \\t:%'`\\n] )+\n\t( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n\t# non-words\/non-whitespace\n\t# RAGEL comment: ([:'`]) => {\n\t(':') @(end_doxy_block) ;\n\n\t# whitespace only\n\t( [ \\t] );\n\n\t# titled paragraph\n\t( ':' . EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t assert(ts > tmp_p);\n\t\t docubody_.push_back((!is_voc ? \"@par \":\"\") + string(tmp_p+1, ts - tmp_p-1)+(is_voc ? \":\":\"\")+\"\\n\");\n\t\t docline = false;\n\t\t }\n\t };\n\t# }}}6\n\t# }}}4\n\n\t# end of line {{{4\n\t( EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t\tint offset = ( latex_begin ? 0 : 1 );\n\t\t\tassert(p >= tmp_p + offset);\n\t\t\tdocubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n\t\t\tdocline = false;\n\t\t }\n\t\t};\n\t # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n\tgarbage = ( (default - [\\r\\n] )* -- '...' );\n\n\t( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n\t( doc_begin . (garbage . '...')* . garbage . EOL )\n\t => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n\t# read in one comment line\n\t( doc_begin . [\\t ]*\n\t . (default - [\\r\\n\\t ]) . (default - [\\r\\n])* . EOL\n\t)\n\t => {\n\t\t\/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n\t\tassert(p >= tmp_p);\n\t\tdocuheader_.push_back(string(tmp_p, p - tmp_p+1));\n\t };\n\n\t# empty line\n\t( doc_begin . [\\t ]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n\t\tfgoto doxy_get_body;\n\t };\n\n\t# end of comment block;\n\t( [\\t ]* . [^%] )\n\t => {\n\t\tp=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n\t\t\/\/fout_ << \"*\/\\n\";\n\t\tif(is_class_)\n\t\t{\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n\t\t if(class_part_ == Header)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n\t\t\tend_of_class_doc();\n\t\t\tfgoto classbody;\n\t\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n\t\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t\t return 1;\n\t\t\tprint_function_synopsis();\n\t\t\tfgoto funcbody;\n\t\t }\n\t\t else if(class_part_ == MethodDeclaration)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n\t\t\tfgoto funcdef;\n\t\t }\n\t\t else if(class_part_ == Property || class_part_ == Event)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n\t\t\tfgoto propertybody;\n\t\t }\n\t\t else if(class_part_ == InClassComment)\n\t\t {\n\t\t\tclass_part_ = Method;\n\t\t\tfgoto methods;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n\t'%' . [ \\t]* .\n\t (\n\t\t('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n\t )\n\t $!{\n#ifdef DEBUG\n\t\tdebug_output(\"doxy_get_brief\",p);\n#endif\n\t\tp = tmp_p - 2;\n\t\tfgoto doxy_get_brief;\n\t }\n ); #}}}2\n\n # access specifier expressions\n spec_public = ( 'public'i | \"'public'\"i );\n spec_protected = ( 'protected'i | \"'protected'\"i );\n spec_private = ( 'private'i | \"'private'\"i );\n \n spec_class_single = \n\t (\n\t ('?' . (IDENT_W_DOT**) >st_tok )\n\t %{\n\t\t\ttmp_string.assign(tmp_p, p - tmp_p);\n\t\t\t\/\/cerr << \"Detected \" << access_.state << \" modifier by class \" << tmp_string << \"\\n\";\n\t\t\taccess_.classMemberAccess.push_back(make_pair(access_.state, tmp_string));\n\t\t}\n\t ) . WS*;\n \n spec_class_multi = '{' . WS* . spec_class_single . ( [,; ] . WS* . spec_class_single )* . '}';\n \n spec_classes = ( spec_class_single | spec_class_multi );\n\t\n # helper for setting the access specifier {{{2\n paramaccess =\n\t( ('SetAccess' @{ access_.state = SetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public \n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'GetAccess' @{ access_.state = GetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'Access' @{ access_.state = Access; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = Protected; access_.get = Protected; access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = Private; access_.get = Private; access_.set = Private;\n\t\t\t } )\n\t\t )\n\t )\n\t); #}}}2\n\n eventparam =\n\t( ('ListenAccess' @{ access_.state = ListenAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'NotifyAccess' @{ access_.state = NotifyAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t );\n\n # method and property params {{{2\n methodparam =\n (\n\t( paramaccess )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.abstr = true;\n\t\t } )\n\t| ( ( 'Static' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.statical = true;\n\t\t } )\n\t| ( ('Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.hidden = true;\n\t\t } )\n\t| ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.sealed = true;\n\t\t } )\n\t| ( ( 'Test' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.test = true;\n\t\t } )\n\t| ( ( 'TestMethodSetup' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodSetup = true;\n\t\t } )\n\t| ( ( 'TestMethodTeardown' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodTeardown = true;\n\t\t } )\n );\n\n propertyparam =\n (\n\t( paramaccess )\n\t| ( ( 'Constant' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.constant = true;\n\t\t } )\n\t| ( ( 'Transient' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.transient = true;\n\t\t } )\n\t| ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.dependent = true;\n\t\t } )\n\t| ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t| ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.setObservable = true;\n\t\t } )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abstr = true;\n\t\t } )\n\t| ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abortSet = true;\n\t\t } )\n );\n\n methodparams =\n (\n\t'(' . WSOC*\n\t. methodparam\n\t. ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n eventparams =\n (\n\t'(' . WSOC*\n\t. eventparam\n\t. ( WSOC* . ',' . WSOC* . eventparam )* . WSOC* . ')'\n ); #}}}2\n\n propertyparams =\n (\n\t'(' . WSOC*\n\t. propertyparam\n\t. ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n\t(empty_line) => {\n\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t {\n\t\tend_method();\n\t\tfout_ << \"\\n\";\n\t }\n\t};\n\n\t# default: method definition\n\t([ \\t]* . 'function' )\n\t => {\n\t\ttmp_string.assign(ts, te - ts+1);\n\t\tfuncindent_ = tmp_string.find_first_not_of(\" \\t\");\n\t\tfout_ << string(ts, ts+funcindent_);\n\t\t#if DEBUG\n\t\t\t{\n\t\t\t ostringstream oss;\n\t\t\t oss << \"in methods: funcindent: \" << funcindent_;\n\t\t\t debug_output(oss.str(), p);\n\t\t\t}\n\t\t#endif\n\t\tp=ts+funcindent_-1;\n\t\tfgoto funct;\n\t };\n\n\t# end of methods block\n\t([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n\t => {\n\t\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t\t {\n\t\t\t end_method();\n\t\t\t #if DEBUG\n\t\t\t debug_output(\"in methods: found end keyword, goto classbody\",p);\n\t\t\t #endif\n\t\t }\n\t\t fgoto classbody;\n\t\t };\n\n\t# comment between two methods\n\t([ \\t]* . '%' ) => {\n\t #if DEBUG\n\t\tdebug_output(\"in methods: garble comment line\",p);\n\t #endif\n\n\t p = ts-1;\n\t class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n\t fgoto expect_doxyblock;\n\t};\n\n\t# if we reach this: method declaration without definition is found\n\t([ \\t]* . [^% \\t\\n]) =>\n\t{\n\t #if DEBUG\n\t\tdebug_output(\"in methods: found method declaration, going to funcdef\",p);\n\t #endif\n\t class_part_ = MethodDeclaration;\n\t p = ts-1;\n\t fgoto funcdef;\n\t};\n\n\t *|;\n\n\n methodsheader := (\n\t[ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n\t\t @{\n\t\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t\tfgoto methods;\n\t\t }\n\t\t );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_property_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\")\n\t\t\t\tfgoto classbody;\n\t\t\t if (propertyparams_.dependent)\n\t\t\t\tspecifier_[s].dependent = true;\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t )\n\t\t. WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n\t\t\t|\n\t\t\t( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n\t\t\t@{\n\t\t\t defaultprop_ = string(tmp_p2, p - tmp_p2);\n\t\t\t string::size_type last_elem = defaultprop_.length() -1;\n\t\t\t if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n\t\t\t {\n\t\t\t\tdefaultprop_[0] = '\\\"';\n\t\t\t\tdefaultprop_[last_elem] = '\\\"';\n\t\t\t }\n\t\t\t string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n\t\t\t string::size_type last_paren;\n\t\t\t if (first_paren == string::npos)\n\t\t\t {\n\t\t\t\tfirst_paren = 1;\n\t\t\t\tlast_paren = last_elem;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tlast_paren = defaultprop_.find_last_of(\")]}\");\n\t\t\t\tif (last_paren == string::npos)\n\t\t\t\t last_paren=last_elem-1;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n\t\t\t\t {\n\t\t\t\t\tfirst_paren++;\n\t\t\t\t\tlast_paren--;\n\t\t\t\t }\n\t\t\t\t defaultprop_.insert(first_paren, 1,'\"');\n\t\t\t\t defaultprop_.insert(last_paren+2, 1,'\"');\n\t\t\t\t first_paren++;\n\t\t\t\t last_paren++;\n\t\t\t\t}\n\t\t\t }\n\t\t\t for (unsigned int i = first_paren; i < last_paren; ++i)\n\t\t\t {\n\t\t\t\tif(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n\t\t\t\t{\n\t\t\t\t defaultprop_[i] = ' ';\n\t\t\t\t defaultprop_[i+1] = ' ';\n\t\t\t\t defaultprop_[i+2] = ' ';\n\t\t\t\t}\n\/* else if(defaultprop_[i] == '[')\n\t\t\t\t defaultprop_[i] = '{';\n\t\t\t\telse if(defaultprop_[i] == ']')\n\t\t\t\t defaultprop_[i] = '}'; *\/\n\t\t\t\telse if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n\t\t\t\t defaultprop_[i] = ',';\n\t\t\t\telse if(defaultprop_[i] == '\\\"')\n\t\t\t\t defaultprop_[i] = '\\'';\n\t\t\t\telse if(defaultprop_[i] == '@')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t\telse if(defaultprop_[i] == '\\n')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t }\n\t\t\t }\n\t\t )\n\t );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n properties := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. propertybody* )\n\t );\n\n #property body {{{4\n eventbody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n events := ((\n\tWSOC* . eventparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. eventbody* )\n\t );\n\n enum = ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_enum_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\") {\n\t\t\t\tfout_ << \"\\n} \" << classname_ << \"Enum;\\n\";\n\t\t\t\tfgoto classbody;\n\t\t\t }\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t . WS* . ( '%' @{ fhold; } | ';' | ',' | EOL )\n\t\t );\n\n enumerationbody = (\n\t(enum)\n\t|\n\t( (empty_line) @{ end_of_enum_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n enumeration := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\tfout_ << \"typedef enum {\\n\";\n\t\t}\n\t. enumerationbody* )\n\t );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n\t# a comment block\n\t(comment_block)\n\t => {\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p - 1);\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p);\n\t\tfcall in_comment_block;\n\t };\n\n\t(WSOC); # => { fout_.write(ts, te-ts); };\n\n\t(EOL) => { fout_ << \"\\n\"; };\n\n\t('end' . [ \\t]* ';'?) => {\n\t std::map::iterator specIt;\n\t for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n\t {\n\t\tfout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n\t\tif ( (*specIt).second.dependent)\n\t\t{\n\t\t if( (*specIt).second.getter && ! (*specIt).second.setter )\n\t\t {\n\t\t\tfout_ << \"@note [readonly]\\n *\";\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t fout_ << \"@note This property has custom functionality when its value is \";\n\t\t if ((*specIt).second.getter)\n\t\t {\n\t\t\tfout_ << \"retrieved\";\n\t\t\tif ((*specIt).second.setter)\n\t\t\t fout_ << \" or changed\";\n\t\t }\n\t\t else if ((*specIt).second.setter)\n\t\t\tfout_ << \"changed\";\n\t\t fout_ << \".\";\n\t\t}\n\t\tfout_ << \"\\n *\/\\n\";\n\t }\n\t fout_ << \"\\n};\\n\";\n\t for( list::iterator it = namespaces_.begin();\n\t\t\tit != namespaces_.end(); ++it)\n\t {\n\t\tfout_ << \"}\\n\";\n\t }\n\t};\n\n\t([ \\t]* . 'properties')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Property;\n\t\tfgoto properties;\n\t };\n\t([ \\t]* . 'methods')\n\t => {\n\t\tmethodparams_ = MethodParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Method;\n\t\tfgoto methodsheader;\n\t };\n\t([ \\t]* . 'events')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\tpropertyparams_.event = true;\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Event;\n\t\tfgoto events;\n\t };\n\t([ \\t]* . 'enumeration')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Enumeration;\n\t\tfgoto enumeration;\n\t };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n\tdoc_begin\n\t @{\n\t\t\/\/fout_ << \"\/*\";\n\t\tp--;\n\t\tfgoto doxyheader;\n\t }\n )\n $!{\n\tfhold;\n\t{\n\t int i = 0;\n\t for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n\t\t;\n\t std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n\tdebug_output(\"stopping expect_doxyblock\", p);\n#endif\n\tif(is_class_)\n\t{\n\t if(class_part_ == Header)\n\t {\n\t\tend_of_class_doc();\n\t\tfgoto classbody;\n\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t {\n\t\tstring endstringtest;\n\t\tendstringtest.assign(p, 100);\n\t\tstring::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tif (endstringtest.substr(first_char, 3) == \"end\")\n\t\t{\n\t\t p += first_char+4;\n\t\t print_function_synopsis();\n\t\t end_function();\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t print_function_synopsis();\n\t\t fout_ << whitespaces;\n\t\t fgoto funcbody;\n\t\t}\n\t }\n\t else if(class_part_ == Property || class_part_ == Event)\n\t {\n\t\tfgoto propertybody;\n\t }\n\t else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n\t {\n\t\tclass_part_ = Method;\n\t\tfgoto methods;\n\t }\n\t else{\n\t\tcerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n\t }\n\t}\n\telse\n\t{\n\t if(runMode_.mode == RunMode::ParseParams)\n\t\treturn 1;\n\t print_function_synopsis();\n\t fout_ << whitespaces;\n\t fgoto funcbody;\n\t}\n\t}\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n\t (WSOC)* .\n\t # return values (if found opt = true)\n\t (lparams)? .\n\t # matlab identifier (function name stored in cfuncname_)\n\t ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n\t\tIDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tcfuncname_.assign(tmp_p, p - tmp_p);\n\t\t\t#ifdef DEBUG\n\t\t\t cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n\t\t\t#endif\n\t\t\t\/\/ in ParseMethodParams mode, we only check for the method\n\t\t\t\/\/ parameters of a specific method.\n\t\t\tif(is_class_ && class_part_ == MethodDeclaration\n\t\t\t && runMode_.mode == RunMode::ParseMethodParams)\n\t\t\t{\n\t\t\t if(runMode_.methodname == cfuncname_)\n\t\t\t {\n\t\t\t\treturn 0;\n\t\t\t }\n\t\t\t}\n\t\t\tif(runMode_.mode == RunMode::Normal\n\t\t\t && is_class_ && class_part_ == AtMethod)\n\t\t\t{\n\t\t\t update_method_params(cfuncname_);\n\t\t\t}\n\t\t\tis_script_ = false;\n\t\t }\n\t )\n\t . WSOC*\n\t . (\n\t\t '('\n\t\t # parameter list\n\t\t . ( paramlist\n\t\t\t %{\n\t\t\t\t if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n\t\t\t\t { paramlist_.clear(); }\n\t\t\t }\n\t\t\t )\n\t\t . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )*\n\t\t . EOL\n\t\t @{\n\t\t\t if(comment_found)\n\t\t\t {\n\t\t\t\ttmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\ttmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\ttmp_string = \"\";\n\t\t\t }\n\t\t\t comment_found = false;\n\t\t\t if(is_class_ && class_part_ == MethodDeclaration )\n\t\t\t {\n\t\t\t class_part_ = Method;\n\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n\t\t\t #endif\n\t\t\t fgoto methods;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t \/\/ fout_ << tmp_string << \"{\\n\";\n\t\t\t \/\/ check for documentation block\n\t\t\t fgoto expect_doxyblock;\n\t\t\t }\n\t\t }\n\t\t# no parameter list && first function => ( script || method )\n\t\t| (( [ \\t]\n\t\t\t |\n\t\t\t ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n\t\t\t@{\n\t\t\t\t if(comment_found)\n\t\t\t\t {\n\t\t\t\t tmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\t tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t tmp_string = \"\";\n\t\t\t\t }\n\t\t\t\t comment_found = false;\n\t\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n\t\t\t\t #endif\n\t\t\t\t if(is_class_ && class_part_ == MethodDeclaration)\n\t\t\t\t {\n\t\t\t\t\tclass_part_ = Method;\n\t\t\t\t\tfgoto methods;\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t fgoto expect_doxyblock;\n\t\t\t\t }\n\t\t\t }\n\t\t)\n\t );\n\n funct :=\n (\n\t(\n\t comment_block @in_c_block\n\t | [ \\t]*. EOL\n\t)*\n\t. ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n\t@{\n\t string :: size_type found = filename_.rfind(\"\/\");\n\t if(found == string :: npos)\n\t\t found = -1;\n\t string funcname = filename_.substr(found+1, filename_.size()-3-found);\n\t cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n\t if(!is_first_function_)\n\t\t fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\t fout_ << funcname << \"() {\\n\";*\/\n\t is_script_ = true;\n\t fhold;\n\t fgoto expect_doxyblock;\n\t }; #}}}2\n\n # class definitions {{{2\n classparams =\n\t '(' . [^)]* . ')';\n\n superclass =\n\t( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n\t\t\t\t\t @{ if(*p == '.')\n\t\t\t\t\t\t fout_ << \"::\";\n\t\t\t\t\t\t else fout_ << *p; } );\n\n superclasses = (\n\t '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n\t\t . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n\t 'classdef' . WSOC* . ('(' . WSOC*\n\t\t. (( 'Sealed'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n\t\t }\n\t\t )\n\n\t\t |( 'Hidden'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Hidden' and is invisible.\"));\n\t\t }\n\t\t )\n\t\t |( 'Abstract'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Abstract' and needs to be inherited in order to be instantiable.\"));\n\t\t }\n\t\t )) . [^)]* . ')')? . WSOC* .\n\t # matlab identifier (class name stored in classname_)\n\t ( IDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tclassname_.assign(tmp_p, p - tmp_p);\n\t\t\tis_class_ = true;\n\t\t\tfout_ << \"class \" << classname_;\n\t\t }\n\t )\n\t . WSOC*\n\t . classparams?\n\t . WSOC*\n\t . superclasses?\n\t . [ \\t;]*\n\t . ( '%'. garble_comment_line_wo_eol )?\n\t EOL\n\t @{\n\t\tfout_ << \" {\\n\";\n\t\tfgoto expect_doxyblock;\n\t } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n\t# either we find a function or classdef definition with a possibly\n\t# preceding comment block or we have a script\n\t( any\n\t @{\n\t\t fhold;\n\t\t tmp_p = p;\n\t\t}\n\t .\n\t(\n\t [ \\t]*. '%' . (any - '\\n')* . EOL\n\t | [ \\t]*. EOL\n\t)*\n\t. [\\t]*\n\t. ( 'function' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t char *tp;\n\t\t\t\t\t for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n\t\t\t\t\t ;\n\t\t\t\t\t funcindent_ = (int)(p - tp);\n#if DEBUG\n\t\t\t\t\t {\n\t\t\t\t\t ostringstream oss;\n\t\t\t\t\t oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n\t\t\t\t\t debug_output(oss.str(), p);\n\t\t\t\t\t }\n#endif\n\t\t\t\t\t if(is_class_ && class_part_ == Header)\n\t\t\t\t\t class_part_ = AtMethod;\n\t\t\t\t\t fgoto funct;\n\t\t\t\t\t}\n\t | 'classdef' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t fgoto classdef;\n\t\t\t\t\t}\n\t ) )\n $!{\n#ifdef DEBUG\n\tdebug_output(\"goto script\",p);\n#endif\n\tp=tmp_p;\n\tfgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n\tchar *p = buf + have;\n\tchar *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n\tstring tmp_string, tmp_string2, tmp_string3;\n\tbool docline = false;\n\tbool latex_begin = true;\n\tbool comment_found = false;\n\tint space = BUFSIZE - have;\n\n\tif ( space == 0 )\n\t{\n\t \/* We filled up the buffer trying to scan a token. *\/\n\t cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n\t exit(-1);\n\t}\n\n\tfin_.read( p, space );\n\tint len = fin_.gcount();\n\tchar *pe = p + len;\n\tchar *rpe = pe;\n\tchar *eof = 0;\n\n\t\/* If we see eof then append the EOF char. *\/\n\tif ( fin_.eof() )\n\t{\n\t char eof_c = *pe;\n\t *pe = '\\n';\n\t pe++;\n\t *pe = eof_c;\n\t eof = pe;\n\t rpe = pe;\n\n\t done = true;\n\t}\n\telse\n\t{\n\t \/* Find the last newline by searching backwards. This is where\n\t * we will stop processing on this iteration. *\/\n\t while ( pe >= p )\n\t {\n\t\tif( *pe != '\\n')\n\t\t pe--;\n\t\telse\n\t\t{\n\t\t if(pe >= p+3\n\t\t\t && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n\t\t\tpe-=3;\n\t\t else\n\t\t\tbreak;\n\t\t}\n\t }\n\t}\n\n\t%% write exec;\n\n\t\/* Check if we failed. *\/\n\tif ( cs == MFileScanner_error )\n\t{\n\t \/* Machine failed before finding a token. *\/\n\t cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n\t debug_output(\"Grrrr!!!!\", p);\n\t exit(-1);\n\t}\n\n\t\/* Now set up the prefix. *\/\n\tif ( ts == 0 )\n\t{\n\t have = rpe - pe;\n\t \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n\t memmove( buf, pe, have );\n\t}\n\telse\n\t{\n\t have = rpe - ts;\n\t \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n\t memmove( buf, ts, have );\n\t}\n\n\tif ( ts != 0 )\n\t{\n\t te -= (ts-buf);\n\t ts = buf;\n\t}\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","old_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') %{ ++line; };\n\n # scanner for comment blocks\n in_comment_block :=\n (\n ([ \\t]* >{ tmp_p = p; } .\n # comment line begins with a percent sign\n '%')\n\t @{ fout_ << \"\\n\";\n\t\tfout_.write(tmp_p, p - tmp_p);\n\t\ttmp_p = p+1; fout_ << \" *\";\n\t }\n # and then some default characters\n . ( ( (default - [\\r\\n])* )\n\t %{ fout_.write(tmp_p, p - tmp_p); } )\n\t . EOL\n )*\n $!{\n\tfout_ << \" *\/\\n\";\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\\n\";\n\/\/ }\n\tfhold;\n\twhile (*p == ' ')\n\t fhold;\n\tif (extra_hold_in_cblock)\n\t{\n\t fhold;\n\t --line;\n\t extra_hold_in_cblock = false;\n\t}\n\tfret;\n };\n\n action end_doxy_block\n {\n\tif(!docline)\n\t{\n\t p = ts-1;\n\t \/* go backward until first non-whitespace is found *\/\n\t for(p=p-1; *p==' ' || *p == '\\t'; --p)\n\t\t;\n\n\t if(is_class_)\n\t {\n\t\tif(class_part_ == Header)\n\t\t{\n\t\t end_of_class_doc();\n\t\t fgoto classbody;\n\t\t} else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t\telse if(class_part_ == MethodDeclaration)\n\t\t{\n\t\t fgoto funcdef;\n\t\t}\n\t\telse if(class_part_ == Property || class_part_ == Event)\n\t\t{\n\t\t fgoto propertybody;\n\t\t}\n\t\telse if(class_part_ == Enumeration)\n\t\t{\n\t\t fgoto enumerationbody;\n\t\t}\n\t\telse if(class_part_ == InClassComment)\n\t\t{\n\t\t class_part_ = Method;\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n\t\t}\n\t }\n\t else\n\t {\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tprint_function_synopsis();\n\t\tfgoto funcbody;\n\t }\n\t}\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n\tend_function();\n\tfor( list::iterator it = namespaces_.begin();\n\t\t it != namespaces_.end(); ++it)\n\t{\n\t fout_ << \"};\\n\";\n\t}\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n\tassert(p >= tmp_p-1);\n\tif (*p == '\\r')\n\t fout_.write(tmp_p, p-tmp_p);\n\telse\n\t fout_.write(tmp_p, p-tmp_p+1);\n\tfcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action st_tok2 { tmp_p2 = p; }\n\n action echo_tok {\n\tassert (p >= tmp_p);\n\tfout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n\tassert ( p >= tmp_p );\n\ttmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n\t(\n\t# RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n\t# comment\n\t '|' @{ \n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"*\/\";\n\/\/ }\n\t\t\tfout_ << \"\/**\"; tmp_p = p+1;\n\t\t }\n\t . (default - [\\r\\n])*\n\t . ( EOL . [ \\t]*\n\t . '%' @{\n\t\t\t\tassert(p >= tmp_p -1);\n\t\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t\t\tfout_ << \" * \";\n\t\t\t\ttmp_p = p+1;\n\t\t\t }\n\t . (default - [\\r\\n])* )* . EOL\n\t |\n\t# RAGEL comment: else: a regular comment\n\t ( (default - '|')\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\t if (string(p, 8) != string(\"@@remove\"))\n\t\t fout_ << \"\/* \";\n\t\t tmp_p = p;\n\t\t } )\n\t . (default - [\\r\\n])* . EOL\n\t);\n\n # comment block in function body\n comment_block = (( [ \\t]* >(st_tok) . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin pattern: if found, automatically set the character pointer to the current position (plus one)\n doc_begin = [\\t ]* . '%' @{\n\tif (!docline) {\n\t\ttmp_p = p + 1;\n\t}\n };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n\t( (default - [\\r\\n])* . EOL )\n\t @{\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#endif\\n\";\n\/\/ }\n\t\tfout_ << \"\/* \";\n\t\tassert( p >= tmp_p );\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p -2) << \"*\/\\n\";\n\n\/\/ if(is_getter_ || is_setter_)\n\/\/ {\n\/\/ fout_ << \"\\n#if 0\\n\";\n\/\/ }\n\t };\n garble_comment_line_wo_eol =\n\t(default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n\t( ([ \\t]+ \n\t @{\n\t\t {\n\t\t\tint i=0;\n\t\t\tif (*(p+1) != ' ' && *(p+1) != '\\t')\n\t\t\t{\n\t\t\t while (*(p-i) == ' ' || *(p-i) == '\\t')\n\t\t\t\ti++;\n\t\t\t if (*(p-i) == '\\n')\n\t\t\t\tfout_ << std::string(i, ' ');\n\t\t\t}\n\t\t }\n\t\t})\n\t | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n\t | ('...'.[ \\t]*.EOL)\n\t);\n\n # white space or line continuation\n WS =\n\t( [ \\t]+\n\t | ('...'.[\\t]*.EOL)\n\t);\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = ([^,)\\n] | EOL)** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n\t(\n\t (WSOC | ',' | EOL\n\t | ( '=' . default_arg ) )+\n\t |\n\t # matlab identifier (parameter)\n\t (IDENT | '~' )\n\t >st_tok\n\t %{\n\t\t assert(p >= tmp_p);\n\t\t string s(tmp_p, p - tmp_p);\n\t\t bool addBlock = true;\n\t\t \/\/ do not print this pointer\n\t\t if( is_class_ && ( !methodparams_.statical\n\t\t\t\t\t\t\t&& (\n\t\t\t\t\t\t\t\t( class_part_ == Method\n\t\t\t\t\t\t\t\t && cfuncname_ != classname_\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t|| class_part_ == AtMethod\n\t\t\t\t\t\t\t\t|| class_part_ == MethodDeclaration\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t\t\t\t && ( ! (\n\t\t\t\t\t\t\t methodparams_.abstr\n\t\t\t\t\t\t\t && !runMode_.remove_first_arg_in_abstract_methods\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t )\n\t\t )\n\t\t {\n\t\t\tif(paramlist_.empty())\n\t\t\t{\n\t\t\t addBlock = false;\n\t\t\t paramlist_.push_back(string(\"this\"));\n\t\t\t}\n\t\t\telse if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n\t\t\t paramlist_.clear();\n\t\t }\n\n\t\t if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t postprocess_unused_params(s, param_list_);\n\t\t \/\/ add an empty docu block for parameter \\a s\n\t\t if(param_list_.find(s) == param_list_.end())\n\t\t {\n\t\t\t param_list_[s] = DocuBlock();\n\t\t }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n\t\t paramlist_.push_back(s);\n\t\t }\n\t }\n\t)**;\n\n \n matrix_or_cell := (\n\t '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n\t |\n\t '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n\t );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n \n \n # return parameter list for functions\n lparamlist =\n\t( (WSOC | EOL )+\n\t | ','\n\t # matlab identifier (return value)\n\t | ( (IDENT | '~') > st_tok\n\t\t %{\n\t\t\tassert(p >= tmp_p);\n\t\t\tstring s(tmp_p, p - tmp_p);\n\t\t\tpostprocess_unused_params(s, return_list_);\n\t\t\treturnlist_.push_back(s);\n\t\t\t\/\/ add an empty docu block for return value \\a s\n\t\t\tif(return_list_.find(s) == return_list_.end())\n\t\t\t{\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t}\n\t\t }\n\t\t)\n\t)**;\n\n # return parameter or return parameter list\n lparams =\n\t(\n\t (\n\t\t(\n\t\t # matlab identifier\n\t\t ( IDENT | '~' )\n\t\t >st_tok\n\t\t %{\n\t\t\t assert(p >= tmp_p);\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t postprocess_unused_params(s, return_list_);\n\t\t\t returnlist_.push_back(s);\n\t\t\t \/\/ add an empty docu block for single return value \\a s\n\n\t\t\t if(return_list_.find(s) == return_list_.end())\n\t\t\t {\n\t\t\t return_list_[s] = DocuBlock();\n\t\t\t }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n\t\t }\n\t\t)\n\t\t| ( '['\n\t\t . lparamlist\n\t\t . ']'\n\t\t )\n\t )\n\t . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n\t :> '=' . WSOC*\n\t);\n\t# }}}2\n\n # a line in the function body {{{2\n funcline := |*\n\t# empty line\n\t([ \\t]+)\n\t => { fout_.write(ts, te-ts); };\n\n\t# line continuation\n\t('...' . [ \\t]* . EOL)\n\t => { fout_.write(ts, te-ts); };\n\n\t# two single quote in a row need to be changed to nothing\n\t('\\'\\'');\n\n\t# a string should not be parsed for comment blocks, so we handle it separately.\n\t('\\'' . [^'\\n]+ . '\\'')\n\t => {\n\t\t \/\/ change double quotes to quotes and vice versa...\n\t\t fout_ << \"\\\" \";\n\t\t string s(ts+1, te-ts-2);\n\t\t std::replace(s.begin(), s.end(), '\\\"', '\\'');\n\t\t fout_ << s;\n\t\t fout_ << \" \\\"\";\n\t\t };\n\n\t# ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n\t(comment_block)\n\t => {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\t fout_.write(tmp_p, p - tmp_p-1);\n\t\t else\n\t\t\t fout_.write(tmp_p, p - tmp_p);\n\t\t extra_hold_in_cblock = true;\n\t\t fcall in_comment_block;\n\t\t };\n\n\t (IDENT %{tmp_string.assign(ts,p-ts);})\n\t . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n\t {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n\t varargin_parser_candidate_ = tmp_string;\n\t };\n\n\t ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\t \n\t ((IDENT %{tmp_string.assign(ts, p - ts);})\n\t\t . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n\t\t . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n\t => {\n\t\t fout_.write(ts, te-ts);\n\t\t if (tmp_string == varargin_parser_candidate_ )\n\t\t {\n\t\t varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n\t\t }\n\t };\n\n\n\t('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n\t . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL ) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\t\n\t((IDENT %{tmp_string.assign(ts, p - ts);})\n\t . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n\t . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n\t . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n\t => {\n\t\tfout_.write(ts, te-ts);\n\t\tif (tmp_string == varargin_parser_candidate_ )\n\t\t{\n\t\t extract_default_argument_of_inputparser(tmp_string3);\n\t\t varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n\t\t}\n\t\tif (*p == '\\n')\n\t\t fgoto funcbody;\n\t };\n\n\n\t# automatically add return value fields to retval_list_\n\t(\n\t # matlab identifier (which can be a return value and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n\t # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n\t . [ \\t]* . '=' . (^'=')\n\t)\n\t=> {\n\t fhold;\n\t \/\/ store fieldname\n\t assert(tmp_p2 >= tmp_p);\n\t string s(tmp_p, tmp_p2 - tmp_p);\n\t fout_ << tmp_string << \".\" << s << \"=\";\n\t \/\/ typedef of iterators\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a return value\n\t iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n\t if(it != returnlist_.end())\n\t {\n\t\t\/\/ if it is a return value...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ retval list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ if it is missing, add an empty docu block\n\t\tif(missing)\n\t\t{\n\t\t retval_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# automatically add parameter fields to required_list_\n\t(\n\t # matlab identifier (which can be a parameter and a structure)\n\t (IDENT\n\t\t%{tmp_string.assign(ts,p-ts);})\n\t . '.'\n\t # matlab identifer (fieldname)\n\t . (IDENT_W_DOT\n\t\t >(st_tok)\n\t )\n\t)\n\t=> {\n\t \/\/ store fieldname\n\t assert(p >= tmp_p);\n\t string s(tmp_p, p - tmp_p+1);\n\t fout_ << tmp_string << \".\" << s;\n\t typedef DocuList :: iterator list_iterator;\n\t typedef DocuListMap :: iterator map_iterator;\n\t typedef DocuBlock :: iterator iterator;\n\n\t \/\/ check wether first IDENT is a parameter\n\t iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n\t if(it != paramlist_.end())\n\t {\n\t\t\/\/ if it is a parameter ...\n\t\t\/\/ ... check wether its found field is still missing a DocuBlock in the\n\t\t\/\/ return, optional and the required list.\n\t\tbool missing = true;\n\t\tmap_iterator rvoit = retval_list_.find(tmp_string);\n\t\tif(rvoit != retval_list_.end())\n\t\t{\n\t\t list_iterator lit = (*rvoit).second.find(s);\n\t\t \/\/ found match in retval list\n\t\t if(lit != (*rvoit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator moit = optional_list_.find(tmp_string);\n\t\tif(moit != optional_list_.end())\n\t\t{\n\t\t \/\/ found match in optional list\n\t\t list_iterator lit = (*moit).second.find(s);\n\t\t if(lit != (*moit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\tmap_iterator roit = required_list_.find(tmp_string);\n\t\tif(roit != required_list_.end())\n\t\t{\n\t\t \/\/ found match in required list\n\t\t list_iterator lit = (*roit).second.find(s);\n\t\t if(lit != (*roit).second.end())\n\t\t\tmissing = false;\n\t\t}\n\t\t\/\/ in case it IS missing, add an empty field to the required block.\n\t\tif(missing)\n\t\t{\n\t\t required_list_[tmp_string][s] = DocuBlock();\n\t\t}\n\t }\n\t};\n\n\t# add a @deprecated command to function declaration if disp_deprecated is\n\t# used in function body\n\t('disp_deprecated' . [ \\t]*\n\t . (\n\t\t ';'\n\t\t\t@{tmp_string.assign(\"\");}\n\t\t |\n\t\t '(' . [\\t ]* . \"'\"\n\t\t . ([^\\n']*\n\t\t\t >(st_tok)\n\t\t\t %(string_tok)\n\t\t\t)\n\t\t . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n\t\t)\n\t . [\\t ]* . EOL\n\t)\n\t => {\n\t\tstring s;\n\t\tif(tmp_string.empty())\n\t\t{\n\t\t s.assign(\"@deprecated function deprecated\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n\t\t}\n\t\tdocuextra_.push_back(s);\n\t\tfhold;\n\t };\n\n\t# simple matlab identifier\n\t(IDENT)\n\t => { fout_.write(ts, te-ts); };\n\n\t# translate curly brackets in edgy brackets, because otherwise the doxygen\n\t# parser breaks.\n\t('{')\n\t => { fout_ << '['; };\n\n\t('}')\n\t => { fout_ << ']'; };\n\t\n\t('\\'')\n\t => { fout_ << \"^t\"; };\n\n\t# simply output all other characters\n\t(default - [\\r\\n{}\\'])\n\t => { fout_ << fc; };\n\n\t# after EOL try to check for new function\n\tEOL\n\t => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n\t # things that got replaced in function body {{{4\n\t ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n\t\t=> {\n\t\t new_syntax_ = true;\n\t\t fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n\t\t};\n\n\t ([ \\t]* . '%@@remove' . ((default - '%') | ('%' . (default - '@')) | ('%' . '@' . (default -'@')))* . '%@@endremove');\n\n\t # a comment block\n\t ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n\t\t=> {\n\t\t assert(p >= tmp_p);\n\t\t if (*(p-1) == '\\r')\n\t\t\tfout_.write(tmp_p, p - tmp_p - 1);\n\t\t else\n\t\t\tfout_.write(tmp_p, p - tmp_p);\n\t\t fcall in_comment_block;\n\t\t};\n\n\t # empty line\n\t ([ \\t]* . EOL)\n\t\t=> { fout_ << '\\n'; };\n\n\t #}}}4\n\n\t # line not beginning with words 'function' or 'end'\n\t ([ \\t]*\n\t . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n\t )\n\t\t=> {\n\t\t p = ts-1;\n\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n\t\t fgoto funcline;\n\t\t};\n\n\t # things that could end the function body {{{4\n\t # line only containing word 'end'\n\t # the keyword needs to be in the same indentation level as beginning function\n\t ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n\t\t => {\n\t\t\t if(is_class_ && class_part_ == Method)\n\t\t\t {\n\t\t\t\ttmp_string.assign(ts,p-ts+1);\n\n\t\t\t\tif(tmp_string.find(\"e\") == funcindent_)\n\t\t\t\t{\n\t\t\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n\t\t\t\t fgoto methods;\n\t\t\t\t}\n\t\t\t }\n\t\t\t \/\/ else\n\t\t\t p=ts-1;\n\t\t\t \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n\t\t\t fgoto funcline;\n\t\t };\n\n\t # line beginning with word 'function'\n\t ([ \\t]*. 'function ')\n\t {\n\t\ttmp_string.assign(ts,p-ts+1);\n\t\tp = ts-1;\n\n\t\tif (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n\t\t{\n\t\t \/\/ end the previous function if existent\n\t\t end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n\t\t fgoto main;\n\t\t}\n\t\telse\n\t\t{\n\t\t fgoto funcline;\n\t\t}\n\t };\n\n\t (EOF) $eof(end_of_file);\n\n\t # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n\t. \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n\t. ( default - [\\r\\n] )* . EOL\n )\n\t=> {\n\t assert(tmp_p2 >= tmp_p3);\n\t tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n\t \/\/ std::fout_ << tmp_string << '\\n';\n\t assert(p >= tmp_p);\n\t (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n\t};\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n\t# at least one word (non white-space characters and no double-colon)\n\t. ( default - [ \\r\\t:\\n] )+ .\n\t# followed by something that is a white-space or a new-line, i.e *no*\n\t# double-colon\n\t(\n\t EOL\n\t |\n\t [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - [\\r\\n])* . EOL)\n\t # [ \\t] . (default - '\\n')* . EOL\n\t)\n )\n\t=> {\n\t assert(p+1 >= tmp_p);\n\t string s(tmp_p, p - tmp_p + 1);\n\t (*clist_)[tmp_string].push_back(s);\n\t \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n\t};\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n\t=> { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n\t=> {\n\t p =ts-1;\n\t \/\/ fout_ << \"*\/\\n\";\n\t fret;\n\t};\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n\t# special lists {{{4\n\n\t# begin required_list\n\t( doc_begin . [ \\t]*\n\t . \/required fields of \/i\n\t . (IDENT >(st_tok) %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL\n\t)\n\t => {\n\t\t\/\/fout_ << tmp_string << '\\n';\n\t\tclist_ = &(required_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/optional fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(optional_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin optional_list\n\t( doc_begin . [ \\t]*\n\t . \/generated fields of \/i\n\t . (IDENT\n\t\t >(st_tok)\n\t\t %(string_tok) )\n\t . [ \\t]* . ':' . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &(retval_list_[tmp_string]);\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin parameter list\n\t( doc_begin . [ \\t]*\n\t . \/parameters\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = ¶m_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\n\t# begin return list\n\t( doc_begin . [ \\t]*\n\t . \/return values\/i . [ \\t]* . ':'\n\t . [ \\t]* . EOL )\n\t => {\n\t\tclist_ = &return_list_;\n\t\tdocline = false;\n\t\tfcall fill_list;\n\t };\n\t#}}}4\n\n\t# default substitutions {{{4\n\n\t# empty line\n\t( doc_begin . [ \\t]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n \";*\/\n\t\tdocubody_.push_back(\"\\n\");\n\t\tdocline = false;\n\t };\n\n\t# paragraph line with second % in text (matlab comment in comment)\n\t( [ \\t]* . '%' . [ \\t]* . '%' )\n\t => {\n\t\tif(!docline)\n\t\t{\n\t\t docubody_.push_back(\"%\");\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line\n\t( [ \\t]* . '%' )\n\t => {\n\t\t\/*\n\t\t ostringstream oss;\n\t\t oss << \"(parline! dl:\" << docline << \")\";\n\t\t docubody_.push_back(oss.str());\n\t\t*\/\n\t\tif(!docline)\n\t\t{\n\t\t docline = true;\n\t\t tmp_p = p;\n\t\t}\n\t };\n\n\t# paragraph line with \"see also\" substituted by \"@sa\"\n\t( \/see also\/i . ':'? )\n\t => {\n\t\tstring s;\n\t\tassert(ts > tmp_p);\n\t\ts.assign(tmp_p+1, ts - tmp_p-1);\n\t\tdocubody_.push_back(s+\"@sa\");\n\t\ttmp_p = p;\n\t };\n\n\t# verbatim or code switches\n\t( [\\\\@] .\n\t\t(\/verbatim\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@verbatim\");\n\t\t}\n\t\t|\n\t\t\/code\/i\n\t\t@{ \n\t\t\tis_voc=true;\n\t\t\t\/\/docubody_.push_back(\"@code\");\n\t\t}\n\t\t));\n\t( [\\\\@] .\n\t\t(\/endverbatim\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endverbatim\");\n\t\t}\n\t\t|\n\t\t\/endcode\/i\n\t\t@{ \n\t\t\tis_voc=false;\n\t\t\t\/\/docubody_.push_back(\"@endcode\");\n\t\t}\n\t\t) );\n\n\t# lines that could end doxyblock {{{6\n\t# words\n\t# RAGEL comment: ( default - [ \\t:%'`\\n] )+\n\t( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n\t# non-words\/non-whitespace\n\t# RAGEL comment: ([:'`]) => {\n\t(':') @(end_doxy_block) ;\n\n\t# whitespace only\n\t( [ \\t] );\n\n\t# titled paragraph\n\t( ':' . EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t assert(ts > tmp_p);\n\t\t docubody_.push_back((!is_voc ? \"@par \":\"\") + string(tmp_p+1, ts - tmp_p-1)+(is_voc ? \":\":\"\")+\"\\n\");\n\t\t docline = false;\n\t\t }\n\t };\n\t# }}}6\n\t# }}}4\n\n\t# end of line {{{4\n\t( EOL )\n\t @(end_doxy_block)\n\t @{ if(docline)\n\t\t {\n\t\t\tint offset = ( latex_begin ? 0 : 1 );\n\t\t\tassert(p >= tmp_p + offset);\n\t\t\tdocubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n\t\t\tdocline = false;\n\t\t }\n\t\t};\n\t # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n\tgarbage = ( (default - [\\r\\n] )* -- '...' );\n\n\t( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n\t( doc_begin . (garbage . '...')* . garbage . EOL )\n\t => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n\t# read in one comment line\n\t( doc_begin . [\\t ]*\n\t . (default - [\\r\\n\\t ]) . (default - [\\r\\n])* . EOL\n\t)\n\t => {\n\t\t\/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n\t\tassert(p >= tmp_p);\n\t\tdocuheader_.push_back(string(tmp_p, p - tmp_p+1));\n\t };\n\n\t# empty line\n\t( doc_begin . [\\t ]* . EOL )\n\t => {\n\t\t\/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n\t\tfgoto doxy_get_body;\n\t };\n\n\t# end of comment block;\n\t( [\\t ]* . [^%] )\n\t => {\n\t\tp=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n\t\t\/\/fout_ << \"*\/\\n\";\n\t\tif(is_class_)\n\t\t{\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n\t\t if(class_part_ == Header)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n\t\t\tend_of_class_doc();\n\t\t\tfgoto classbody;\n\t\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n\t\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t\t return 1;\n\t\t\tprint_function_synopsis();\n\t\t\tfgoto funcbody;\n\t\t }\n\t\t else if(class_part_ == MethodDeclaration)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n\t\t\tfgoto funcdef;\n\t\t }\n\t\t else if(class_part_ == Property || class_part_ == Event)\n\t\t {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n\t\t\tfgoto propertybody;\n\t\t }\n\t\t else if(class_part_ == InClassComment)\n\t\t {\n\t\t\tclass_part_ = Method;\n\t\t\tfgoto methods;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t if(runMode_.mode == RunMode::ParseParams)\n\t\t\treturn 1;\n\t\t print_function_synopsis();\n\t\t fgoto funcbody;\n\t\t}\n\t };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n\t'%' . [ \\t]* .\n\t (\n\t\t('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n\t )\n\t $!{\n#ifdef DEBUG\n\t\tdebug_output(\"doxy_get_brief\",p);\n#endif\n\t\tp = tmp_p - 2;\n\t\tfgoto doxy_get_brief;\n\t }\n ); #}}}2\n\n # access specifier expressions\n spec_public = ( 'public'i | \"'public'\"i );\n spec_protected = ( 'protected'i | \"'protected'\"i );\n spec_private = ( 'private'i | \"'private'\"i );\n \n spec_class_single = \n\t (\n\t ('?' . (IDENT_W_DOT**) >st_tok )\n\t %{\n\t\t\ttmp_string.assign(tmp_p, p - tmp_p);\n\t\t\t\/\/cerr << \"Detected \" << access_.state << \" modifier by class \" << tmp_string << \"\\n\";\n\t\t\taccess_.classMemberAccess.push_back(make_pair(access_.state, tmp_string));\n\t\t}\n\t ) . WS*;\n \n spec_class_multi = '{' . WS* . spec_class_single . ( [,; ] . WS* . spec_class_single )* . '}';\n \n spec_classes = ( spec_class_single | spec_class_multi );\n\t\n # helper for setting the access specifier {{{2\n paramaccess =\n\t( ('SetAccess' @{ access_.state = SetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public \n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'GetAccess' @{ access_.state = GetAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'Access' @{ access_.state = Access; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = Protected; access_.get = Protected; access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = Private; access_.get = Private; access_.set = Private;\n\t\t\t } )\n\t\t )\n\t )\n\t); #}}}2\n\n eventparam =\n\t( ('ListenAccess' @{ access_.state = ListenAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.get = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.set == Public ? Public : Protected );\n\t\t\t access_.get = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.set; access_.get = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( 'NotifyAccess' @{ access_.state = NotifyAccess; } . WS* . '=' . WS*\n\t . ( ( spec_public\n\t\t\t%{ access_.full = Public; access_.set = Public;\n\t\t\t } )\n\t\t| ( ( spec_protected | spec_classes )\n\t\t\t%{ access_.full = (access_.get == Public ? Public : Protected );\n\t\t\t access_.set = Protected;\n\t\t\t } )\n\t\t| ( spec_private\n\t\t\t%{ access_.full = access_.get; access_.set = Private;\n\t\t\t } )\n\t\t)\n\t )\n\t | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t );\n\n # method and property params {{{2\n methodparam =\n (\n\t( paramaccess )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.abstr = true;\n\t\t } )\n\t| ( ( 'Static' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.statical = true;\n\t\t } )\n\t| ( ('Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.hidden = true;\n\t\t } )\n\t| ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.sealed = true;\n\t\t } )\n\t| ( ( 'Test' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.test = true;\n\t\t } )\n\t| ( ( 'TestMethodSetup' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodSetup = true;\n\t\t } )\n\t| ( ( 'TestMethodTeardown' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t methodparams_.testMethodTeardown = true;\n\t\t } )\n );\n\n propertyparam =\n (\n\t( paramaccess )\n\t| ( ( 'Constant' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.constant = true;\n\t\t } )\n\t| ( ( 'Transient' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.transient = true;\n\t\t } )\n\t| ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.dependent = true;\n\t\t } )\n\t| ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.hidden = true;\n\t\t } )\n\t| ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.setObservable = true;\n\t\t } )\n\t| ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abstr = true;\n\t\t } )\n\t| ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n\t\t@{\n\t\t propertyparams_.abortSet = true;\n\t\t } )\n );\n\n methodparams =\n (\n\t'(' . WSOC*\n\t. methodparam\n\t. ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n eventparams =\n (\n\t'(' . WSOC*\n\t. eventparam\n\t. ( WSOC* . ',' . WSOC* . eventparam )* . WSOC* . ')'\n ); #}}}2\n\n propertyparams =\n (\n\t'(' . WSOC*\n\t. propertyparam\n\t. ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n\t(empty_line) => {\n\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t {\n\t\tend_method();\n\t\tfout_ << \"\\n\";\n\t }\n\t};\n\n\t# default: method definition\n\t([ \\t]* . 'function' )\n\t => {\n\t\ttmp_string.assign(ts, te - ts+1);\n\t\tfuncindent_ = tmp_string.find_first_not_of(\" \\t\");\n\t\tfout_ << string(ts, ts+funcindent_);\n\t\t#if DEBUG\n\t\t\t{\n\t\t\t ostringstream oss;\n\t\t\t oss << \"in methods: funcindent: \" << funcindent_;\n\t\t\t debug_output(oss.str(), p);\n\t\t\t}\n\t\t#endif\n\t\tp=ts+funcindent_-1;\n\t\tfgoto funct;\n\t };\n\n\t# end of methods block\n\t([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n\t => {\n\t\t if(runMode_.mode != RunMode::ParseMethodParams)\n\t\t {\n\t\t\t end_method();\n\t\t\t #if DEBUG\n\t\t\t debug_output(\"in methods: found end keyword, goto classbody\",p);\n\t\t\t #endif\n\t\t }\n\t\t fgoto classbody;\n\t\t };\n\n\t# comment between two methods\n\t([ \\t]* . '%' ) => {\n\t #if DEBUG\n\t\tdebug_output(\"in methods: garble comment line\",p);\n\t #endif\n\n\t p = ts-1;\n\t class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n\t fgoto expect_doxyblock;\n\t};\n\n\t# if we reach this: method declaration without definition is found\n\t([ \\t]* . [^% \\t\\n]) =>\n\t{\n\t #if DEBUG\n\t\tdebug_output(\"in methods: found method declaration, going to funcdef\",p);\n\t #endif\n\t class_part_ = MethodDeclaration;\n\t p = ts-1;\n\t fgoto funcdef;\n\t};\n\n\t *|;\n\n\n methodsheader := (\n\t[ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n\t\t @{\n\t\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t\tfgoto methods;\n\t\t }\n\t\t );\n\n #}}}4\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_property_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\")\n\t\t\t\tfgoto classbody;\n\t\t\t if (propertyparams_.dependent)\n\t\t\t\tspecifier_[s].dependent = true;\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t )\n\t\t. WS* . ( ( '%' @{ fhold; } | ';' | EOL ) @{defaultprop_ = \"\";}\n\t\t\t|\n\t\t\t( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n\t\t\t@{\n\t\t\t defaultprop_ = string(tmp_p2, p - tmp_p2);\n\t\t\t string::size_type last_elem = defaultprop_.length() -1;\n\t\t\t if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n\t\t\t {\n\t\t\t\tdefaultprop_[0] = '\\\"';\n\t\t\t\tdefaultprop_[last_elem] = '\\\"';\n\t\t\t }\n\t\t\t string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n\t\t\t string::size_type last_paren;\n\t\t\t if (first_paren == string::npos)\n\t\t\t {\n\t\t\t\tfirst_paren = 1;\n\t\t\t\tlast_paren = last_elem;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tlast_paren = defaultprop_.find_last_of(\")]}\");\n\t\t\t\tif (last_paren == string::npos)\n\t\t\t\t last_paren=last_elem-1;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n\t\t\t\t {\n\t\t\t\t\tfirst_paren++;\n\t\t\t\t\tlast_paren--;\n\t\t\t\t }\n\t\t\t\t defaultprop_.insert(first_paren, 1,'\"');\n\t\t\t\t defaultprop_.insert(last_paren+2, 1,'\"');\n\t\t\t\t first_paren++;\n\t\t\t\t last_paren++;\n\t\t\t\t}\n\t\t\t }\n\t\t\t for (unsigned int i = first_paren; i < last_paren; ++i)\n\t\t\t {\n\t\t\t\tif(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n\t\t\t\t{\n\t\t\t\t defaultprop_[i] = ' ';\n\t\t\t\t defaultprop_[i+1] = ' ';\n\t\t\t\t defaultprop_[i+2] = ' ';\n\t\t\t\t}\n\/* else if(defaultprop_[i] == '[')\n\t\t\t\t defaultprop_[i] = '{';\n\t\t\t\telse if(defaultprop_[i] == ']')\n\t\t\t\t defaultprop_[i] = '}'; *\/\n\t\t\t\telse if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n\t\t\t\t defaultprop_[i] = ',';\n\t\t\t\telse if(defaultprop_[i] == '\\\"')\n\t\t\t\t defaultprop_[i] = '\\'';\n\t\t\t\telse if(defaultprop_[i] == '@')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t\telse if(defaultprop_[i] == '\\n')\n\t\t\t\t{\n\t\t\t\t defaultprop_.insert(i, 1, '\\\\');\n\t\t\t\t ++i;\n\t\t\t\t}\n\t\t\t }\n\t\t\t }\n\t\t )\n\t );\n\n #}}}4\n\n #property body {{{4\n propertybody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n properties := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. propertybody* )\n\t );\n\n #property body {{{4\n eventbody = (\n\t(prop)\n\t|\n\t( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n events := ((\n\tWSOC* . eventparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\t}\n\t. eventbody* )\n\t );\n\n enum = ( [ \\t]* . (IDENT) >st_tok\n\t\t\t%{\n\t\t\t {\n\t\t\t\tchar *i = tmp_p-1;\n\t\t\t\tfor (; *i == ' ' || *i == '\\t'; --i)\n\t\t\t\t fout_ << *i;\n\t\t\t }\n\t\t\t \n\t\t\t end_of_enum_doc();\n\t\t\t string s(tmp_p, p - tmp_p);\n\t\t\t if (s == \"end\") {\n\t\t\t\tfout_ << \"\\n} \" << classname_ << \"Enum;\\n\";\n\t\t\t\tfgoto classbody;\n\t\t\t }\n\t\t\t property_list_.push_back(s);\n\t\t\t \/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n\t\t\t undoced_prop_ = true;\n\t\t\t}\n\t\t . WS* . ( '%' @{ fhold; } | ';' | ',' | EOL )\n\t\t );\n\n enumerationbody = (\n\t(enum)\n\t|\n\t( (empty_line) @{ end_of_enum_doc(); fout_ << \"\\n\";} )\n\t|\n\t( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n\t);\n\n enumeration := ( (\n\tWSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n\t\tprint_access_specifier(access_.full, methodparams_, propertyparams_);\n\t\tfout_ << \"typedef enum {\\n\";\n\t\t}\n\t. enumerationbody* )\n\t );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n\t# a comment block\n\t(comment_block)\n\t => {\n\t\tif (*(p-1) == '\\r')\n\t\t fout_.write(tmp_p, p - tmp_p - 1);\n\t\telse\n\t\t fout_.write(tmp_p, p - tmp_p);\n\t\tfcall in_comment_block;\n\t };\n\n\t(WSOC); # => { fout_.write(ts, te-ts); };\n\n\t(EOL) => { fout_ << \"\\n\"; };\n\n\t('end' . [ \\t]* ';'?) => {\n\t std::map::iterator specIt;\n\t for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n\t {\n\t\tfout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n\t\tif ( (*specIt).second.dependent)\n\t\t{\n\t\t if( (*specIt).second.getter && ! (*specIt).second.setter )\n\t\t {\n\t\t\tfout_ << \"@note [readonly]\\n *\";\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t fout_ << \"@note This property has custom functionality when its value is \";\n\t\t if ((*specIt).second.getter)\n\t\t {\n\t\t\tfout_ << \"retrieved\";\n\t\t\tif ((*specIt).second.setter)\n\t\t\t fout_ << \" or changed\";\n\t\t }\n\t\t else if ((*specIt).second.setter)\n\t\t\tfout_ << \"changed\";\n\t\t fout_ << \".\";\n\t\t}\n\t\tfout_ << \"\\n *\/\\n\";\n\t }\n\t fout_ << \"\\n};\\n\";\n\t for( list::iterator it = namespaces_.begin();\n\t\t\tit != namespaces_.end(); ++it)\n\t {\n\t\tfout_ << \"}\\n\";\n\t }\n\t};\n\n\t([ \\t]* . 'properties')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Property;\n\t\tfgoto properties;\n\t };\n\t([ \\t]* . 'methods')\n\t => {\n\t\tmethodparams_ = MethodParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Method;\n\t\tfgoto methodsheader;\n\t };\n\t([ \\t]* . 'events')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\tpropertyparams_.event = true;\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Event;\n\t\tfgoto events;\n\t };\n\t([ \\t]* . 'enumeration')\n\t => {\n\t\tpropertyparams_ = PropParams();\n\t\taccess_ = AccessStruct();\n\t\tclass_part_ = Enumeration;\n\t\tfgoto enumeration;\n\t };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n\tdoc_begin\n\t @{\n\t\t\/\/fout_ << \"\/*\";\n\t\tp--;\n\t\tfgoto doxyheader;\n\t }\n )\n $!{\n\tfhold;\n\t{\n\t int i = 0;\n\t for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n\t\t;\n\t std::string whitespaces(i, ' ');\n\/\/ if (string(p, 5) == \" if ~\")\n\/\/ {\n\/\/ debug_output(\"break;\", p);\n\/\/ fout_ << \"\/* start *\/\";\n\/\/ }\n\/\/ for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/ fout_ << *i;\n\/\/ fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n\tdebug_output(\"stopping expect_doxyblock\", p);\n#endif\n\tif(is_class_)\n\t{\n\t if(class_part_ == Header)\n\t {\n\t\tend_of_class_doc();\n\t\tfgoto classbody;\n\t } else if(class_part_ == Method || class_part_ == AtMethod)\n\t {\n\t\tstring endstringtest;\n\t\tendstringtest.assign(p, 100);\n\t\tstring::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n\t\tif(runMode_.mode == RunMode::ParseParams)\n\t\t return 1;\n\t\tif (endstringtest.substr(first_char, 3) == \"end\")\n\t\t{\n\t\t p += first_char+4;\n\t\t print_function_synopsis();\n\t\t end_function();\n\t\t fgoto methods;\n\t\t}\n\t\telse\n\t\t{\n\t\t print_function_synopsis();\n\t\t fout_ << whitespaces;\n\t\t fgoto funcbody;\n\t\t}\n\t }\n\t else if(class_part_ == Property || class_part_ == Event)\n\t {\n\t\tfgoto propertybody;\n\t }\n\t else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n\t {\n\t\tclass_part_ = Method;\n\t\tfgoto methods;\n\t }\n\t else{\n\t\tcerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n\t }\n\t}\n\telse\n\t{\n\t if(runMode_.mode == RunMode::ParseParams)\n\t\treturn 1;\n\t print_function_synopsis();\n\t fout_ << whitespaces;\n\t fgoto funcbody;\n\t}\n\t}\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n\t (WSOC)* .\n\t # return values (if found opt = true)\n\t (lparams)? .\n\t # matlab identifier (function name stored in cfuncname_)\n\t ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n\t\tIDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tcfuncname_.assign(tmp_p, p - tmp_p);\n\t\t\t#ifdef DEBUG\n\t\t\t cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n\t\t\t#endif\n\t\t\t\/\/ in ParseMethodParams mode, we only check for the method\n\t\t\t\/\/ parameters of a specific method.\n\t\t\tif(is_class_ && class_part_ == MethodDeclaration\n\t\t\t && runMode_.mode == RunMode::ParseMethodParams)\n\t\t\t{\n\t\t\t if(runMode_.methodname == cfuncname_)\n\t\t\t {\n\t\t\t\treturn 0;\n\t\t\t }\n\t\t\t}\n\t\t\tif(runMode_.mode == RunMode::Normal\n\t\t\t && is_class_ && class_part_ == AtMethod)\n\t\t\t{\n\t\t\t update_method_params(cfuncname_);\n\t\t\t}\n\t\t\tis_script_ = false;\n\t\t }\n\t )\n\t . WSOC*\n\t . (\n\t\t '('\n\t\t # parameter list\n\t\t . ( paramlist\n\t\t\t %{\n\t\t\t\t if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n\t\t\t\t { paramlist_.clear(); }\n\t\t\t }\n\t\t\t )\n\t\t . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )*\n\t\t . EOL\n\t\t @{\n\t\t\t if(comment_found)\n\t\t\t {\n\t\t\t\ttmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\ttmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\ttmp_string = \"\";\n\t\t\t }\n\t\t\t comment_found = false;\n\t\t\t if(is_class_ && class_part_ == MethodDeclaration )\n\t\t\t {\n\t\t\t class_part_ = Method;\n\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n\t\t\t #endif\n\t\t\t fgoto methods;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t \/\/ fout_ << tmp_string << \"{\\n\";\n\t\t\t \/\/ check for documentation block\n\t\t\t fgoto expect_doxyblock;\n\t\t\t }\n\t\t }\n\t\t# no parameter list && first function => ( script || method )\n\t\t| (( [ \\t]\n\t\t\t |\n\t\t\t ('%' @{ tmp_p=p; comment_found=true; }\n\t\t\t . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n\t\t\t@{\n\t\t\t\t if(comment_found)\n\t\t\t\t {\n\t\t\t\t tmp_string.assign(tmp_p+1, p - tmp_p-1);\n\t\t\t\t tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t tmp_string = \"\";\n\t\t\t\t }\n\t\t\t\t comment_found = false;\n\t\t\t\t #if DEBUG\n\t\t\t\t debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n\t\t\t\t #endif\n\t\t\t\t if(is_class_ && class_part_ == MethodDeclaration)\n\t\t\t\t {\n\t\t\t\t\tclass_part_ = Method;\n\t\t\t\t\tfgoto methods;\n\t\t\t\t }\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t fgoto expect_doxyblock;\n\t\t\t\t }\n\t\t\t }\n\t\t)\n\t );\n\n funct :=\n (\n\t(\n\t comment_block @in_c_block\n\t | [ \\t]*. EOL\n\t)*\n\t. ([\\t]*) . 'function' . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n\t@{\n\t string :: size_type found = filename_.rfind(\"\/\");\n\t if(found == string :: npos)\n\t\t found = -1;\n\t string funcname = filename_.substr(found+1, filename_.size()-3-found);\n\t cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n\t if(!is_first_function_)\n\t\t fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\t fout_ << funcname << \"() {\\n\";*\/\n\t is_script_ = true;\n\t fhold;\n\t fgoto expect_doxyblock;\n\t }; #}}}2\n\n # class definitions {{{2\n classparams =\n\t '(' . [^)]* . ')';\n\n superclass =\n\t( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n\t\t\t\t\t @{ if(*p == '.')\n\t\t\t\t\t\t fout_ << \"::\";\n\t\t\t\t\t\t else fout_ << *p; } );\n\n superclasses = (\n\t '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n\t\t . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n\t 'classdef' . WSOC* . ('(' . WSOC*\n\t\t. (( 'Sealed'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n\t\t }\n\t\t )\n\n\t\t |( 'Hidden'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Hidden' and is invisible.\"));\n\t\t }\n\t\t )\n\t\t |( 'Abstract'i\n\t\t @{\n\t\t\tdocuextra_.push_back(std::string(\"@note This class has the class property 'Abstract' and needs to be inherited in order to be instantiable.\"));\n\t\t }\n\t\t )) . [^)]* . ')')? . WSOC* .\n\t # matlab identifier (class name stored in classname_)\n\t ( IDENT\n\t\t >st_tok\n\t\t %{\n\t\t\tclassname_.assign(tmp_p, p - tmp_p);\n\t\t\tis_class_ = true;\n\t\t\tfout_ << \"class \" << classname_;\n\t\t }\n\t )\n\t . WSOC*\n\t . classparams?\n\t . WSOC*\n\t . superclasses?\n\t . [ \\t;]*\n\t . ( '%'. garble_comment_line_wo_eol )?\n\t EOL\n\t @{\n\t\tfout_ << \" {\\n\";\n\t\tfgoto expect_doxyblock;\n\t } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n\t# either we find a function or classdef definition with a possibly\n\t# preceding comment block or we have a script\n\t( any\n\t @{\n\t\t fhold;\n\t\t tmp_p = p;\n\t\t}\n\t .\n\t(\n\t [ \\t]*. '%' . (any - '\\n')* . EOL\n\t | [ \\t]*. EOL\n\t)*\n\t. [\\t]*\n\t. ( 'function' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t char *tp;\n\t\t\t\t\t for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n\t\t\t\t\t ;\n\t\t\t\t\t funcindent_ = (int)(p - tp);\n#if DEBUG\n\t\t\t\t\t {\n\t\t\t\t\t ostringstream oss;\n\t\t\t\t\t oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n\t\t\t\t\t debug_output(oss.str(), p);\n\t\t\t\t\t }\n#endif\n\t\t\t\t\t if(is_class_ && class_part_ == Header)\n\t\t\t\t\t class_part_ = AtMethod;\n\t\t\t\t\t fgoto funct;\n\t\t\t\t\t}\n\t | 'classdef' @{\n\t\t\t\t\t p-=8;\n\t\t\t\t\t fgoto classdef;\n\t\t\t\t\t}\n\t ) )\n $!{\n#ifdef DEBUG\n\tdebug_output(\"goto script\",p);\n#endif\n\tp=tmp_p;\n\tfgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n fout_ << \" * the correct locations in the source code browser.\\n\";\n fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n \n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n\tchar *p = buf + have;\n\tchar *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n\tstring tmp_string, tmp_string2, tmp_string3;\n\tbool docline = false;\n\tbool latex_begin = true;\n\tbool comment_found = false;\n\tint space = BUFSIZE - have;\n\n\tif ( space == 0 )\n\t{\n\t \/* We filled up the buffer trying to scan a token. *\/\n\t cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n\t exit(-1);\n\t}\n\n\tfin_.read( p, space );\n\tint len = fin_.gcount();\n\tchar *pe = p + len;\n\tchar *rpe = pe;\n\tchar *eof = 0;\n\n\t\/* If we see eof then append the EOF char. *\/\n\tif ( fin_.eof() )\n\t{\n\t char eof_c = *pe;\n\t *pe = '\\n';\n\t pe++;\n\t *pe = eof_c;\n\t eof = pe;\n\t rpe = pe;\n\n\t done = true;\n\t}\n\telse\n\t{\n\t \/* Find the last newline by searching backwards. This is where\n\t * we will stop processing on this iteration. *\/\n\t while ( pe >= p )\n\t {\n\t\tif( *pe != '\\n')\n\t\t pe--;\n\t\telse\n\t\t{\n\t\t if(pe >= p+3\n\t\t\t && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n\t\t\tpe-=3;\n\t\t else\n\t\t\tbreak;\n\t\t}\n\t }\n\t}\n\n\t%% write exec;\n\n\t\/* Check if we failed. *\/\n\tif ( cs == MFileScanner_error )\n\t{\n\t \/* Machine failed before finding a token. *\/\n\t cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n\t debug_output(\"Grrrr!!!!\", p);\n\t exit(-1);\n\t}\n\n\t\/* Now set up the prefix. *\/\n\tif ( ts == 0 )\n\t{\n\t have = rpe - pe;\n\t \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n\t memmove( buf, pe, have );\n\t}\n\telse\n\t{\n\t have = rpe - ts;\n\t \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n\t memmove( buf, ts, have );\n\t}\n\n\tif ( ts != 0 )\n\t{\n\t te -= (ts-buf);\n\t ts = buf;\n\t}\n }\n\n return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"7d7be6ccc3a13c5bfb6d145d947508af096994c7","subject":"added a couple missing includes","message":"added a couple missing includes\n","repos":"timoc\/colm,timoc\/colm,timoc\/colm,timoc\/colm","old_file":"test\/mediawiki\/garticle.rl","new_file":"test\/mediawiki\/garticle.rl","new_contents":"#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::ifstream;\nusing std::ofstream;\n\n%%{\n\tmachine garticle;\n\twrite data;\n}%%\n\n\nint main( int argc, char **argv )\n{\n\tstd::ios::sync_with_stdio(false);\n\n\tif ( argc != 5 ) {\n\t\tcerr << \"usage: garticle

\" << endl;\n\t\treturn -1;\n\t}\n\n\tchar *dumpFile = argv[1];\n\tchar *articleIndex = argv[2];\n\tchar *section = argv[3];\n\tchar *article = argv[4];\n\n\tifstream dump( dumpFile );\n\tif ( !dump.is_open() ) {\n\t\tcerr << \"error: unable to open \" << dumpFile << \" for reading\" << endl;\n\t\treturn -1;\n\t}\n\n\tifstream index( articleIndex );\n\tif ( !index.is_open() ) {\n\t\tcerr << \"error: unable to open \" << articleIndex << \" for writing\" << endl;\n\t\treturn -1;\n\t}\n\n\tlong long articleNum = atoll(article);\n\tindex.seekg( articleNum * sizeof(long long) );\n\n\tlong long start, end;\n\tindex.read( (char*)&start, sizeof(long long) );\n\tindex.read( (char*)&end, sizeof(long long) );\n\n\tlong long len = end - start;\n\tchar *buf = new char[len];\n\tdump.seekg( start-5 );\n\tdump.read( buf, len );\n\n\tchar tn[2048];\n\tlong ptn = 0;\n\tbool emit = false;\n\n\tchar *p = buf, *pe = buf+len;\n\tint cs;\n\n\t%%{\n\t\tnewline = '\\n';\n\t\tsp = [ \\t\\n\\r];\n\n\t\tname = [a-zA-Z:_0-9]+;\n\n\t\t# Tag names.\n\t\ttag_name = name\n\t\t\t>{ ptn = 0; }\n\t\t\t${ tn[ptn++] = *p; }\n\t\t\t%{ tn[ptn++] = 0; }\n\t\t\t;\n\n\t\tattr_name = name;\n\n\t\t# Attributes\n\t\tattr_val = '\"' ( [^\"\\\\] | newline | ( '\\\\' any ) )* '\"';\n\t\tattr = attr_name '=' attr_val;\n\t\tattrs = ( sp attr )*;\n\n\t\taction maybe_open {\n\t\t\tif ( strcmp( tn, section ) == 0 )\n\t\t\t\temit = true;\n\t\t}\n\n\t\taction maybe_close {\n\t\t\tif ( strcmp( tn, section ) == 0 )\n\t\t\t\temit = false;\n\t\t}\n\n\t\t# Tags\n\t\ttag = '<' tag_name %maybe_open attrs sp? ( '>' | '\/>' );\n\t\tclose_tag = '<\/' tag_name %maybe_close '>';\n\n\t\t# Character data, not spaces and not tag starts.\n\t\tchar_data_char = ^('<'|'&');\n\t\tchar_data = char_data_char+\n\t\t\t${ \n\t\t\t\tif ( emit )\n\t\t\t\t\tcout << *p;\n\t\t\t} ;\n\n\t\tdefined_entities =\n\t\t\t'quot' %{if (emit) cout << '\"';} |\n\t\t\t'amp' %{if (emit) cout << '&';} |\n\t\t\t'apos' %{if (emit) cout << '\\'';} |\n\t\t\t'lt' %{if (emit) cout << '<';} |\n\t\t\t'gt' %{if (emit) cout << '>';};\n\n\t\tentity_ref = '&' defined_entities ';';\n\n\t\tmain := ( \n\t\t\t\ttag |\n\t\t\t\tclose_tag |\n\t\t\t\tentity_ref |\n\t\t\t\tchar_data\n\t\t\t)*\n\t\t\t;\n\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\n\tif ( cs < garticle_first_final ) {\n\t\tcerr << endl << endl << \"garticle: error parsing dump file\" << endl;\n\t\treturn 1;\n\t}\n\n\t\/\/cout.write( buf, len );\n\tcout << endl;\n\n\treturn 0;\n}\n","old_contents":"#include \n#include \n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::ifstream;\nusing std::ofstream;\n\n%%{\n\tmachine garticle;\n\twrite data;\n}%%\n\n\nint main( int argc, char **argv )\n{\n\tstd::ios::sync_with_stdio(false);\n\n\tif ( argc != 5 ) {\n\t\tcerr << \"usage: garticle
\" << endl;\n\t\treturn -1;\n\t}\n\n\tchar *dumpFile = argv[1];\n\tchar *articleIndex = argv[2];\n\tchar *section = argv[3];\n\tchar *article = argv[4];\n\n\tifstream dump( dumpFile );\n\tif ( !dump.is_open() ) {\n\t\tcerr << \"error: unable to open \" << dumpFile << \" for reading\" << endl;\n\t\treturn -1;\n\t}\n\n\tifstream index( articleIndex );\n\tif ( !index.is_open() ) {\n\t\tcerr << \"error: unable to open \" << articleIndex << \" for writing\" << endl;\n\t\treturn -1;\n\t}\n\n\tlong long articleNum = atoll(article);\n\tindex.seekg( articleNum * sizeof(long long) );\n\n\tlong long start, end;\n\tindex.read( (char*)&start, sizeof(long long) );\n\tindex.read( (char*)&end, sizeof(long long) );\n\n\tlong long len = end - start;\n\tchar *buf = new char[len];\n\tdump.seekg( start-5 );\n\tdump.read( buf, len );\n\n\tchar tn[2048];\n\tlong ptn = 0;\n\tbool emit = false;\n\n\tchar *p = buf, *pe = buf+len;\n\tint cs;\n\n\t%%{\n\t\tnewline = '\\n';\n\t\tsp = [ \\t\\n\\r];\n\n\t\tname = [a-zA-Z:_0-9]+;\n\n\t\t# Tag names.\n\t\ttag_name = name\n\t\t\t>{ ptn = 0; }\n\t\t\t${ tn[ptn++] = *p; }\n\t\t\t%{ tn[ptn++] = 0; }\n\t\t\t;\n\n\t\tattr_name = name;\n\n\t\t# Attributes\n\t\tattr_val = '\"' ( [^\"\\\\] | newline | ( '\\\\' any ) )* '\"';\n\t\tattr = attr_name '=' attr_val;\n\t\tattrs = ( sp attr )*;\n\n\t\taction maybe_open {\n\t\t\tif ( strcmp( tn, section ) == 0 )\n\t\t\t\temit = true;\n\t\t}\n\n\t\taction maybe_close {\n\t\t\tif ( strcmp( tn, section ) == 0 )\n\t\t\t\temit = false;\n\t\t}\n\n\t\t# Tags\n\t\ttag = '<' tag_name %maybe_open attrs sp? ( '>' | '\/>' );\n\t\tclose_tag = '<\/' tag_name %maybe_close '>';\n\n\t\t# Character data, not spaces and not tag starts.\n\t\tchar_data_char = ^('<'|'&');\n\t\tchar_data = char_data_char+\n\t\t\t${ \n\t\t\t\tif ( emit )\n\t\t\t\t\tcout << *p;\n\t\t\t} ;\n\n\t\tdefined_entities =\n\t\t\t'quot' %{if (emit) cout << '\"';} |\n\t\t\t'amp' %{if (emit) cout << '&';} |\n\t\t\t'apos' %{if (emit) cout << '\\'';} |\n\t\t\t'lt' %{if (emit) cout << '<';} |\n\t\t\t'gt' %{if (emit) cout << '>';};\n\n\t\tentity_ref = '&' defined_entities ';';\n\n\t\tmain := ( \n\t\t\t\ttag |\n\t\t\t\tclose_tag |\n\t\t\t\tentity_ref |\n\t\t\t\tchar_data\n\t\t\t)*\n\t\t\t;\n\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\n\tif ( cs < garticle_first_final ) {\n\t\tcerr << endl << endl << \"garticle: error parsing dump file\" << endl;\n\t\treturn 1;\n\t}\n\n\t\/\/cout.write( buf, len );\n\tcout << endl;\n\n\treturn 0;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"4ec304024c924cc5a6ab939109006b13fdd1ff0f","subject":"The proper align value is 'justify' not 'justified'","message":"The proper align value is 'justify' not 'justified'\n","repos":"mmorga\/redcloth,purcell\/redcloth,amrocco\/redcloth,amrocco\/redcloth,mmorga\/redcloth,purcell\/redcloth,dmitry\/redcloth,github\/redcloth,github\/redcloth,dmitry\/redcloth","old_file":"ext\/superredcloth_scan\/superredcloth_common.rl","new_file":"ext\/superredcloth_scan\/superredcloth_common.rl","new_contents":"%%{\n\n machine superredcloth_common;\n\n action A { reg = p; }\n action T { STORE(text); }\n action X { regs = rb_hash_new(); reg = NULL; }\n action cat { CAT(block); }\n action esc { rb_str_cat_escaped(block, tokstart, tokend); }\n action esc_pre { rb_str_cat_escaped_for_preformatted(block, tokstart, tokend); }\n action ignore { rb_str_append(block, rb_funcall(rb_formatter, rb_intern(\"ignore\"), 1, regs)); }\n\n # simple\n CRLF = ( '\\r'? '\\n' ) ;\n default = ^0 ;\n EOF = 0 ;\n\n # textile modifiers\n A_LEFT = \"<\" %{ ASET(align, left) } ;\n A_RIGHT = \">\" %{ ASET(align, right) } ;\n A_JUSTIFIED = \"<>\" %{ ASET(align, justify) } ;\n A_CENTER = \"=\" %{ ASET(align, center) } ;\n A_PADLEFT = \"(\" >A %{ AINC(padding-left) } ;\n A_PADRIGHT = \")\" >A %{ AINC(padding-right) } ;\n A_HLGN = ( A_LEFT | A_RIGHT | A_JUSTIFIED | A_CENTER | A_PADLEFT | A_PADRIGHT ) ;\n A_LIMIT = ( A_LEFT | A_CENTER | A_RIGHT ) ;\n A_VLGN = ( \"-\" %{ ASET(valign, middle) } | \"^\" %{ ASET(valign, top) } | \"~\" %{ ASET(valign, bottom) } ) ;\n C_CLAS = ( \"(\" ( [^)#]+ >A %{ STORE(class) } )? (\"#\" [^)]+ >A %{STORE(id)} )? \")\" ) ;\n C_LNGE = ( \"[\" [^\\]]+ >A %{ STORE(lang) } \"]\" ) ;\n C_STYL = ( \"{\" [^}]+ >A %{ STORE(style) } \"}\" ) ;\n S_CSPN = ( \"\\\\\" [0-9]+ >A %{ STORE(colspan) } ) ;\n S_RSPN = ( \"\/\" [0-9]+ >A %{ STORE(rowspan) } ) ;\n D_HEADER = \"_\" %{ ASET(th, true) } ;\n A = ( ( A_HLGN | A_VLGN )* ) ;\n A2 = ( A_LIMIT? ) ;\n S = ( S_CSPN | S_RSPN )* ;\n C = ( C_CLAS | C_STYL | C_LNGE )* ;\n D = ( D_HEADER ) ;\n N_CONT = \"_\" %{ ASET(start, continue) };\n N_NUM = digit+ >A %{ STORE(start) };\n N = ( N_CONT | N_NUM )? ;\n PUNCT = ( \"!\" | '\"' | \"#\" | \"$\" | \"%\" | \"&\" | \"'\" | \",\" | \"--\" | \".\" | \"\/\" | \":\" | \";\" | \"=\" | \"?\" | \"\\\\\" | \"^\" | \"`\" | \"|\" | \"~\" | \"[\" | \"(\" | \"<\" ) ;\n dotspace = (\".\" \" \"*) ;\n indent = [ \\t]* ;\n\n # text blocks\n trailing = PUNCT - (\"'\" | '\"') ;\n chars = (default - space)+ ;\n phrase = chars -- trailing ;\n\n # html tags (from Hpricot)\n NameChar = [\\-A-Za-z0-9._:?] ;\n Name = [A-Za-z_:] NameChar* ;\n NameAttr = NameChar+ ;\n Q1Attr = [^']* ;\n Q2Attr = [^\"]* ;\n UnqAttr = ( space | [^ \\t\\r\\n<>\"'] [^ \\t\\r\\n<>]* ) ;\n Nmtoken = NameChar+ ;\n Attr = NameAttr space* \"=\" space* ('\"' Q2Attr '\"' | \"'\" Q1Attr \"'\" | UnqAttr space+ ) space* ;\n AttrEnd = ( NameAttr space* \"=\" space* UnqAttr? | Nmtoken ) ;\n AttrSet = ( Attr | Nmtoken space+ ) ;\n start_tag = \"<\" Name space+ AttrSet* (AttrEnd)? \">\" | \"<\" Name \">\";\n empty_tag = \"<\" Name space+ AttrSet* (AttrEnd)? \"\/>\" | \"<\" Name \"\/>\" ;\n end_tag = \"<\/\" Name space* \">\" ;\n html_comment = \"\";\n\n}%%;\n","old_contents":"%%{\n\n machine superredcloth_common;\n\n action A { reg = p; }\n action T { STORE(text); }\n action X { regs = rb_hash_new(); reg = NULL; }\n action cat { CAT(block); }\n action esc { rb_str_cat_escaped(block, tokstart, tokend); }\n action esc_pre { rb_str_cat_escaped_for_preformatted(block, tokstart, tokend); }\n action ignore { rb_str_append(block, rb_funcall(rb_formatter, rb_intern(\"ignore\"), 1, regs)); }\n\n # simple\n CRLF = ( '\\r'? '\\n' ) ;\n default = ^0 ;\n EOF = 0 ;\n\n # textile modifiers\n A_LEFT = \"<\" %{ ASET(align, left) } ;\n A_RIGHT = \">\" %{ ASET(align, right) } ;\n A_JUSTIFIED = \"<>\" %{ ASET(align, justified) } ;\n A_CENTER = \"=\" %{ ASET(align, center) } ;\n A_PADLEFT = \"(\" >A %{ AINC(padding-left) } ;\n A_PADRIGHT = \")\" >A %{ AINC(padding-right) } ;\n A_HLGN = ( A_LEFT | A_RIGHT | A_JUSTIFIED | A_CENTER | A_PADLEFT | A_PADRIGHT ) ;\n A_LIMIT = ( A_LEFT | A_CENTER | A_RIGHT ) ;\n A_VLGN = ( \"-\" %{ ASET(valign, middle) } | \"^\" %{ ASET(valign, top) } | \"~\" %{ ASET(valign, bottom) } ) ;\n C_CLAS = ( \"(\" ( [^)#]+ >A %{ STORE(class) } )? (\"#\" [^)]+ >A %{STORE(id)} )? \")\" ) ;\n C_LNGE = ( \"[\" [^\\]]+ >A %{ STORE(lang) } \"]\" ) ;\n C_STYL = ( \"{\" [^}]+ >A %{ STORE(style) } \"}\" ) ;\n S_CSPN = ( \"\\\\\" [0-9]+ >A %{ STORE(colspan) } ) ;\n S_RSPN = ( \"\/\" [0-9]+ >A %{ STORE(rowspan) } ) ;\n D_HEADER = \"_\" %{ ASET(th, true) } ;\n A = ( ( A_HLGN | A_VLGN )* ) ;\n A2 = ( A_LIMIT? ) ;\n S = ( S_CSPN | S_RSPN )* ;\n C = ( C_CLAS | C_STYL | C_LNGE )* ;\n D = ( D_HEADER ) ;\n N_CONT = \"_\" %{ ASET(start, continue) };\n N_NUM = digit+ >A %{ STORE(start) };\n N = ( N_CONT | N_NUM )? ;\n PUNCT = ( \"!\" | '\"' | \"#\" | \"$\" | \"%\" | \"&\" | \"'\" | \",\" | \"--\" | \".\" | \"\/\" | \":\" | \";\" | \"=\" | \"?\" | \"\\\\\" | \"^\" | \"`\" | \"|\" | \"~\" | \"[\" | \"(\" | \"<\" ) ;\n dotspace = (\".\" \" \"*) ;\n indent = [ \\t]* ;\n\n # text blocks\n trailing = PUNCT - (\"'\" | '\"') ;\n chars = (default - space)+ ;\n phrase = chars -- trailing ;\n\n # html tags (from Hpricot)\n NameChar = [\\-A-Za-z0-9._:?] ;\n Name = [A-Za-z_:] NameChar* ;\n NameAttr = NameChar+ ;\n Q1Attr = [^']* ;\n Q2Attr = [^\"]* ;\n UnqAttr = ( space | [^ \\t\\r\\n<>\"'] [^ \\t\\r\\n<>]* ) ;\n Nmtoken = NameChar+ ;\n Attr = NameAttr space* \"=\" space* ('\"' Q2Attr '\"' | \"'\" Q1Attr \"'\" | UnqAttr space+ ) space* ;\n AttrEnd = ( NameAttr space* \"=\" space* UnqAttr? | Nmtoken ) ;\n AttrSet = ( Attr | Nmtoken space+ ) ;\n start_tag = \"<\" Name space+ AttrSet* (AttrEnd)? \">\" | \"<\" Name \">\";\n empty_tag = \"<\" Name space+ AttrSet* (AttrEnd)? \"\/>\" | \"<\" Name \"\/>\" ;\n end_tag = \"<\/\" Name space* \">\" ;\n html_comment = \"\";\n\n}%%;\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"4097be1d6e3be9a9ad7b132124c35e5e8d7dc241","subject":"Fixes invalid variable reference","message":"Fixes invalid variable reference","repos":"medcat\/liquidscript,medcat\/liquidscript","old_file":"lib\/liquidscript\/scanner\/lexer.rl","new_file":"lib\/liquidscript\/scanner\/lexer.rl","new_contents":"%%{\n\n machine lexer;\n\n variable data @data;\n variable p @p;\n variable pe @pe;\n variable eof @eof;\n access @;\n\n number_integer = '-'? [0-9][1-9]*;\n number_frac = '.' [0-9]+;\n number_e = ('e' | 'E') ('+' | '-' | '');\n number_exp = number_e [0-9]+;\n number = number_integer number_frac? number_exp?;\n\n string_double = '\"' ( any -- '\"' | '\\\\\"' )* '\"';\n identifier = [A-Za-z_$][A-Za-z0-9_$]*;\n string_single = \"'\" [A-Za-z0-9_$\\-]+;\n\n\n main := |*\n number => { emit :number };\n string_double => { emit :dstring };\n string_single => { emit :sstring };\n identifier => { emit :identifier };\n '->' => { emit :arrow };\n '=' => { emit :equal };\n '{' => { emit :lbrack };\n '(' => { emit :lparen };\n '[' => { emit :lbrace };\n '}' => { emit :rbrack };\n ')' => { emit :rparen };\n ']' => { emit :rbrace };\n ':' => { emit :colon };\n ',' => { emit :comma };\n space => { };\n any => { error };\n *|;\n}%%\n\nmodule Liquidscript\n class Scanner\n\n class Lexer\n\n attr_reader :tokens\n\n def initialize\n %% write data;\n # %% # fix\n @tokens = []\n end\n\n def clean!\n @p = nil\n @pe = nil\n @te = nil\n @ts = nil\n @act = nil\n @eof = nil\n @top = nil\n @data = nil\n @stack = nil\n end\n\n def emit(type)\n @tokens << Token.new(type, @data[@ts..(@te - 1)])\n end\n\n def error\n raise SyntaxError, \"Unexpected #{@data[@ts..(@te-1)].pack('c*')}\"\n end\n\n def perform(data)\n @data = data.unpack(\"c*\") if data.is_a? String\n @eof = data.length\n\n @tokens = []\n\n %% write init;\n %% write exec;\n\n clean!\n\n @tokens\n end\n end\n end\nend\n","old_contents":"%%{\n\n machine lexer;\n\n variable data @data;\n variable p @p;\n variable pe @pe;\n variable eof @eof;\n access @;\n\n number_integer = '-'? [0-9][1-9]*;\n number_frac = '.' [0-9]+;\n number_e = ('e' | 'E') ('+' | '-' | '');\n number_exp = number_e [0-9]+;\n number = number_integer number_frac? number_exp?;\n\n string_double = '\"' ( any -- '\"' | '\\\\\"' )* '\"';\n identifier = [A-Za-z_$][A-Za-z0-9_$]*;\n string_single = \"'\" [A-Za-z0-9_$\\-]+;\n\n\n main := |*\n number => { emit :number };\n string_double => { emit :dstring };\n string_single => { emit :sstring };\n identifier => { emit :identifier };\n '->' => { emit :arrow };\n '=' => { emit :equal };\n '{' => { emit :lbrack };\n '(' => { emit :lparen };\n '[' => { emit :lbrace };\n '}' => { emit :rbrack };\n ')' => { emit :rparen };\n ']' => { emit :rbrace };\n ':' => { emit :colon };\n ',' => { emit :comma };\n space => { };\n any => { error };\n *|;\n}%%\n\nmodule Liquidscript\n class Scanner\n\n class Lexer\n\n attr_reader :tokens\n\n def initialize\n %% write data;\n # %% # fix\n @tokens = []\n end\n\n def clean!\n @p = nil\n @pe = nil\n @te = nil\n @ts = nil\n @act = nil\n @eof = nil\n @top = nil\n @data = nil\n @stack = nil\n end\n\n def emit(type)\n @tokens << Token.new(type, @data[@ts..(@te - 1)])\n end\n\n def error\n raise SyntaxError, \"Unexpected #{@data[ts..(te-1)].pack('c*')}\"\n end\n\n def perform(data)\n @data = data.unpack(\"c*\") if data.is_a? String\n @eof = data.length\n\n @tokens = []\n\n %% write init;\n %% write exec;\n\n clean!\n\n @tokens\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"23f19c85fcb343dd422bc8cfc6eb147213192bb3","subject":"simplify","message":"simplify\n","repos":"razum2um\/params_tree","old_file":"hello_world.rl","new_file":"hello_world.rl","new_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ',' >H@T @{ log(:delimiter) };\n LEVEL = '('+ >H@T @{ log(:level) };\n END_LEVEL = ')'+ >H@T @{ log(:end_level); };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER? @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n #@hash.inspect\n #@hash_stack.inspect\n @hash_stack.first\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\ns = \"default(all,usadasdid(zczxc(pio(xqwe)),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\nputs s\nputs ParamsTree::Parser.new.process s\n","old_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ]) >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER? @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n #@hash.inspect\n #@hash_stack.inspect\n @hash_stack.first\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\ns = \"default(all,usadasdid(zczxc(pio(xqwe)),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\nputs s\nputs ParamsTree::Parser.new.process s\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"199d8f0a19a4ef24c7b086eff68c45486f894cab","subject":"Updated Rapa source to 36f91258.","message":"Updated Rapa source to 36f91258.\n","repos":"dblock\/rubinius,travis-repos\/rubinius,slawosz\/rubinius,sferik\/rubinius,kachick\/rubinius,Wirachmat\/rubinius,jemc\/rubinius,jsyeo\/rubinius,digitalextremist\/rubinius,ngpestelos\/rubinius,Wirachmat\/rubinius,benlovell\/rubinius,sferik\/rubinius,dblock\/rubinius,lgierth\/rubinius,ngpestelos\/rubinius,jsyeo\/rubinius,Wirachmat\/rubinius,digitalextremist\/rubinius,kachick\/rubinius,ruipserra\/rubinius,jsyeo\/rubinius,sferik\/rubinius,Azizou\/rubinius,ruipserra\/rubinius,Azizou\/rubinius,slawosz\/rubinius,slawosz\/rubinius,digitalextremist\/rubinius,dblock\/rubinius,sferik\/rubinius,jemc\/rubinius,benlovell\/rubinius,jemc\/rubinius,mlarraz\/rubinius,mlarraz\/rubinius,mlarraz\/rubinius,kachick\/rubinius,heftig\/rubinius,lgierth\/rubinius,lgierth\/rubinius,lgierth\/rubinius,mlarraz\/rubinius,travis-repos\/rubinius,benlovell\/rubinius,Wirachmat\/rubinius,travis-repos\/rubinius,Azizou\/rubinius,heftig\/rubinius,ngpestelos\/rubinius,jsyeo\/rubinius,benlovell\/rubinius,ruipserra\/rubinius,pH14\/rubinius,Azizou\/rubinius,travis-repos\/rubinius,jemc\/rubinius,digitalextremist\/rubinius,pH14\/rubinius,ngpestelos\/rubinius,heftig\/rubinius,kachick\/rubinius,travis-repos\/rubinius,heftig\/rubinius,sferik\/rubinius,digitalextremist\/rubinius,sferik\/rubinius,lgierth\/rubinius,ruipserra\/rubinius,mlarraz\/rubinius,pH14\/rubinius,pH14\/rubinius,Azizou\/rubinius,jemc\/rubinius,kachick\/rubinius,Azizou\/rubinius,benlovell\/rubinius,ruipserra\/rubinius,jsyeo\/rubinius,slawosz\/rubinius,digitalextremist\/rubinius,dblock\/rubinius,pH14\/rubinius,lgierth\/rubinius,kachick\/rubinius,Wirachmat\/rubinius,heftig\/rubinius,slawosz\/rubinius,dblock\/rubinius,jemc\/rubinius,travis-repos\/rubinius,benlovell\/rubinius,mlarraz\/rubinius,heftig\/rubinius,travis-repos\/rubinius,digitalextremist\/rubinius,jemc\/rubinius,benlovell\/rubinius,Wirachmat\/rubinius,jsyeo\/rubinius,kachick\/rubinius,Wirachmat\/rubinius,sferik\/rubinius,ngpestelos\/rubinius,ngpestelos\/rubinius,kachick\/rubinius,ruipserra\/rubinius,heftig\/rubinius,slawosz\/rubinius,pH14\/rubinius,lgierth\/rubinius,ruipserra\/rubinius,dblock\/rubinius,ngpestelos\/rubinius,jsyeo\/rubinius,dblock\/rubinius,Azizou\/rubinius,slawosz\/rubinius,mlarraz\/rubinius,pH14\/rubinius","old_file":"projects\/rapa\/actions\/rubinius\/unpack_actions.rl","new_file":"projects\/rapa\/actions\/rubinius\/unpack_actions.rl","new_contents":"\/\/ vim: filetype=ragel\n\n%%{\n\n machine unpack;\n\n action start {\n count = 1;\n rest = false;\n platform = false;\n }\n\n action start_digit {\n count = fc - '0';\n }\n\n action count {\n count = count * 10 + (fc - '0');\n }\n\n action rest {\n count = 0;\n rest = true;\n }\n\n action zero_count {\n count = 0;\n }\n\n action platform {\n platform = true;\n }\n\n action byte_width {\n width = 1;\n }\n\n action short_width {\n width = 2;\n }\n\n action int_width {\n width = 4;\n }\n\n action long_width {\n width = 8;\n }\n\n action platform_width {\n if(platform) {\n#if RBX_SIZEOF_LONG == 4\n width = 4;\n#else\n width = 8;\n#endif\n } else {\n width = 4;\n }\n }\n\n action set_stop {\n if(!rest) {\n stop = index + width * count;\n }\n\n if(rest || stop > bytes_size) {\n stop = index + ((bytes_size - index) \/ width) * width;\n }\n }\n\n action extra {\n for(; count > 0; count--) {\n array->append(state, Qnil);\n }\n }\n\n # Integers\n\n action C {\n unpack_integer(ubyte);\n }\n\n action c {\n unpack_integer(sbyte);\n }\n\n action S {\n unpack_integer(u2bytes);\n }\n\n action s {\n unpack_integer(s2bytes);\n }\n\n action I {\n unpack_integer(u4bytes);\n }\n\n action i {\n unpack_integer(s4bytes);\n }\n\n action L {\n if(platform) {\n#if RBX_SIZEOF_LONG == 4\n unpack_integer(u4bytes);\n#else\n unpack_integer(u8bytes);\n#endif\n } else {\n unpack_integer(u4bytes);\n }\n }\n\n action l {\n if(platform) {\n#if RBX_SIZEOF_LONG == 4\n unpack_integer(s4bytes);\n#else\n unpack_integer(s8bytes);\n#endif\n } else {\n unpack_integer(s4bytes);\n }\n }\n\n action N {\n unpack_integer(u4bytes_be);\n }\n\n action n {\n unpack_integer(u2bytes_be);\n }\n\n action V {\n unpack_integer(u4bytes_le);\n }\n\n action v {\n unpack_integer(u2bytes_le);\n }\n\n action Q {\n unpack_integer(u8bytes);\n }\n\n action q {\n unpack_integer(s8bytes);\n }\n\n # Floats\n\n action D {\n unpack_double;\n }\n\n action E {\n unpack_double_le;\n }\n\n action e {\n unpack_float_le;\n }\n\n action F {\n unpack_float;\n }\n\n action G {\n unpack_double_be;\n }\n\n action g {\n unpack_float_be;\n }\n\n # Moves\n\n action X {\n if(rest) count = bytes_size - index;\n index -= count;\n }\n\n action x {\n if(rest) {\n index = bytes_size;\n } else {\n index += count;\n }\n }\n\n action at {\n if(!rest) {\n index = count;\n }\n }\n\n action check_bounds {\n if(index < 0 || index > bytes_size) {\n std::ostringstream msg;\n msg << *p << \" outside of string\";\n Exception::argument_error(state, msg.str().c_str());\n }\n }\n\n # String \/ Encoding helpers\n\n action bytes {\n bytes = (const char*)self->byte_address() + index;\n }\n\n action bytes_end {\n bytes_end = (const char*)self->byte_address() + bytes_size;\n }\n\n action string_width {\n width = 1;\n }\n\n action bit_width {\n width = 8;\n }\n\n action hex_width {\n width = 2;\n }\n\n action remainder {\n remainder = bytes_size - index;\n }\n\n action rest_count {\n if(rest) {\n count = remainder;\n } else if(count > remainder) {\n count = remainder;\n }\n }\n\n action string_size {\n if(rest || count > remainder * width) {\n count = remainder * width;\n }\n }\n\n # Strings\n\n action A {\n String* string;\n\n if(count > 0) {\n native_int i;\n for(i = count; i > 0; i--) {\n uint8_t c = bytes[i-1];\n if(c != ' ' && c != '\\0')\n break;\n }\n string = String::create(state, bytes, i);\n } else {\n string = String::create(state, \"\");\n }\n\n array->append(state, string);\n unpack::increment(index, count, bytes_size);\n }\n\n action a {\n array->append(state, String::create(state, bytes, count));\n\n unpack::increment(index, count, bytes_size);\n }\n\n action Z {\n native_int c;\n for(c = 0; c < count; c++) {\n if(bytes[c] == '\\0') break;\n }\n array->append(state, String::create(state, bytes, c));\n\n if(rest) {\n unpack::increment(index, c < count ? c + 1 : count, bytes_size);\n } else {\n unpack::increment(index, count, bytes_size);\n }\n }\n\n # Encodings\n\n action index_increment {\n unpack::increment(index,\n bytes - ((const char*)self->byte_address() + index),\n bytes_size);\n }\n\n action B {\n array->append(state, unpack::bit_high(state, bytes, count));\n }\n\n action b {\n array->append(state, unpack::bit_low(state, bytes, count));\n }\n\n action H {\n array->append(state, unpack::hex_high(state, bytes, count));\n }\n\n action h {\n array->append(state, unpack::hex_low(state, bytes, count));\n }\n\n action M {\n array->append(state, unpack::quotable_printable(state, bytes, bytes_end, remainder));\n }\n\n action m {\n array->append(state, unpack::base64_decode(state, bytes, bytes_end, remainder));\n }\n\n action U {\n unpack::utf8_decode(state, array, bytes, bytes_end, count, index);\n }\n\n action u {\n array->append(state, unpack::uu_decode(state, bytes, bytes_end, remainder));\n }\n\n action w {\n unpack::ber_decode(state, array, bytes, bytes_end, count, index);\n index = bytes - (const char*)self->byte_address();\n }\n\n action non_native_error {\n std::ostringstream msg;\n msg << \"'\" << *p << \"' allowed only after types sSiIlL\";\n Exception::argument_error(state, msg.str().c_str());\n }\n\n action done {\n return array;\n }\n}%%\n","old_contents":"\/\/ vim: filetype=ragel\n\n%%{\n\n machine unpack;\n\n action start {\n count = 1;\n rest = false;\n platform = false;\n }\n\n action start_digit {\n count = fc - '0';\n }\n\n action count {\n count = count * 10 + (fc - '0');\n }\n\n action rest {\n count = 0;\n rest = true;\n }\n\n action zero_count {\n count = 0;\n }\n\n action platform {\n platform = true;\n }\n\n action byte_width {\n width = 1;\n }\n\n action short_width {\n width = 2;\n }\n\n action int_width {\n width = 4;\n }\n\n action long_width {\n width = 8;\n }\n\n action platform_width {\n if(platform) {\n#if RBX_SIZEOF_LONG == 4\n width = 4;\n#else\n width = 8;\n#endif\n } else {\n width = 4;\n }\n }\n\n action set_stop {\n stop = rest ? bytes_size + 1 : index + width * count;\n if(stop > bytes_size) {\n stop = index + ((bytes_size - index) \/ width) * width;\n }\n }\n\n action extra {\n for(; count > 0; count--) {\n array->append(state, Qnil);\n }\n }\n\n # Integers\n\n action C {\n unpack_integer(ubyte);\n }\n\n action c {\n unpack_integer(sbyte);\n }\n\n action S {\n unpack_integer(u2bytes);\n }\n\n action s {\n unpack_integer(s2bytes);\n }\n\n action I {\n unpack_integer(u4bytes);\n }\n\n action i {\n unpack_integer(s4bytes);\n }\n\n action L {\n if(platform) {\n#if RBX_SIZEOF_LONG == 4\n unpack_integer(u4bytes);\n#else\n unpack_integer(u8bytes);\n#endif\n } else {\n unpack_integer(u4bytes);\n }\n }\n\n action l {\n if(platform) {\n#if RBX_SIZEOF_LONG == 4\n unpack_integer(s4bytes);\n#else\n unpack_integer(s8bytes);\n#endif\n } else {\n unpack_integer(s4bytes);\n }\n }\n\n action N {\n unpack_integer(u4bytes_be);\n }\n\n action n {\n unpack_integer(u2bytes_be);\n }\n\n action V {\n unpack_integer(u4bytes_le);\n }\n\n action v {\n unpack_integer(u2bytes_le);\n }\n\n action Q {\n unpack_integer(u8bytes);\n }\n\n action q {\n unpack_integer(s8bytes);\n }\n\n # Floats\n\n action D {\n unpack_double;\n }\n\n action E {\n unpack_double_le;\n }\n\n action e {\n unpack_float_le;\n }\n\n action F {\n unpack_float;\n }\n\n action G {\n unpack_double_be;\n }\n\n action g {\n unpack_float_be;\n }\n\n # Moves\n\n action X {\n if(rest) count = bytes_size - index;\n index -= count;\n }\n\n action x {\n if(rest) {\n index = bytes_size;\n } else {\n index += count;\n }\n }\n\n action at {\n if(!rest) {\n index = count;\n }\n }\n\n action check_bounds {\n if(index < 0 || index > bytes_size) {\n std::ostringstream msg;\n msg << *p << \" outside of string\";\n Exception::argument_error(state, msg.str().c_str());\n }\n }\n\n # String \/ Encoding helpers\n\n action bytes {\n bytes = (const char*)self->byte_address() + index;\n }\n\n action bytes_end {\n bytes_end = (const char*)self->byte_address() + bytes_size;\n }\n\n action string_width {\n width = 1;\n }\n\n action bit_width {\n width = 8;\n }\n\n action hex_width {\n width = 2;\n }\n\n action remainder {\n remainder = bytes_size - index;\n }\n\n action rest_count {\n if(rest) {\n count = remainder;\n } else if(count > remainder) {\n count = remainder;\n }\n }\n\n action string_size {\n if(rest || count > remainder * width) {\n count = remainder * width;\n }\n }\n\n # Strings\n\n action A {\n String* string;\n\n if(count > 0) {\n native_int i;\n for(i = count; i > 0; i--) {\n uint8_t c = bytes[i-1];\n if(c != ' ' && c != '\\0')\n break;\n }\n string = String::create(state, bytes, i);\n } else {\n string = String::create(state, \"\");\n }\n\n array->append(state, string);\n unpack::increment(index, count, bytes_size);\n }\n\n action a {\n array->append(state, String::create(state, bytes, count));\n\n unpack::increment(index, count, bytes_size);\n }\n\n action Z {\n native_int c;\n for(c = 0; c < count; c++) {\n if(bytes[c] == '\\0') break;\n }\n array->append(state, String::create(state, bytes, c));\n\n if(rest) {\n unpack::increment(index, c < count ? c + 1 : count, bytes_size);\n } else {\n unpack::increment(index, count, bytes_size);\n }\n }\n\n # Encodings\n\n action index_increment {\n unpack::increment(index,\n bytes - ((const char*)self->byte_address() + index),\n bytes_size);\n }\n\n action B {\n array->append(state, unpack::bit_high(state, bytes, count));\n }\n\n action b {\n array->append(state, unpack::bit_low(state, bytes, count));\n }\n\n action H {\n array->append(state, unpack::hex_high(state, bytes, count));\n }\n\n action h {\n array->append(state, unpack::hex_low(state, bytes, count));\n }\n\n action M {\n array->append(state, unpack::quotable_printable(state, bytes, bytes_end, remainder));\n }\n\n action m {\n array->append(state, unpack::base64_decode(state, bytes, bytes_end, remainder));\n }\n\n action U {\n unpack::utf8_decode(state, array, bytes, bytes_end, count, index);\n }\n\n action u {\n array->append(state, unpack::uu_decode(state, bytes, bytes_end, remainder));\n }\n\n action w {\n unpack::ber_decode(state, array, bytes, bytes_end, count, index);\n index = bytes - (const char*)self->byte_address();\n }\n\n action non_native_error {\n std::ostringstream msg;\n msg << \"'\" << *p << \"' allowed only after types sSiIlL\";\n Exception::argument_error(state, msg.str().c_str());\n }\n\n action done {\n return array;\n }\n}%%\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"9b74ea00cf739338d856a8bd712b7421347dd6f6","subject":"Check for final state of correct state machine.","message":"Check for final state of correct state machine.\n","repos":"damballa\/inet.data,damballa\/inet.data","old_file":"src\/ragel\/inet\/data\/dns\/DNSDomainParser.java.rl","new_file":"src\/ragel\/inet\/data\/dns\/DNSDomainParser.java.rl","new_contents":"package inet.data.dns;\n\npublic class DNSDomainParser {\n\npublic static final int MAX_DOMAIN_LENGTH = 255;\npublic static final int MAX_LABEL_LENGTH = 63;\n\n%% machine domain;\n%% write data;\n\npublic static boolean\nisValid(byte[] data) {\n if (data.length > MAX_DOMAIN_LENGTH)\n return false;\n\n int lablen = 0;\n\n int cs = 0;\n int p = 0;\n int pe = data.length;\n int eof = pe;\n\n %%{\n action beg_label { lablen = ((int) fc) & 0xff; }\n action in_label { (lablen-- > 0) }\n action not_in_label { (lablen <= 0) }\n\n lablen = 1..63 $beg_label;\n content = ( any when in_label )+;\n terminal = '' when not_in_label;\n label = lablen content <: terminal;\n domain = label+;\n\n main := domain;\n\n alphtype byte;\n }%%\n\n %% write init;\n %% write exec;\n\n if (cs < domain_first_final || lablen > 0)\n return false;\n return true;\n}\n\n\n%% machine hostname;\n%% write data;\n\npublic static boolean\nisValidHostname(byte[] data, int length, boolean underscores) {\n if (length > MAX_DOMAIN_LENGTH)\n return false;\n\n int lablen = 0;\n boolean letter = false;\n\n int cs = 0;\n int p = 0;\n int pe = length;\n int eof = pe;\n\n %%{\n action beg_label { lablen = ((int) fc) & 0xff; }\n action in_label { (lablen-- > 0) }\n action not_in_label { (lablen <= 0) }\n action underscores { underscores }\n action letter { letter = true; }\n\n lablen = 1..63 $beg_label;\n let = ( alpha when in_label ) $letter;\n dig = digit when in_label;\n let_dig = let | dig;\n hyp = ( \"-\" | \"_\" when underscores ) when in_label;\n let_dig_hyp = let_dig | hyp;\n ldh_str = let_dig_hyp+;\n content = let_dig (ldh_str? let_dig)?;\n terminal = '' when not_in_label;\n label = lablen content <: terminal;\n domain = label+;\n\n main := domain;\n\n alphtype byte;\n }%%\n\n %% write init;\n %% write exec;\n\n if (cs < hostname_first_final || lablen > 0 || !letter)\n return false;\n return true;\n}\n\n}\n","old_contents":"package inet.data.dns;\n\npublic class DNSDomainParser {\n\npublic static final int MAX_DOMAIN_LENGTH = 255;\npublic static final int MAX_LABEL_LENGTH = 63;\n\n%% machine domain;\n%% write data;\n\npublic static boolean\nisValid(byte[] data) {\n if (data.length > MAX_DOMAIN_LENGTH)\n return false;\n\n int lablen = 0;\n\n int cs = 0;\n int p = 0;\n int pe = data.length;\n int eof = pe;\n\n %%{\n action beg_label { lablen = ((int) fc) & 0xff; }\n action in_label { (lablen-- > 0) }\n action not_in_label { (lablen <= 0) }\n\n lablen = 1..63 $beg_label;\n content = ( any when in_label )+;\n terminal = '' when not_in_label;\n label = lablen content <: terminal;\n domain = label+;\n\n main := domain;\n\n alphtype byte;\n }%%\n\n %% write init;\n %% write exec;\n\n if (cs < domain_first_final || lablen > 0)\n return false;\n return true;\n}\n\n\n%% machine hostname;\n%% write data;\n\npublic static boolean\nisValidHostname(byte[] data, int length, boolean underscores) {\n if (length > MAX_DOMAIN_LENGTH)\n return false;\n\n int lablen = 0;\n boolean letter = false;\n\n int cs = 0;\n int p = 0;\n int pe = length;\n int eof = pe;\n\n %%{\n action beg_label { lablen = ((int) fc) & 0xff; }\n action in_label { (lablen-- > 0) }\n action not_in_label { (lablen <= 0) }\n action underscores { underscores }\n action letter { letter = true; }\n\n lablen = 1..63 $beg_label;\n let = ( alpha when in_label ) $letter;\n dig = digit when in_label;\n let_dig = let | dig;\n hyp = ( \"-\" | \"_\" when underscores ) when in_label;\n let_dig_hyp = let_dig | hyp;\n ldh_str = let_dig_hyp+;\n content = let_dig (ldh_str? let_dig)?;\n terminal = '' when not_in_label;\n label = lablen content <: terminal;\n domain = label+;\n\n main := domain;\n\n alphtype byte;\n }%%\n\n %% write init;\n %% write exec;\n\n if (cs < domain_first_final || lablen > 0 || !letter)\n return false;\n return true;\n}\n\n}\n","returncode":0,"stderr":"","license":"epl-1.0","lang":"Ragel in Ruby Host"} {"commit":"f1a27f4dc9e053ab1bccef7c877ec5979f8db07f","subject":"include stdint.h for inptr_t","message":"include stdint.h for inptr_t\n","repos":"wahern\/dns,wahern\/dns","old_file":"src\/spf.rl","new_file":"src\/spf.rl","new_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf setjmp(3) longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\nint spf_debug = SPF_DEBUG - 1;\n\n#undef SPF_DEBUG\n#define SPF_DEBUG(N) (spf_debug >= (N))\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (SPF_DEBUG(1)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#define SPF_TRACE(retval, ...) ({ if (SPF_DEBUG(2)) SPF_SAY(__VA_ARGS__); (retval); })\n#else\n#undef SPF_DEBUG\n#define SPF_DEBUG(N) 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#define SPF_TRACE(retval, ...) (retval)\n#endif \/* SPF_DEBUG *\/\n\n\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned spf_atoi(const char *src) {\n\tunsigned i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_inetcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_inetcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG(1)) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\t\/\/SPF_TRACE(1, \"term -> %s\", term_comp(&(struct spf_sbuf){ 0 }, term));\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-1) == S(-2) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_STRCAT,\n\tOP_PRINTI,\n\tOP_PRINTS,\n\tOP_PRINTP,\n\tOP_PRINTAI,\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\tlongjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (!(cond)) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic int vm_indexof(struct spf_vm *vm, int p) {\n\tif (p < 0)\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, t & vm_typeof(vm, p), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tchar *s;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\ts = (char *)v_;\n\t\tn = strlen(s) + 1;\n\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], s, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define STRCAT(sub) sub_emit((sub), OP_STRCAT)\n#define PRINTI(sub) sub_emit((sub), OP_PRINTI)\n#define PRINTS(sub) sub_emit((sub), OP_PRINTS)\n#define PRINTP(sub) sub_emit((sub), OP_PRINTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tfor (i = 0; i < n; i++) {\n\t\tvm_assert(vm, ++vm->pc < vm->end, EFAULT);\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pc = ++vm->pc;\n\n\twhile (pc < spf_lengthof(vm->code) && vm->code[pc])\n\t\tpc++;\n\n\tvm_assert(vm, pc < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[vm->pc], ++pc - vm->pc);\n\n\tvm->pc = pc;\n} \/* op_str() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tSTRCAT(&sub);\n\t\tPRINTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPRINTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tSTRCAT(&sub);\n\tPRINTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_inetcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PRINTAI);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_inetcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_strcat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-3] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -3))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -3, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -3, T_ANY));\n\n\t\/* Print [-1] as string or character code *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_putc(&sbuf, vm_peek(vm, -1, T_INT));\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 3);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_strcat() *\/\n\n\nstatic void op_printi(struct spf_vm *vm) {\n\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_printi() *\/\n\n\nstatic void op_prints(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_prints() *\/\n\n\nstatic void op_printp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_printp() *\/\n\n\nstatic void op_printai(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_printai() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_STRCAT] = { \"strcat\", &op_strcat, },\n\t[OP_PRINTI] = { \"printi\", &op_printi, },\n\t[OP_PRINTS] = { \"prints\", &op_prints, },\n\t[OP_PRINTP] = { \"printp\", &op_printp, },\n\t[OP_PRINTAI] = { \"printai\", &op_printai, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (SPF_DEBUG(2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic size_t rtrim(char *str) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && isspace((unsigned char)str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* rtrim() *\/\n\nstatic int vm(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, stdin)) {\n\t\trtrim(line);\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, 0, 0));\n\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t}\n\t\t}\n\t} \/* while() *\/\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG(2)) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG(2)) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\n\tspf_debug = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.r, \"unknown\", sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'I':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'C':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc)\n\t\tgoto usage;\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\n\t\treturn vm(argc - 1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","old_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf setjmp(3) longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\nint spf_debug = SPF_DEBUG - 1;\n\n#undef SPF_DEBUG\n#define SPF_DEBUG(N) (spf_debug >= (N))\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (SPF_DEBUG(1)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#define SPF_TRACE(retval, ...) ({ if (SPF_DEBUG(2)) SPF_SAY(__VA_ARGS__); (retval); })\n#else\n#undef SPF_DEBUG\n#define SPF_DEBUG(N) 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#define SPF_TRACE(retval, ...) (retval)\n#endif \/* SPF_DEBUG *\/\n\n\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned spf_atoi(const char *src) {\n\tunsigned i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_inetcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_inetcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG(1)) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\t\/\/SPF_TRACE(1, \"term -> %s\", term_comp(&(struct spf_sbuf){ 0 }, term));\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-1) == S(-2) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_STRCAT,\n\tOP_PRINTI,\n\tOP_PRINTS,\n\tOP_PRINTP,\n\tOP_PRINTAI,\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\tlongjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (!(cond)) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic int vm_indexof(struct spf_vm *vm, int p) {\n\tif (p < 0)\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, t & vm_typeof(vm, p), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tchar *s;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\ts = (char *)v_;\n\t\tn = strlen(s) + 1;\n\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], s, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define STRCAT(sub) sub_emit((sub), OP_STRCAT)\n#define PRINTI(sub) sub_emit((sub), OP_PRINTI)\n#define PRINTS(sub) sub_emit((sub), OP_PRINTS)\n#define PRINTP(sub) sub_emit((sub), OP_PRINTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tfor (i = 0; i < n; i++) {\n\t\tvm_assert(vm, ++vm->pc < vm->end, EFAULT);\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pc = ++vm->pc;\n\n\twhile (pc < spf_lengthof(vm->code) && vm->code[pc])\n\t\tpc++;\n\n\tvm_assert(vm, pc < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[vm->pc], ++pc - vm->pc);\n\n\tvm->pc = pc;\n} \/* op_str() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tSTRCAT(&sub);\n\t\tPRINTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPRINTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tSTRCAT(&sub);\n\tPRINTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_inetcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PRINTAI);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_inetcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_strcat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-3] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -3))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -3, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -3, T_ANY));\n\n\t\/* Print [-1] as string or character code *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_putc(&sbuf, vm_peek(vm, -1, T_INT));\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 3);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_strcat() *\/\n\n\nstatic void op_printi(struct spf_vm *vm) {\n\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_printi() *\/\n\n\nstatic void op_prints(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_prints() *\/\n\n\nstatic void op_printp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_printp() *\/\n\n\nstatic void op_printai(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_printai() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_STRCAT] = { \"strcat\", &op_strcat, },\n\t[OP_PRINTI] = { \"printi\", &op_printi, },\n\t[OP_PRINTS] = { \"prints\", &op_prints, },\n\t[OP_PRINTP] = { \"printp\", &op_printp, },\n\t[OP_PRINTAI] = { \"printai\", &op_printai, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (SPF_DEBUG(2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic size_t rtrim(char *str) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && isspace((unsigned char)str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* rtrim() *\/\n\nstatic int vm(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, stdin)) {\n\t\trtrim(line);\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, 0, 0));\n\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t}\n\t\t}\n\t} \/* while() *\/\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG(2)) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG(2)) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\n\tspf_debug = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.r, \"unknown\", sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'I':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'C':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc)\n\t\tgoto usage;\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\n\t\treturn vm(argc - 1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"7bb900e6e8af661d3b0ed2e654e456fa9e036dad","subject":"Improve SSA parsing for files with stray [ in them.","message":"Improve SSA parsing for files with stray [ in them.\n","repos":"MaddTheSane\/perian,MaddTheSane\/perian,JanX2\/Perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,JanX2\/Perian,JanX2\/Perian,JanX2\/Perian,JanX2\/Perian","old_file":"Subtitles\/SubParsing.m.rl","new_file":"Subtitles\/SubParsing.m.rl","new_contents":"\/*\n * SubParsing.c\n * SSARender2\n *\n * Created by Alexander Strange on 7\/25\/07.\n * Copyright 2007 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize {[delegate releaseSpanExtra:ex]; [super finalize];}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tis_shape = positioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n div->is_shape = NO;\n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(const unichar *ssa, size_t len, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n#define send() [NSString stringWithCharacters:strbegin length:p-strbegin]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic NSMutableString *FilterSlashEscapes(NSMutableString *s)\n{\n\t[s replaceOccurrencesOfString:@\"\\\\n\" withString:@\"\\n\" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];\n\tunichar nbsp = 0xA0;\n\t\n\t[s replaceOccurrencesOfString:@\"\\\\h\" withString:[NSString stringWithCharacters:  length:1] options:0 range: NSMakeRange(0,[s length])];\n\treturn s;\n}\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = a, *divB = b;\n\t\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate, unichar *linebuf)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n\t\tsize_t linelen = [inputText length];\n\t\t[inputText getCharacters:linebuf];\n\t\tlinebuf[linelen] = 0;\n\t\t\n#undef send\n#define send() [NSString stringWithCharacters:outputbegin length:p-outputbegin]\n#define psend() [NSString stringWithCharacters:parambegin length:p-parambegin]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tunichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_cmd_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; int intnum = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tunsigned curX, curY;\n\t\t\tBOOL reached_end = NO, startNewLayout = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction setxypos {curX=curY=-1; sscanf([psend() UTF8String], \"(%d,%d)\", &curX, &curY);}\n\t\t\t\t\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (outputbegin == pb) ParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (outputbegin == pb) ParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!startNewLayout) {\n\t\t\t\t\t\tstartNewLayout = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([div->text length] > 0) {[divs addObject:div]; div = [div nextDivWithDelegate:delegate];}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tdiv->wrapStyle = intnum;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!startNewLayout) {\n\t\t\t\t\t\tstartNewLayout = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([div->text length] > 0) {[divs addObject:div]; div = [div nextDivWithDelegate:delegate];}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatnum = ([0-9]+ (\".\" [0-9]*)?) >paramset %setfloatnum;\n\t\t\t\tstring = ([^\\\\}]*) >paramset %setstringval;\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\txypos = (\"(\" \"-\"? [0-9]+ \",\" \"-\"? [0-9]+ \")\") >paramset %setxypos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum %frx\n\t\t\t\t\t\t\t|\"fry\" floatnum %fry\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" xypos %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\tcmd_list = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\t[div->text appendString:send()];\t\t\t\t\t\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\to = c;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\toutputbegin = p+2;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\t\t\t\t\t\n\t\t\t\t\tif (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\tcurrent_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_cmd_start = p;\n\t\t\t\t\tif (p == pe) reached_end = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_cmd_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tif (startNewLayout) {\n\t\t\t\t\t\tstartNewLayout = NO;\n\t\t\t\t\t\tchars_deleted = outputbegin - pb;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" any) >backslash_handler | cmd_list >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char*;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reached_end) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","old_contents":"\/*\n * SubParsing.c\n * SSARender2\n *\n * Created by Alexander Strange on 7\/25\/07.\n * Copyright 2007 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize {[delegate releaseSpanExtra:ex]; [super finalize];}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tis_shape = positioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n div->is_shape = NO;\n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(const unichar *ssa, size_t len, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n#define send() [NSString stringWithCharacters:strbegin length:p-strbegin]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header :> styles :> lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic NSMutableString *FilterSlashEscapes(NSMutableString *s)\n{\n\t[s replaceOccurrencesOfString:@\"\\\\n\" withString:@\"\\n\" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];\n\tunichar nbsp = 0xA0;\n\t\n\t[s replaceOccurrencesOfString:@\"\\\\h\" withString:[NSString stringWithCharacters:  length:1] options:0 range: NSMakeRange(0,[s length])];\n\treturn s;\n}\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = a, *divB = b;\n\t\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate, unichar *linebuf)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n\t\tsize_t linelen = [inputText length];\n\t\t[inputText getCharacters:linebuf];\n\t\tlinebuf[linelen] = 0;\n\t\t\n#undef send\n#define send() [NSString stringWithCharacters:outputbegin length:p-outputbegin]\n#define psend() [NSString stringWithCharacters:parambegin length:p-parambegin]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tunichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_cmd_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; int intnum = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tunsigned curX, curY;\n\t\t\tBOOL reached_end = NO, startNewLayout = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction setxypos {curX=curY=-1; sscanf([psend() UTF8String], \"(%d,%d)\", &curX, &curY);}\n\t\t\t\t\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (outputbegin == pb) ParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (outputbegin == pb) ParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!startNewLayout) {\n\t\t\t\t\t\tstartNewLayout = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([div->text length] > 0) {[divs addObject:div]; div = [div nextDivWithDelegate:delegate];}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tdiv->wrapStyle = intnum;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!startNewLayout) {\n\t\t\t\t\t\tstartNewLayout = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([div->text length] > 0) {[divs addObject:div]; div = [div nextDivWithDelegate:delegate];}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatnum = ([0-9]+ (\".\" [0-9]*)?) >paramset %setfloatnum;\n\t\t\t\tstring = ([^\\\\}]*) >paramset %setstringval;\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\txypos = (\"(\" \"-\"? [0-9]+ \",\" \"-\"? [0-9]+ \")\") >paramset %setxypos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum %frx\n\t\t\t\t\t\t\t|\"fry\" floatnum %fry\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" xypos %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\tcmd_list = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\t[div->text appendString:send()];\t\t\t\t\t\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\to = c;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\toutputbegin = p+2;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\t\t\t\t\t\n\t\t\t\t\tif (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\tcurrent_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_cmd_start = p;\n\t\t\t\t\tif (p == pe) reached_end = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_cmd_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tif (startNewLayout) {\n\t\t\t\t\t\tstartNewLayout = NO;\n\t\t\t\t\t\tchars_deleted = outputbegin - pb;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" any) >backslash_handler | cmd_list >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char*;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reached_end) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"4ebc16fc5f36e32173399ae0ef5e3dcb0f86d268","subject":"Fix(Lexer) use Ruby #empty? instead of Rails #blank?","message":"Fix(Lexer) use Ruby #empty? instead of Rails #blank?\n","repos":"nevesenin\/graphql-ruby,xuorig\/graphql-ruby,nevesenin\/graphql-ruby,nevesenin\/graphql-ruby,rmosolgo\/graphql-ruby,xuorig\/graphql-ruby,nevesenin\/graphql-ruby,xuorig\/graphql-ruby,rmosolgo\/graphql-ruby,rmosolgo\/graphql-ruby,rmosolgo\/graphql-ruby","old_file":"lib\/graphql\/language\/lexer.rl","new_file":"lib\/graphql\/language\/lexer.rl","new_contents":"%%{\n machine graphql_lexer;\n\n IDENTIFIER = [_A-Za-z][_0-9A-Za-z]*;\n NEWLINE = [\\c\\r\\n];\n BLANK = [, \\t]+;\n COMMENT = '#' [^\\n\\r]*;\n INT = '-'? ('0'|[1-9][0-9]*);\n FLOAT_DECIMAL = '.'[0-9]+;\n FLOAT_EXP = ('e' | 'E')?('+' | '-')?[0-9]+;\n FLOAT = INT FLOAT_DECIMAL? FLOAT_EXP?;\n ON = 'on';\n FRAGMENT = 'fragment';\n TRUE = 'true';\n FALSE = 'false';\n NULL = 'null';\n QUERY = 'query';\n MUTATION = 'mutation';\n SUBSCRIPTION = 'subscription';\n SCHEMA = 'schema';\n SCALAR = 'scalar';\n TYPE = 'type';\n IMPLEMENTS = 'implements';\n INTERFACE = 'interface';\n UNION = 'union';\n ENUM = 'enum';\n INPUT = 'input';\n DIRECTIVE = 'directive';\n LCURLY = '{';\n RCURLY = '}';\n LPAREN = '(';\n RPAREN = ')';\n LBRACKET = '[';\n RBRACKET = ']';\n COLON = ':';\n QUOTE = '\"';\n BLOCK_QUOTE = '\"\"\"';\n ESCAPED_BLOCK_QUOTE = '\\\\\"\"\"';\n BLOCK_STRING_CHAR = (ESCAPED_BLOCK_QUOTE | ^'\"\"\"');\n ESCAPED_QUOTE = '\\\\\"';\n STRING_CHAR = (ESCAPED_QUOTE | ^'\"');\n VAR_SIGN = '$';\n DIR_SIGN = '@';\n ELLIPSIS = '...';\n EQUALS = '=';\n BANG = '!';\n PIPE = '|';\n\n QUOTED_STRING = QUOTE STRING_CHAR* QUOTE;\n BLOCK_STRING = BLOCK_QUOTE BLOCK_STRING_CHAR* BLOCK_QUOTE;\n # catch-all for anything else. must be at the bottom for precedence.\n UNKNOWN_CHAR = \/.\/;\n\n main := |*\n INT => { emit(:INT, ts, te, meta) };\n FLOAT => { emit(:FLOAT, ts, te, meta) };\n ON => { emit(:ON, ts, te, meta) };\n FRAGMENT => { emit(:FRAGMENT, ts, te, meta) };\n TRUE => { emit(:TRUE, ts, te, meta) };\n FALSE => { emit(:FALSE, ts, te, meta) };\n NULL => { emit(:NULL, ts, te, meta) };\n QUERY => { emit(:QUERY, ts, te, meta) };\n MUTATION => { emit(:MUTATION, ts, te, meta) };\n SUBSCRIPTION => { emit(:SUBSCRIPTION, ts, te, meta) };\n SCHEMA => { emit(:SCHEMA, ts, te, meta) };\n SCALAR => { emit(:SCALAR, ts, te, meta) };\n TYPE => { emit(:TYPE, ts, te, meta) };\n IMPLEMENTS => { emit(:IMPLEMENTS, ts, te, meta) };\n INTERFACE => { emit(:INTERFACE, ts, te, meta) };\n UNION => { emit(:UNION, ts, te, meta) };\n ENUM => { emit(:ENUM, ts, te, meta) };\n INPUT => { emit(:INPUT, ts, te, meta) };\n DIRECTIVE => { emit(:DIRECTIVE, ts, te, meta) };\n RCURLY => { emit(:RCURLY, ts, te, meta) };\n LCURLY => { emit(:LCURLY, ts, te, meta) };\n RPAREN => { emit(:RPAREN, ts, te, meta) };\n LPAREN => { emit(:LPAREN, ts, te, meta) };\n RBRACKET => { emit(:RBRACKET, ts, te, meta) };\n LBRACKET => { emit(:LBRACKET, ts, te, meta) };\n COLON => { emit(:COLON, ts, te, meta) };\n QUOTED_STRING => { emit_string(ts, te, meta, block: false) };\n BLOCK_STRING => { emit_string(ts, te, meta, block: true) };\n VAR_SIGN => { emit(:VAR_SIGN, ts, te, meta) };\n DIR_SIGN => { emit(:DIR_SIGN, ts, te, meta) };\n ELLIPSIS => { emit(:ELLIPSIS, ts, te, meta) };\n EQUALS => { emit(:EQUALS, ts, te, meta) };\n BANG => { emit(:BANG, ts, te, meta) };\n PIPE => { emit(:PIPE, ts, te, meta) };\n IDENTIFIER => { emit(:IDENTIFIER, ts, te, meta) };\n COMMENT => { record_comment(ts, te, meta) };\n\n NEWLINE => {\n meta[:line] += 1\n meta[:col] = 1\n };\n\n BLANK => { meta[:col] += te - ts };\n\n UNKNOWN_CHAR => { emit(:UNKNOWN_CHAR, ts, te, meta) };\n\n *|;\n}%%\n\n\nmodule GraphQL\n module Language\n module Lexer\n def self.tokenize(query_string)\n run_lexer(query_string)\n end\n\n # Replace any escaped unicode or whitespace with the _actual_ characters\n # To avoid allocating more strings, this modifies the string passed into it\n def self.replace_escaped_characters_in_place(raw_string)\n raw_string.gsub!(ESCAPES, ESCAPES_REPLACE)\n raw_string.gsub!(UTF_8, &UTF_8_REPLACE)\n nil\n end\n\n private\n\n %% write data;\n\n def self.run_lexer(query_string)\n data = query_string.unpack(\"c*\")\n eof = data.length\n\n # Since `Lexer` is a module, store all lexer state\n # in this local variable:\n meta = {\n line: 1,\n col: 1,\n data: data,\n tokens: [],\n previous_token: nil,\n }\n\n p ||= 0\n pe ||= data.length\n\n %% write init;\n\n %% write exec;\n\n meta[:tokens]\n end\n\n def self.record_comment(ts, te, meta)\n token = GraphQL::Language::Token.new(\n name: :COMMENT,\n value: meta[:data][ts...te].pack(PACK_DIRECTIVE).force_encoding(UTF_8_ENCODING),\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n\n meta[:previous_token] = token\n\n meta[:col] += te - ts\n end\n\n def self.emit(token_name, ts, te, meta)\n meta[:tokens] << token = GraphQL::Language::Token.new(\n name: token_name,\n value: meta[:data][ts...te].pack(PACK_DIRECTIVE).force_encoding(UTF_8_ENCODING),\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n meta[:previous_token] = token\n # Bump the column counter for the next token\n meta[:col] += te - ts\n end\n\n ESCAPES = \/\\\\[\"\\\\\\\/bfnrt]\/\n ESCAPES_REPLACE = {\n '\\\\\"' => '\"',\n \"\\\\\\\\\" => \"\\\\\",\n \"\\\\\/\" => '\/',\n \"\\\\b\" => \"\\b\",\n \"\\\\f\" => \"\\f\",\n \"\\\\n\" => \"\\n\",\n \"\\\\r\" => \"\\r\",\n \"\\\\t\" => \"\\t\",\n }\n\n UTF_8 = \/\\\\u[\\dAa-f]{4}\/i\n UTF_8_REPLACE = ->(m) { [m[-4..-1].to_i(16)].pack('U'.freeze) }\n\n VALID_STRING = \/\\A(?:[^\\\\]|#{ESCAPES}|#{UTF_8})*\\z\/o\n\n PACK_DIRECTIVE = \"c*\"\n UTF_8_ENCODING = \"UTF-8\"\n\n def self.emit_string(ts, te, meta, block:)\n quotes_length = block ? 3 : 1\n ts += quotes_length\n value = meta[:data][ts...te - quotes_length].pack(PACK_DIRECTIVE).force_encoding(UTF_8_ENCODING)\n if block\n value = trim_indent(value)\n end\n if value !~ VALID_STRING\n meta[:tokens] << token = GraphQL::Language::Token.new(\n name: :BAD_UNICODE_ESCAPE,\n value: value,\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n else\n replace_escaped_characters_in_place(value)\n\n meta[:tokens] << token = GraphQL::Language::Token.new(\n name: :STRING,\n value: value,\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n end\n\n meta[:previous_token] = token\n meta[:col] += te - ts\n end\n\n def self.trim_indent(str)\n lines = str.split(\"\\n\")\n common_indent = nil\n\n # find the common whitespace\n lines.each_with_index do |line, idx|\n if idx == 0\n next\n end\n line_length = line.size\n line_indent = line[\/\\A *\/].size\n if line_indent < line_length && common_indent.nil? || line_indent < common_indent\n common_indent = line_indent\n end\n end\n\n # Remove the common whitespace\n if common_indent\n lines.each_with_index do |line, idx|\n if idx == 0\n next\n else\n line[0, common_indent] = \"\"\n end\n end\n end\n\n # Remove leading & trailing blank lines\n while lines.first.empty?\n lines.shift\n end\n while lines.last.empty?\n lines.pop\n end\n\n # Rebuild the string\n lines.join(\"\\n\")\n end\n end\n end\nend\n","old_contents":"%%{\n machine graphql_lexer;\n\n IDENTIFIER = [_A-Za-z][_0-9A-Za-z]*;\n NEWLINE = [\\c\\r\\n];\n BLANK = [, \\t]+;\n COMMENT = '#' [^\\n\\r]*;\n INT = '-'? ('0'|[1-9][0-9]*);\n FLOAT_DECIMAL = '.'[0-9]+;\n FLOAT_EXP = ('e' | 'E')?('+' | '-')?[0-9]+;\n FLOAT = INT FLOAT_DECIMAL? FLOAT_EXP?;\n ON = 'on';\n FRAGMENT = 'fragment';\n TRUE = 'true';\n FALSE = 'false';\n NULL = 'null';\n QUERY = 'query';\n MUTATION = 'mutation';\n SUBSCRIPTION = 'subscription';\n SCHEMA = 'schema';\n SCALAR = 'scalar';\n TYPE = 'type';\n IMPLEMENTS = 'implements';\n INTERFACE = 'interface';\n UNION = 'union';\n ENUM = 'enum';\n INPUT = 'input';\n DIRECTIVE = 'directive';\n LCURLY = '{';\n RCURLY = '}';\n LPAREN = '(';\n RPAREN = ')';\n LBRACKET = '[';\n RBRACKET = ']';\n COLON = ':';\n QUOTE = '\"';\n BLOCK_QUOTE = '\"\"\"';\n ESCAPED_BLOCK_QUOTE = '\\\\\"\"\"';\n BLOCK_STRING_CHAR = (ESCAPED_BLOCK_QUOTE | ^'\"\"\"');\n ESCAPED_QUOTE = '\\\\\"';\n STRING_CHAR = (ESCAPED_QUOTE | ^'\"');\n VAR_SIGN = '$';\n DIR_SIGN = '@';\n ELLIPSIS = '...';\n EQUALS = '=';\n BANG = '!';\n PIPE = '|';\n\n QUOTED_STRING = QUOTE STRING_CHAR* QUOTE;\n BLOCK_STRING = BLOCK_QUOTE BLOCK_STRING_CHAR* BLOCK_QUOTE;\n # catch-all for anything else. must be at the bottom for precedence.\n UNKNOWN_CHAR = \/.\/;\n\n main := |*\n INT => { emit(:INT, ts, te, meta) };\n FLOAT => { emit(:FLOAT, ts, te, meta) };\n ON => { emit(:ON, ts, te, meta) };\n FRAGMENT => { emit(:FRAGMENT, ts, te, meta) };\n TRUE => { emit(:TRUE, ts, te, meta) };\n FALSE => { emit(:FALSE, ts, te, meta) };\n NULL => { emit(:NULL, ts, te, meta) };\n QUERY => { emit(:QUERY, ts, te, meta) };\n MUTATION => { emit(:MUTATION, ts, te, meta) };\n SUBSCRIPTION => { emit(:SUBSCRIPTION, ts, te, meta) };\n SCHEMA => { emit(:SCHEMA, ts, te, meta) };\n SCALAR => { emit(:SCALAR, ts, te, meta) };\n TYPE => { emit(:TYPE, ts, te, meta) };\n IMPLEMENTS => { emit(:IMPLEMENTS, ts, te, meta) };\n INTERFACE => { emit(:INTERFACE, ts, te, meta) };\n UNION => { emit(:UNION, ts, te, meta) };\n ENUM => { emit(:ENUM, ts, te, meta) };\n INPUT => { emit(:INPUT, ts, te, meta) };\n DIRECTIVE => { emit(:DIRECTIVE, ts, te, meta) };\n RCURLY => { emit(:RCURLY, ts, te, meta) };\n LCURLY => { emit(:LCURLY, ts, te, meta) };\n RPAREN => { emit(:RPAREN, ts, te, meta) };\n LPAREN => { emit(:LPAREN, ts, te, meta) };\n RBRACKET => { emit(:RBRACKET, ts, te, meta) };\n LBRACKET => { emit(:LBRACKET, ts, te, meta) };\n COLON => { emit(:COLON, ts, te, meta) };\n QUOTED_STRING => { emit_string(ts, te, meta, block: false) };\n BLOCK_STRING => { emit_string(ts, te, meta, block: true) };\n VAR_SIGN => { emit(:VAR_SIGN, ts, te, meta) };\n DIR_SIGN => { emit(:DIR_SIGN, ts, te, meta) };\n ELLIPSIS => { emit(:ELLIPSIS, ts, te, meta) };\n EQUALS => { emit(:EQUALS, ts, te, meta) };\n BANG => { emit(:BANG, ts, te, meta) };\n PIPE => { emit(:PIPE, ts, te, meta) };\n IDENTIFIER => { emit(:IDENTIFIER, ts, te, meta) };\n COMMENT => { record_comment(ts, te, meta) };\n\n NEWLINE => {\n meta[:line] += 1\n meta[:col] = 1\n };\n\n BLANK => { meta[:col] += te - ts };\n\n UNKNOWN_CHAR => { emit(:UNKNOWN_CHAR, ts, te, meta) };\n\n *|;\n}%%\n\n\nmodule GraphQL\n module Language\n module Lexer\n def self.tokenize(query_string)\n run_lexer(query_string)\n end\n\n # Replace any escaped unicode or whitespace with the _actual_ characters\n # To avoid allocating more strings, this modifies the string passed into it\n def self.replace_escaped_characters_in_place(raw_string)\n raw_string.gsub!(ESCAPES, ESCAPES_REPLACE)\n raw_string.gsub!(UTF_8, &UTF_8_REPLACE)\n nil\n end\n\n private\n\n %% write data;\n\n def self.run_lexer(query_string)\n data = query_string.unpack(\"c*\")\n eof = data.length\n\n # Since `Lexer` is a module, store all lexer state\n # in this local variable:\n meta = {\n line: 1,\n col: 1,\n data: data,\n tokens: [],\n previous_token: nil,\n }\n\n p ||= 0\n pe ||= data.length\n\n %% write init;\n\n %% write exec;\n\n meta[:tokens]\n end\n\n def self.record_comment(ts, te, meta)\n token = GraphQL::Language::Token.new(\n name: :COMMENT,\n value: meta[:data][ts...te].pack(PACK_DIRECTIVE).force_encoding(UTF_8_ENCODING),\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n\n meta[:previous_token] = token\n\n meta[:col] += te - ts\n end\n\n def self.emit(token_name, ts, te, meta)\n meta[:tokens] << token = GraphQL::Language::Token.new(\n name: token_name,\n value: meta[:data][ts...te].pack(PACK_DIRECTIVE).force_encoding(UTF_8_ENCODING),\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n meta[:previous_token] = token\n # Bump the column counter for the next token\n meta[:col] += te - ts\n end\n\n ESCAPES = \/\\\\[\"\\\\\\\/bfnrt]\/\n ESCAPES_REPLACE = {\n '\\\\\"' => '\"',\n \"\\\\\\\\\" => \"\\\\\",\n \"\\\\\/\" => '\/',\n \"\\\\b\" => \"\\b\",\n \"\\\\f\" => \"\\f\",\n \"\\\\n\" => \"\\n\",\n \"\\\\r\" => \"\\r\",\n \"\\\\t\" => \"\\t\",\n }\n\n UTF_8 = \/\\\\u[\\dAa-f]{4}\/i\n UTF_8_REPLACE = ->(m) { [m[-4..-1].to_i(16)].pack('U'.freeze) }\n\n VALID_STRING = \/\\A(?:[^\\\\]|#{ESCAPES}|#{UTF_8})*\\z\/o\n\n PACK_DIRECTIVE = \"c*\"\n UTF_8_ENCODING = \"UTF-8\"\n\n def self.emit_string(ts, te, meta, block:)\n quotes_length = block ? 3 : 1\n ts += quotes_length\n value = meta[:data][ts...te - quotes_length].pack(PACK_DIRECTIVE).force_encoding(UTF_8_ENCODING)\n if block\n value = trim_indent(value)\n end\n if value !~ VALID_STRING\n meta[:tokens] << token = GraphQL::Language::Token.new(\n name: :BAD_UNICODE_ESCAPE,\n value: value,\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n else\n replace_escaped_characters_in_place(value)\n\n meta[:tokens] << token = GraphQL::Language::Token.new(\n name: :STRING,\n value: value,\n line: meta[:line],\n col: meta[:col],\n prev_token: meta[:previous_token],\n )\n end\n\n meta[:previous_token] = token\n meta[:col] += te - ts\n end\n\n def self.trim_indent(str)\n lines = str.split(\"\\n\")\n common_indent = nil\n\n # find the common whitespace\n lines.each_with_index do |line, idx|\n if idx == 0\n next\n end\n line_length = line.size\n line_indent = line[\/\\A *\/].size\n if line_indent < line_length && common_indent.nil? || line_indent < common_indent\n common_indent = line_indent\n end\n end\n\n # Remove the common whitespace\n if common_indent\n lines.each_with_index do |line, idx|\n if idx == 0\n next\n else\n line[0, common_indent] = \"\"\n end\n end\n end\n\n # Remove leading & trailing blank lines\n while lines.first.blank?\n lines.shift\n end\n while lines.last.blank?\n lines.pop\n end\n\n # Rebuild the string\n lines.join(\"\\n\")\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"db4d62aeaadd3cd552729eb866eaaa23155155a3","subject":"hext-machine: fix formatting","message":"hext-machine: fix formatting\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"libhext\/ragel\/hext-machine.rl","new_file":"libhext\/ragel\/hext-machine.rl","new_contents":"%%{\n\n# This ragel machine parses\/lexes hext. It is embedded in ragel\/Parser.cpp.rl.\nmachine hext;\n\n\n#### NTH_PATTERN ###############################################################\n# nth_pattern is used by traits, e.g. nth-last-child(nth_pattern).\n# Examples: :nth-child(1) :nth-child(even) :nth-child(2n) :nth-child(2n+1)\nnth_pattern = (\n ( 'even' %{ pv.nth = {2, 0}; } )\n |\n\n ( 'odd' %{ pv.nth = {2, 1}; } )\n |\n\n ( ( ( '-'? [0-9]+ )\n >{ TK_START; }\n %{ TK_STOP; pv.nth = {0, std::stoi(tok)}; }\n )\n ( 'n'\n %{ pv.nth = {pv.nth.second, 0}; }\n ( ( ('+'|'-') [0-9]+ )\n >{ TK_START; }\n %{ TK_STOP; pv.nth.second = std::stoi(tok); }\n )?\n )?\n )\n);\n\n\n#### TRAITS ####################################################################\ntrait = ':' (\n ( 'empty' %{ pv.set_trait(0); } )\n |\n\n ( 'child-count('\n ( [0-9]+\n >{ TK_START; }\n %{ TK_STOP; pv.set_trait(std::stoi(tok)); } )\n ')' )\n |\n\n ( 'attribute-count('\n ( [0-9]+\n >{ TK_START; }\n %{ TK_STOP; pv.set_trait(std::stoi(tok)); } )\n ')' )\n |\n\n ( 'nth-child(' nth_pattern ')'\n %{ pv.set_trait(pv.nth); } )\n |\n\n ( 'nth-last-child(' nth_pattern ')'\n %{ pv.set_trait(pv.nth, NthChildMatch::Last); } )\n |\n\n ( 'nth-of-type(' nth_pattern ')'\n %{ pv.set_trait(pv.nth, NthChildMatch::First|NthChildMatch::OfType); } )\n |\n\n ( 'first-child'\n %{ pv.set_trait(0, 1); } )\n |\n\n ( 'first-of-type'\n %{ pv.set_trait(0, 1, NthChildMatch::First|NthChildMatch::OfType); } )\n |\n\n ( 'last-child'\n %{ pv.set_trait(0, 1, NthChildMatch::Last); } )\n |\n\n ( 'last-of-type'\n %{ pv.set_trait(0, 1, NthChildMatch::Last|NthChildMatch::OfType); } )\n |\n\n ( 'nth-last-of-type(' nth_pattern ')'\n %{ pv.set_trait(pv.nth, NthChildMatch::Last|NthChildMatch::OfType); } )\n |\n\n ( 'only-child' %{ pv.set_trait(); } )\n |\n\n ( 'only-of-type' %{ pv.set_trait(OnlyChildMatch::OfType); } )\n |\n\n ( 'text' %{ pv.set_trait(); } )\n);\nnot_trait =\n':not('\n %{ pv.negate = std::make_unique(); }\n (\n trait\n %{\n assert(pv.negate);\n pv.negate->take_match(std::move(pv.trait));\n }\n )+\n')';\n\n\n#### REGULAR EXPRESSIONS #######################################################\nregex =\n'\/' ( ( [^\/] | '\\\\\/' )** >{ TK_START; } %{ TK_STOP; } ) '\/'\n# regex flags\n(\n # case insensitive\n ( 'i' %{ pv.regex_flag |= boost::regex::icase; } )\n |\n # collate (locale aware character groups)\n ( 'c' %{ pv.regex_flag |= boost::regex::collate; } )\n)*\n%{ try {\n pv.regex = boost::regex(tok, pv.regex_flag);\n }\n catch( const boost::regex_error& e ) {\n \/\/ Mark whole regex as error, including slashes and flags\n auto mark_len = static_cast(this->p - tok_begin + 1);\n this->throw_regex_error(mark_len, e.code());\n }\n};\n# Wrap a regular expression into a RegexTest.\nregex_test = regex %{ assert(pv.regex); pv.set_test(*pv.regex); };\n\n\n#### BUILTIN FUNCTION ##########################################################\nbuiltin = (\n '@'\n ( ( 'text' %{ pv.builtin = TextBuiltin; } )\n |\n ( 'inner-html' %{ pv.builtin = InnerHtmlBuiltin; } )\n |\n ( 'strip-tags' %{ pv.builtin = StripTagsBuiltin; } ) )\n);\n\n\n#### CAPTURE ###################################################################\n# capture variable, e.g. id={cap_var}, @text={cap_var}\ncapture = (\n '{' ( ( [^\/{}][^\/{}]** )\n >{ TK_START; }\n %{ TK_STOP; pv.cap_var = tok; } )\n # optional capture regex, e.g. @text={time\/(\\d\\d:\\d\\d)\/}\n regex?\n '}'\n);\n\n\n#### HELPERS ###################################################################\n# Set an attribute capture to optional. By default, attribute captures are\n# mandatory, i.e. the attribute has to exist in a node for it to match.\noptional = (\n '?' %{ pv.optional = true; }\n);\n# Negate a match pattern, e.g. style!, class=\"menu\"!, @text=\/foo\/!\nnegate = (\n '!' %{ pv.set_test(std::move(pv.test)); }\n);\n# The name of an HTML-element's attribute\nattr_name = (\n ( alpha (alnum | '-' | '_')** )\n >{ TK_START; }\n %{ TK_STOP; pv.attr_name = tok; }\n);\n# Literal value, e.g. attr=\"literal\", class='single'\nliteral_value =\n( '\"' (\n ( [^\"] | '\\\\\"' )**\n >{ TK_START; } %{ TK_STOP; pv.literal_value = tok; }\n ) '\"' )\n|\n( '\\'' (\n ( [^'] | '\\\\\\'' )**\n >{ TK_START; } %{ TK_STOP; pv.literal_value = tok; }\n ) '\\'' );\n\n\n#### LITERAL ###################################################################\nliteral = (\n ( '=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '==' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '^=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '*=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '$=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n);\n\n\n#### PATTERNS ##################################################################\npattern = (\n space+\n ( ( ( builtin '=' capture )\n %{ if( pv.regex )\n cur_rule().append_capture(pv.builtin, pv.cap_var, *pv.regex);\n else\n cur_rule().append_capture(pv.builtin, pv.cap_var); } )\n |\n\n ( ( builtin '=' regex_test negate? )\n %{ cur_rule().append_match(pv.builtin, std::move(pv.test)); } )\n |\n\n ( ( builtin literal negate? )\n %{ cur_rule().append_match(pv.builtin, std::move(pv.test)); } )\n |\n\n ( ( attr_name '=' capture optional? )\n %{ if( pv.regex )\n cur_rule()\n .append_capture(pv.attr_name, pv.cap_var, *pv.regex);\n else\n cur_rule().append_capture(pv.attr_name, pv.cap_var);\n if( !pv.optional )\n cur_rule().append_match(pv.attr_name);\n } )\n |\n\n ( ( attr_name '=' regex_test negate? )\n %{ cur_rule().append_match(pv.attr_name, std::move(pv.test)); } )\n |\n\n ( ( attr_name literal negate? )\n %{ cur_rule().append_match(pv.attr_name, std::move(pv.test)); } )\n |\n\n ( ( attr_name\n %{ pv.test = nullptr; }\n negate?\n )\n %{ cur_rule().append_match(pv.attr_name, std::move(pv.test)); } )\n ) %{ pv.reset(); }\n);\n\n\n#### RULES #####################################################################\ntag_name = ( alpha (alnum | '-' | '_')** );\nmain := (\n # ignore whitespace\n space\n |\n\n # comment\n ( '#' (any - '\\n')* '\\n' )\n |\n\n # open rule\n (\n # a rule starts with '<'\n ( '<' %{ push_rule(); } )\n\n # a rule can be optional\n ( '?' %{ cur_rule().set_optional(true); } )?\n\n # a rule must have a tag name, e.g. { TK_START; }\n %{ TK_STOP; set_open_tag_or_throw(tok); } )\n\n # a rule can have multiple traits, e.g. :first-child, :empty\n ( ( not_trait %{ cur_rule().append_match(std::move(pv.negate)); } )\n |\n\n ( trait %{ cur_rule().append_match(std::move(pv.trait)); } ) )*\n\n # a rule can have multiple match or capture patterns,\n # e.g. class=\"menu\", @text={heading}\n pattern*\n\n space*\n\n ( ( '\/>' %{ pop_rule(); } ) | '>' )\n )\n |\n\n # end rule\n (\n '<\/'\n ( ( '*' | tag_name ) >{ TK_START; }\n %{ TK_STOP;\n validate_close_tag_or_throw(tok);\n pop_rule(); } )\n '>'\n )\n)* $err{ this->throw_unexpected(); };\n\n}%%\n","old_contents":"%%{\n\n# This ragel machine parses\/lexes hext. It is embedded in ragel\/Parser.cpp.rl.\nmachine hext;\n\n\n#### NTH_PATTERN ###############################################################\n# nth_pattern is used by traits, e.g. nth-last-child(nth_pattern).\n# Examples: :nth-child(1) :nth-child(even) :nth-child(2n) :nth-child(2n+1)\nnth_pattern = (\n ( 'even' %{ pv.nth = {2, 0}; } )\n |\n\n ( 'odd' %{ pv.nth = {2, 1}; } )\n |\n\n ( ( ( '-'? [0-9]+ )\n >{ TK_START; }\n %{ TK_STOP; pv.nth = {0, std::stoi(tok)}; }\n )\n ( 'n'\n %{ pv.nth = {pv.nth.second, 0}; }\n ( ( ('+'|'-') [0-9]+ )\n >{ TK_START; }\n %{ TK_STOP; pv.nth.second = std::stoi(tok); }\n )?\n )?\n )\n);\n\n\n#### TRAITS ####################################################################\ntrait = ':' (\n ( 'empty' %{ pv.set_trait(0); } )\n |\n\n ( 'child-count('\n ( [0-9]+\n >{ TK_START; }\n %{ TK_STOP; pv.set_trait(std::stoi(tok)); } )\n ')' )\n |\n\n ( 'attribute-count('\n ( [0-9]+\n >{ TK_START; }\n %{ TK_STOP; pv.set_trait(std::stoi(tok)); } )\n ')' )\n |\n\n ( 'nth-child(' nth_pattern ')'\n %{ pv.set_trait(pv.nth); } )\n |\n\n ( 'nth-last-child(' nth_pattern ')'\n %{ pv.set_trait(pv.nth, NthChildMatch::Last); } )\n |\n\n ( 'nth-of-type(' nth_pattern ')'\n %{ pv.set_trait(pv.nth, NthChildMatch::First|NthChildMatch::OfType); } )\n |\n\n ( 'first-child'\n %{ pv.set_trait(0, 1); } )\n |\n\n ( 'first-of-type'\n %{ pv.set_trait(0, 1, NthChildMatch::First|NthChildMatch::OfType); } )\n |\n\n ( 'last-child'\n %{ pv.set_trait(0, 1, NthChildMatch::Last); } )\n |\n\n ( 'last-of-type'\n %{ pv.set_trait(0, 1, NthChildMatch::Last|NthChildMatch::OfType); } )\n |\n\n ( 'nth-last-of-type(' nth_pattern ')'\n %{ pv.set_trait(pv.nth, NthChildMatch::Last|NthChildMatch::OfType); } )\n |\n\n ( 'only-child' %{ pv.set_trait(); } )\n |\n\n ( 'only-of-type' %{ pv.set_trait(OnlyChildMatch::OfType); } )\n |\n\n ( 'text' %{ pv.set_trait(); } )\n);\nnot_trait =\n':not('\n %{ pv.negate = std::make_unique(); }\n (\n trait\n %{\n assert(pv.negate);\n pv.negate->take_match(std::move(pv.trait));\n }\n )+\n')';\n\n\n#### REGULAR EXPRESSIONS #######################################################\nregex =\n'\/' ( ( [^\/] | '\\\\\/' )** >{ TK_START; } %{ TK_STOP; } ) '\/'\n# regex flags\n(\n # case insensitive\n ( 'i' %{ pv.regex_flag |= boost::regex::icase; } )\n |\n # collate (locale aware character groups)\n ( 'c' %{ pv.regex_flag |= boost::regex::collate; } )\n)*\n%{ try {\n pv.regex = boost::regex(tok, pv.regex_flag);\n }\n catch( const boost::regex_error& e ) {\n \/\/ Mark whole regex as error, including slashes and flags\n auto mark_len = static_cast(this->p - tok_begin + 1);\n this->throw_regex_error(mark_len, e.code());\n }\n};\n# Wrap a regular expression into a RegexTest.\nregex_test = regex %{ assert(pv.regex); pv.set_test(*pv.regex); };\n\n\n#### BUILTIN FUNCTION ##########################################################\nbuiltin = (\n '@'\n ( ( 'text' %{ pv.builtin = TextBuiltin; } )\n |\n ( 'inner-html' %{ pv.builtin = InnerHtmlBuiltin; } )\n |\n ( 'strip-tags' %{ pv.builtin = StripTagsBuiltin; } ) )\n);\n\n\n#### CAPTURE ###################################################################\n# capture variable, e.g. id={cap_var}, @text={cap_var}\ncapture = (\n '{' ( ( [^\/{}][^\/{}]** )\n >{ TK_START; }\n %{ TK_STOP; pv.cap_var = tok; } )\n # optional capture regex, e.g. @text={time\/(\\d\\d:\\d\\d)\/}\n regex?\n '}'\n);\n\n\n#### HELPERS ###################################################################\n# Set an attribute capture to optional. By default, attribute captures are\n# mandatory, i.e. the attribute has to exist in a node for it to match.\noptional = (\n '?' %{ pv.optional = true; }\n);\n# Negate a match pattern, e.g. style!, class=\"menu\"!, @text=\/foo\/!\nnegate = (\n '!' %{ pv.set_test(std::move(pv.test)); }\n);\n# The name of an HTML-element's attribute\nattr_name = (\n ( alpha (alnum | '-' | '_')** )\n >{ TK_START; }\n %{ TK_STOP; pv.attr_name = tok; }\n);\n# Literal value, e.g. attr=\"literal\", class='single'\nliteral_value =\n( '\"' (\n ( [^\"] | '\\\\\"' )**\n >{ TK_START; } %{ TK_STOP; pv.literal_value = tok; }\n ) '\"' )\n|\n( '\\'' (\n ( [^'] | '\\\\\\'' )**\n >{ TK_START; } %{ TK_STOP; pv.literal_value = tok; }\n ) '\\'' );\n\n\n#### LITERAL ###################################################################\nliteral = (\n ( '=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '==' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '^=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '*=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n |\n ( '$=' literal_value\n %{ pv.set_test(pv.literal_value); } )\n);\n\n\n#### PATTERNS ##################################################################\npattern = (\n space+\n ( ( ( builtin '=' capture )\n %{ if( pv.regex )\n cur_rule().append_capture(pv.builtin, pv.cap_var, *pv.regex);\n else\n cur_rule().append_capture(pv.builtin, pv.cap_var); } )\n |\n\n ( ( builtin '=' regex_test negate? )\n %{ cur_rule().append_match(pv.builtin, std::move(pv.test)); } )\n |\n\n ( ( builtin literal negate? )\n %{ cur_rule().append_match(pv.builtin, std::move(pv.test)); } )\n |\n\n ( ( attr_name '=' capture optional? )\n %{ if( pv.regex )\n cur_rule()\n .append_capture(pv.attr_name, pv.cap_var, *pv.regex);\n else\n cur_rule().append_capture(pv.attr_name, pv.cap_var);\n if( !pv.optional )\n cur_rule().append_match(pv.attr_name);\n } )\n |\n\n ( ( attr_name '=' regex_test negate? )\n %{ cur_rule().append_match(pv.attr_name, std::move(pv.test)); } )\n |\n\n ( ( attr_name literal negate? )\n %{ cur_rule().append_match(pv.attr_name, std::move(pv.test)); } )\n |\n\n ( ( attr_name\n %{ pv.test = nullptr; }\n negate?\n )\n %{ cur_rule().append_match(pv.attr_name, std::move(pv.test)); } )\n ) %{ pv.reset(); }\n);\n\n\n#### RULES #####################################################################\ntag_name = ( alpha (alnum | '-' | '_')** );\nmain := (\n # ignore whitespace\n space\n |\n\n # comment\n ( '#' (any - '\\n')* '\\n' )\n |\n\n # open rule\n (\n # a rule starts with '<'\n ( '<' %{ push_rule(); } )\n\n # a rule can be optional, i.e. starts with { TK_START; }\n %{ TK_STOP; set_open_tag_or_throw(tok); } )\n\n # a rule can have multiple traits, e.g. :first-child, :empty\n ( ( not_trait %{ cur_rule().append_match(std::move(pv.negate)); } )\n |\n\n ( trait %{ cur_rule().append_match(std::move(pv.trait)); } ) )*\n\n # a rule can have multiple match or capture patterns,\n # e.g. class=\"menu\", @text={heading}\n pattern*\n\n space*\n\n ( ( '\/>' %{ pop_rule(); } ) | '>' )\n )\n |\n\n # end rule\n (\n '<\/'\n ( ( '*' | tag_name ) >{ TK_START; }\n %{ TK_STOP;\n validate_close_tag_or_throw(tok);\n pop_rule(); } )\n '>'\n )\n)* $err{ this->throw_unexpected(); };\n\n}%%\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"88e9b7803f9667d7061fb6157a2696fc159ad0f0","subject":"make control \"kill\" command use Register_disconnect() rather than fdclose().","message":"make control \"kill\" command use Register_disconnect() rather than fdclose().\n\nPreviously it would leave a stale registration entry, and any new connections\nthat re-used that fd would get booted immediately.","repos":"solidrails\/mongrel2,solidrails\/mongrel2,solidrails\/mongrel2,solidrails\/mongrel2","old_file":"src\/control.rl","new_file":"src\/control.rl","new_contents":"#include \"control.h\"\n#include \"bstring.h\"\n#include \"task\/task.h\"\n#include \"register.h\"\n#include \"dbg.h\"\n#include \n#include \n#include \"setting.h\"\n#include \n\n\nvoid bstring_free(void *data, void *hint)\n{\n bdestroy((bstring)hint);\n}\n\nstruct tagbstring REQ_STATUS_TASKS = bsStatic(\"status tasks\");\nstruct tagbstring REQ_STATUS_NET = bsStatic(\"status net\");\n\n\nstatic inline bstring read_message(void *sock)\n{\n bstring req = NULL;\n int rc = 0;\n\n zmq_msg_t *inmsg = calloc(sizeof(zmq_msg_t), 1);\n rc = zmq_msg_init(inmsg);\n check(rc == 0, \"init failed.\");\n\n rc = mqrecv(sock, inmsg, ZMQ_NOBLOCK);\n check(rc == 0, \"Receive on control failed.\");\n\n req = blk2bstr(zmq_msg_data(inmsg), zmq_msg_size(inmsg));\n check(req, \"Failed to create the request string.\");\n\n zmq_msg_close(inmsg);\n free(inmsg);\n\n return req;\n\nerror:\n if(inmsg) {\n zmq_msg_close(inmsg);\n free(inmsg);\n }\n\n return NULL;\n}\n\nstatic inline void send_reply(void *sock, bstring rep)\n{\n int rc = 0;\n zmq_msg_t *outmsg = calloc(sizeof(zmq_msg_t), 1);\n rc = zmq_msg_init(outmsg);\n check(rc == 0, \"init failed.\");\n\n rc = zmq_msg_init_data(outmsg, bdata(rep), blength(rep), bstring_free, rep);\n check(rc == 0, \"Failed to init reply data.\");\n \n rc = mqsend(sock, outmsg, 0);\n check(rc == 0, \"Failed to deliver 0mq message to requestor.\");\n\nerror:\n free(outmsg);\n return;\n}\n\nstatic int CONTROL_RUNNING = 1;\nstatic void *CONTROL_SOCKET = NULL;\n\n\n%%{\n machine ControlParser;\n\n action mark { mark = fpc; }\n\n action status_tasks { reply = taskgetinfo(); fbreak; }\n action status_net { reply = Register_info(); fbreak; }\n\n action control_stop {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"stopping control port\\\"}\");\n CONTROL_RUNNING = 0; fbreak;\n }\n\n action time {\n reply = bformat(\"{\\\"time\\\": %d}\", (int)time(NULL)); fbreak;\n }\n\n action kill {\n int id = atoi(p);\n\n if(id < 0 || id > MAX_REGISTERED_FDS) {\n reply = bformat(\"{\\\"error\\\": \\\"invalid id: %d\\\"}\", id);\n } else {\n int fd = Register_fd_for_id(id);\n\n if(fd >= 0) {\n Register_disconnect(fd);\n reply = bformat(\"{\\\"result\\\": \\\"killed %d\\\"}\", id);\n } else {\n reply = bformat(\"{\\\"error\\\": \\\"does not exist: %d\\\"}\", id);\n }\n }\n\n fbreak;\n }\n\n action reload {\n int rc = raise(SIGHUP);\n if (0 == rc) {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"the server will be reloaded\\\"}\");\n } else {\n reply = bfromcstr(\"{\\\"error\\\": \\\"failed to reload the server\\\"}\");\n }\n fbreak;\n }\n\n action stop {\n \/\/ TODO: probably report back the number of waiting tasks\n int rc = raise(SIGINT);\n if (0 == rc) {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"the server will be stopped\\\"}\");\n } else {\n reply = bfromcstr(\"{\\\"error\\\": \\\"failed to stop the server\\\"}\");\n }\n fbreak;\n }\n\n action terminate {\n \/\/ TODO: the server might have been terminated before\n \/\/ the reply is sent back. If this scenario is crucial (if possible at all)\n \/\/ find a workaround, otherwise, forget about it and remove this comment.\n int rc = raise(SIGTERM);\n if (0 == rc) {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"the server will be terminated\\\"}\");\n } else {\n reply = bfromcstr(\"{\\\"error\\\": \\\"failed to terminate the server\\\"}\");\n }\n fbreak;\n }\n\n action help {\n reply = bfromcstr(\"{\\\"command_list\\\":[\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"control stop\\\", \\\"description\\\": \\\"Close the control port.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"kill \\\", \\\"description\\\": \\\"Kill a connection in a violent way.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"reload\\\", \\\"description\\\": \\\"Reload the server. Same as `kill -SIGHUP `.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"status net\\\", \\\"description\\\": \\\"Return a list of active connections.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"status tasks\\\", \\\"description\\\": \\\"Return a list of active tasks.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"stop\\\", \\\"description\\\": \\\"Gracefully shut down the server. Same as `kill -SIGINT `.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"terminate\\\", \\\"description\\\": \\\"Unconditionally terminate the server. Same as `kill -SIGTERM .\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"time\\\", \\\"description\\\": \\\"Return server timestamp.\\\"}\\n\");\n bcatcstr(reply, \"]}\\n\");\n fbreak;\n }\n\n Status = \"status\" space+ (\"tasks\" @status_tasks | \"net\" @status_net);\n Control = \"control stop\" @control_stop;\n Time = \"time\" @time;\n Kill = \"kill\" space+ digit+ >mark @kill;\n Reload = \"reload\" @reload;\n Stop = \"stop\" @stop;\n Terminate = \"terminate\" @terminate;\n Help = \"help\" @help;\n\n main := Status | Control | Time | Kill | Reload | Stop | Terminate | Help;\n}%%\n\n%% write data;\n\nbstring Control_execute(bstring req)\n{\n const char *p = bdata(req);\n const char *pe = p+blength(req);\n const char *mark = NULL;\n int cs = 0;\n bstring reply = NULL;\n\n debug(\"RECEIVED CONTROL COMMAND: %s\", bdata(req));\n\n %% write init;\n %% write exec noend;\n\n check(p <= pe, \"Buffer overflow after parsing. Tell Zed that you sent something from a handler that went %ld past the end in the parser.\", \n (long int)(pe - p));\n\n if ( cs == %%{ write error; }%% ) {\n check(pe - p > 0, \"Major erorr in the parser, tell Zed.\");\n return bformat(\"{\\\"error\\\": \\\"parsing error at: ...%s\\\"}\", bdata(req) + (pe - p));\n } else if(!reply) {\n return bformat(\"{\\\"error\\\": \\\"invalid command\\\"}\", pe - p);\n } else {\n return reply;\n }\n\nerror:\n return bfromcstr(\"{\\\"error\\\": \\\"fatal error\\\"}\");\n}\n\nstruct tagbstring DEFAULT_CONTROL_SPEC = bsStatic(\"ipc:\/\/run\/control\");\n\nvoid Control_task(void *v)\n{\n int rc = 0;\n bstring req = NULL;\n bstring rep = NULL;\n bstring spec = Setting_get_str(\"control_port\", &DEFAULT_CONTROL_SPEC);\n taskname(\"control\");\n\n log_info(\"Setting up control socket in at %s\", bdata(spec));\n\n CONTROL_SOCKET = mqsocket(ZMQ_REP);\n check(CONTROL_SOCKET != NULL, \"Can't create contol socket.\");\n\n rc = zmq_bind(CONTROL_SOCKET, bdata(spec));\n check(rc == 0, \"Failed to bind control port to run\/control.\");\n\n while(CONTROL_RUNNING) {\n taskstate(\"waiting\");\n \n req = read_message(CONTROL_SOCKET);\n check(req, \"Failed to read message %s.\",errno);\n\n rep = Control_execute(req);\n bdestroy(req);\n\n taskstate(\"replying\");\n send_reply(CONTROL_SOCKET, rep);\n check(rep, \"Faild to create a reply.\");\n }\n\n rc = zmq_close(CONTROL_SOCKET);\n check(rc == 0, \"Failed to close control port socket.\");\n CONTROL_SOCKET = NULL;\n log_info(\"Control port exiting.\");\n taskexit(0);\n\nerror:\n log_info(\"Control port exiting with error.\");\n zmq_close(CONTROL_SOCKET);\n CONTROL_SOCKET = NULL;\n taskexit(1);\n}\n\n\nvoid Control_port_start()\n{\n taskcreate(Control_task, NULL, 32 * 1024);\n}\n\nint Control_port_stop()\n{\n int rc = 0;\n\n if(CONTROL_SOCKET != NULL) {\n rc = zmq_close(CONTROL_SOCKET);\n check(rc == 0, \"Failed to close control socket\");\n\n \/\/ TODO: wake up the control task.\n \/\/ it doesn't seem to notice that the socket has been closed.\n }\n\nerror:\n return rc;\n}\n","old_contents":"#include \"control.h\"\n#include \"bstring.h\"\n#include \"task\/task.h\"\n#include \"register.h\"\n#include \"dbg.h\"\n#include \n#include \n#include \"setting.h\"\n#include \n\n\nvoid bstring_free(void *data, void *hint)\n{\n bdestroy((bstring)hint);\n}\n\nstruct tagbstring REQ_STATUS_TASKS = bsStatic(\"status tasks\");\nstruct tagbstring REQ_STATUS_NET = bsStatic(\"status net\");\n\n\nstatic inline bstring read_message(void *sock)\n{\n bstring req = NULL;\n int rc = 0;\n\n zmq_msg_t *inmsg = calloc(sizeof(zmq_msg_t), 1);\n rc = zmq_msg_init(inmsg);\n check(rc == 0, \"init failed.\");\n\n rc = mqrecv(sock, inmsg, ZMQ_NOBLOCK);\n check(rc == 0, \"Receive on control failed.\");\n\n req = blk2bstr(zmq_msg_data(inmsg), zmq_msg_size(inmsg));\n check(req, \"Failed to create the request string.\");\n\n zmq_msg_close(inmsg);\n free(inmsg);\n\n return req;\n\nerror:\n if(inmsg) {\n zmq_msg_close(inmsg);\n free(inmsg);\n }\n\n return NULL;\n}\n\nstatic inline void send_reply(void *sock, bstring rep)\n{\n int rc = 0;\n zmq_msg_t *outmsg = calloc(sizeof(zmq_msg_t), 1);\n rc = zmq_msg_init(outmsg);\n check(rc == 0, \"init failed.\");\n\n rc = zmq_msg_init_data(outmsg, bdata(rep), blength(rep), bstring_free, rep);\n check(rc == 0, \"Failed to init reply data.\");\n \n rc = mqsend(sock, outmsg, 0);\n check(rc == 0, \"Failed to deliver 0mq message to requestor.\");\n\nerror:\n free(outmsg);\n return;\n}\n\nstatic int CONTROL_RUNNING = 1;\nstatic void *CONTROL_SOCKET = NULL;\n\n\n%%{\n machine ControlParser;\n\n action mark { mark = fpc; }\n\n action status_tasks { reply = taskgetinfo(); fbreak; }\n action status_net { reply = Register_info(); fbreak; }\n\n action control_stop {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"stopping control port\\\"}\");\n CONTROL_RUNNING = 0; fbreak;\n }\n\n action time {\n reply = bformat(\"{\\\"time\\\": %d}\", (int)time(NULL)); fbreak;\n }\n\n action kill {\n int id = atoi(p);\n\n if(id < 0 || id > MAX_REGISTERED_FDS) {\n reply = bformat(\"{\\\"error\\\": \\\"invalid id: %d\\\"}\", id);\n } else {\n int fd = Register_fd_for_id(id);\n\n if(fd >= 0) {\n fdclose(fd);\n reply = bformat(\"{\\\"result\\\": \\\"killed %d\\\"}\", id);\n } else {\n reply = bformat(\"{\\\"error\\\": \\\"does not exist: %d\\\"}\", id);\n }\n }\n\n fbreak;\n }\n\n action reload {\n int rc = raise(SIGHUP);\n if (0 == rc) {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"the server will be reloaded\\\"}\");\n } else {\n reply = bfromcstr(\"{\\\"error\\\": \\\"failed to reload the server\\\"}\");\n }\n fbreak;\n }\n\n action stop {\n \/\/ TODO: probably report back the number of waiting tasks\n int rc = raise(SIGINT);\n if (0 == rc) {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"the server will be stopped\\\"}\");\n } else {\n reply = bfromcstr(\"{\\\"error\\\": \\\"failed to stop the server\\\"}\");\n }\n fbreak;\n }\n\n action terminate {\n \/\/ TODO: the server might have been terminated before\n \/\/ the reply is sent back. If this scenario is crucial (if possible at all)\n \/\/ find a workaround, otherwise, forget about it and remove this comment.\n int rc = raise(SIGTERM);\n if (0 == rc) {\n reply = bfromcstr(\"{\\\"msg\\\": \\\"the server will be terminated\\\"}\");\n } else {\n reply = bfromcstr(\"{\\\"error\\\": \\\"failed to terminate the server\\\"}\");\n }\n fbreak;\n }\n\n action help {\n reply = bfromcstr(\"{\\\"command_list\\\":[\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"control stop\\\", \\\"description\\\": \\\"Close the control port.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"kill \\\", \\\"description\\\": \\\"Kill a connection in a violent way.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"reload\\\", \\\"description\\\": \\\"Reload the server. Same as `kill -SIGHUP `.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"status net\\\", \\\"description\\\": \\\"Return a list of active connections.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"status tasks\\\", \\\"description\\\": \\\"Return a list of active tasks.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"stop\\\", \\\"description\\\": \\\"Gracefully shut down the server. Same as `kill -SIGINT `.\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"terminate\\\", \\\"description\\\": \\\"Unconditionally terminate the server. Same as `kill -SIGTERM .\\\"},\\n\");\n bcatcstr(reply, \"{\\\"name\\\": \\\"time\\\", \\\"description\\\": \\\"Return server timestamp.\\\"}\\n\");\n bcatcstr(reply, \"]}\\n\");\n fbreak;\n }\n\n Status = \"status\" space+ (\"tasks\" @status_tasks | \"net\" @status_net);\n Control = \"control stop\" @control_stop;\n Time = \"time\" @time;\n Kill = \"kill\" space+ digit+ >mark @kill;\n Reload = \"reload\" @reload;\n Stop = \"stop\" @stop;\n Terminate = \"terminate\" @terminate;\n Help = \"help\" @help;\n\n main := Status | Control | Time | Kill | Reload | Stop | Terminate | Help;\n}%%\n\n%% write data;\n\nbstring Control_execute(bstring req)\n{\n const char *p = bdata(req);\n const char *pe = p+blength(req);\n const char *mark = NULL;\n int cs = 0;\n bstring reply = NULL;\n\n debug(\"RECEIVED CONTROL COMMAND: %s\", bdata(req));\n\n %% write init;\n %% write exec noend;\n\n check(p <= pe, \"Buffer overflow after parsing. Tell Zed that you sent something from a handler that went %ld past the end in the parser.\", \n (long int)(pe - p));\n\n if ( cs == %%{ write error; }%% ) {\n check(pe - p > 0, \"Major erorr in the parser, tell Zed.\");\n return bformat(\"{\\\"error\\\": \\\"parsing error at: ...%s\\\"}\", bdata(req) + (pe - p));\n } else if(!reply) {\n return bformat(\"{\\\"error\\\": \\\"invalid command\\\"}\", pe - p);\n } else {\n return reply;\n }\n\nerror:\n return bfromcstr(\"{\\\"error\\\": \\\"fatal error\\\"}\");\n}\n\nstruct tagbstring DEFAULT_CONTROL_SPEC = bsStatic(\"ipc:\/\/run\/control\");\n\nvoid Control_task(void *v)\n{\n int rc = 0;\n bstring req = NULL;\n bstring rep = NULL;\n bstring spec = Setting_get_str(\"control_port\", &DEFAULT_CONTROL_SPEC);\n taskname(\"control\");\n\n log_info(\"Setting up control socket in at %s\", bdata(spec));\n\n CONTROL_SOCKET = mqsocket(ZMQ_REP);\n check(CONTROL_SOCKET != NULL, \"Can't create contol socket.\");\n\n rc = zmq_bind(CONTROL_SOCKET, bdata(spec));\n check(rc == 0, \"Failed to bind control port to run\/control.\");\n\n while(CONTROL_RUNNING) {\n taskstate(\"waiting\");\n \n req = read_message(CONTROL_SOCKET);\n check(req, \"Failed to read message %s.\",errno);\n\n rep = Control_execute(req);\n bdestroy(req);\n\n taskstate(\"replying\");\n send_reply(CONTROL_SOCKET, rep);\n check(rep, \"Faild to create a reply.\");\n }\n\n rc = zmq_close(CONTROL_SOCKET);\n check(rc == 0, \"Failed to close control port socket.\");\n CONTROL_SOCKET = NULL;\n log_info(\"Control port exiting.\");\n taskexit(0);\n\nerror:\n log_info(\"Control port exiting with error.\");\n zmq_close(CONTROL_SOCKET);\n CONTROL_SOCKET = NULL;\n taskexit(1);\n}\n\n\nvoid Control_port_start()\n{\n taskcreate(Control_task, NULL, 32 * 1024);\n}\n\nint Control_port_stop()\n{\n int rc = 0;\n\n if(CONTROL_SOCKET != NULL) {\n rc = zmq_close(CONTROL_SOCKET);\n check(rc == 0, \"Failed to close control socket\");\n\n \/\/ TODO: wake up the control task.\n \/\/ it doesn't seem to notice that the socket has been closed.\n }\n\nerror:\n return rc;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"dbc990bd351f8639dde331a0a4c426f3a1121ec0","subject":"improve formatting","message":"improve formatting\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"libhext\/ragel\/hext-machine.rl","new_file":"libhext\/ragel\/hext-machine.rl","new_contents":"%%{\n# This ragel machine lexes hext. It is embedded in Parser::parse.\nmachine hext;\n\naction error {\n this->throw_unexpected();\n}\n\naction act_newline {\n if( rule_start )\n {\n rule.consume_rule();\n rule_start = false;\n }\n else\n {\n \/\/ If a newline is encountered, reset indent, because the spaces could have\n \/\/ been used to indent a comment.\n rule.reset_indent();\n }\n}\n\n\n#### HELPERS ###################################################################\nattr_name = ( alpha (alnum | '-' | '_')** );\nbuiltin_name = ( alpha (alnum | '-' | '_')** );\ncap_var = ( [^\/{}][^\/{}]** );\nmatch_literal = ( ( [^\"] | '\\\\\"' )** );\nregex_content = ( ( [^\/] | '\\\\\/' )** );\n\n\n#### NTH_PATTERN ###############################################################\n# nth_pattern is used in some traits, e.g. nth-child(nth_pattern).\n# Examples: :nth-child(1) :nth-child(even) :nth-child(2n) :nth-child(2n+1)\nnth_pattern = (\n # nth-child(even)\n ( 'even' %{ pattern.set_nth_mul(\"2\"); pattern.set_nth_add(\"0\"); } )\n |\n\n # nth-child(odd)\n ( 'odd' %{ pattern.set_nth_mul(\"2\"); pattern.set_nth_add(\"1\"); } )\n |\n\n # nth-child(2n+1)\n ( ( [0-9]+ >{ TK_START; } %{ TK_STOP; pattern.set_nth_mul(tok); } )\n ( 'n' %{ pattern.set_nth_add(\"0\"); }\n ( '+'\n ( [0-9]+ >{ TK_START; } %{ TK_STOP; pattern.set_nth_add(tok); } )\n )?\n )?\n )\n);\n\n\n#### TRAITS ####################################################################\ntrait = ':' (\n # :empty\n ( 'empty' %{ pattern.consume_child_count(\"0\"); } )\n |\n\n # :child-count(5)\n ( 'child-count('\n ( [0-9]+ >{ TK_START; } %{ TK_STOP; pattern.consume_child_count(tok); } )\n ')' )\n |\n\n # :nth-child(2n+1)\n ( 'nth-child(' nth_pattern ')' %{ pattern.consume_nth_child(); } )\n |\n\n # :nth-last-child(2n+1)\n ( 'nth-last-child(' nth_pattern ')'\n %{ pattern.consume_nth_child(NthOff::Back); } )\n |\n\n # :nth-of-type(2n+1)\n ( 'nth-of-type(' nth_pattern ')'\n %{ pattern.consume_nth_child(NthOff::Front, rule.tag()); } )\n |\n\n # :first-child\n ( 'first-child' %{ pattern.set_nth_mul(\"1\"); pattern.consume_nth_child(); } )\n |\n\n # :first-of-type\n ( 'first-of-type'\n %{ pattern.set_nth_mul(\"1\");\n pattern.consume_nth_child(NthOff::Front, rule.tag()); } )\n |\n\n # :last-child\n ( 'last-child'\n %{ pattern.set_nth_mul(\"1\"); pattern.consume_nth_child(NthOff::Back); } )\n |\n\n # :last-of-type\n ( 'last-of-type'\n %{ pattern.set_nth_mul(\"1\");\n pattern.consume_nth_child(NthOff::Back, rule.tag()); } )\n |\n\n # :nth-last-of-type(2n+1)\n ( 'nth-last-of-type(' nth_pattern ')'\n %{ pattern.consume_nth_child(NthOff::Back, rule.tag()); } )\n |\n\n # :only-child\n ( 'only-child'\n %{ pattern.set_nth_mul(\"1\"); pattern.consume_nth_child();\n pattern.set_nth_mul(\"1\"); pattern.consume_nth_child(NthOff::Back); } )\n);\n\n\n# Literal value, e.g. attr=\"literal\"\nliteral_value = '\"' ( match_literal\n >{ TK_START; } %{ TK_STOP; pattern.set_attr_literal(tok); }\n) '\"';\n\n\n# Regular expression\nregex = '\/' ( regex_content\n >{ TK_START; }\n %{ TK_STOP; pattern.set_regex_str(tok); }\n ) '\/'\n # regex modifier:\n # 'i': case insensitive\n # 'c': collate (locale aware character groups)\n # '!': negate regex\n # Capture all characters to provide better error diagnostics.\n ( [a-zA-Z!]+ )?\n >{ TK_START; }\n %{ TK_STOP;\n if( !pattern.set_regex_mod(tok) )\n this->throw_unknown_token(tok, \"regex modifier\");\n try{ pattern.consume_regex(); }\n catch( const boost::regex_error& e )\n { \/\/ Mark whole regex as error, including slashes\n auto mark_len = pattern.regex_length() + tok.size() + 2;\n this->throw_regex_error(mark_len, e.code()); } };\n\n\n#### ATTRIBUTES ################################################################\nattributes = (\n ' '+\n (\n # attribute name\n (\n # builtin function, e.g. @text\n ( '@'\n ( builtin_name\n >{ TK_START; }\n %{ TK_STOP; { if( !pattern.set_builtin(tok) )\n this->throw_unknown_token(tok, \"builtin\"); } } ) )\n |\n\n # html node attribute, e.g. class\n ( attr_name >{ TK_START; } %{ TK_STOP; pattern.set_attr_name(tok); } )\n )\n\n # attribute value\n (\n # literal operator, e.g. @text^=\"Lorem \", class~=\"menu\"\n ( ( '^' | '*' | '!' | '~' | '$' ) >{ pattern.set_literal_op(*this->p); }\n '=' literal_value )\n |\n\n # capture variable, match regex or match literal\n ( '='\n (\n # capture variable, e.g. id={html_node_attr_id}, @text={heading}\n ( '{' cap_var >{ TK_START; }\n %{ TK_STOP;\n if( rule.path() )\n this->throw_error(\"Paths cannot have captures\", tok.size());\n pattern.set_cap_var(tok); }\n # optional capture regex, e.g. @text={time\/(\\d\\d:\\d\\d)\/}\n regex?\n '}' )\n |\n\n # match regex, e.g. id=\/article_[0-9]+\/\n regex\n |\n\n # match literal, e.g. id=\"article_23\"\n literal_value\n )\n )\n )?\n ) %{ pattern.consume_pattern(); }\n)+;\n\n\n#### RULES #####################################################################\nmain := (\n # comments may be prefixed with any spaces and must terminate with a newline\n ( ' '* '#' (any - '\\n')* ( '\\n' %act_newline ) )\n |\n\n # rules\n (\n # groups of two spaces indent a rule\n ( ' ' %{ rule.increment_indent(); } )*\n\n # a rule starts with either '<' (direct descendant), '>' (any descendant)\n # or '~' (path)\n ( ( ( '<' )\n |\n ( '>' %{ rule.set_any_descendant(true); } )\n |\n ( '~' %{ rule.set_any_descendant(true); rule.set_path(true); } )\n ) %{ rule_start = true; }\n )\n\n # a rule can be optional, e.g. { TK_START; }\n %{ TK_STOP;\n if( !rule.set_tag_name(tok) )\n this->throw_unknown_token(tok, \"html-tag\"); }\n )?\n\n # a rule can have multiple traits, e.g. ' %{ rule.set_closed(true); } )?\n )\n\n # rules and comments may terminate with a newline\n ( '\\n' %act_newline )?\n)** $err(error) $\/act_newline $\/{ fbreak; };\n\n}%%\n","old_contents":"%%{\n# This ragel machine lexes hext. It is embedded in Parser::parse.\nmachine hext;\n\naction error {\n this->throw_unexpected();\n}\n\naction act_newline {\n if( rule_start )\n {\n rule.consume_rule();\n rule_start = false;\n }\n else\n {\n \/\/ If a newline is encountered, reset indent, because the spaces could have\n \/\/ been used to indent a comment.\n rule.reset_indent();\n }\n}\n\n\n#### HELPERS ###################################################################\nattr_name = ( alpha (alnum | '-' | '_')** );\nbuiltin_name = ( alpha (alnum | '-' | '_')** );\ncap_var = ( [^\/{}][^\/{}]** );\nmatch_literal = ( ( [^\"] | '\\\\\"' )** );\nregex_content = ( ( [^\/] | '\\\\\/' )** );\n\n\n#### NTH_PATTERN ###############################################################\n# nth_pattern is used in some traits, e.g. nth-child(nth_pattern).\n# Examples: :nth-child(1) :nth-child(even) :nth-child(2n) :nth-child(2n+1)\nnth_pattern = (\n # nth-child(even)\n ( 'even' %{ pattern.set_nth_mul(\"2\"); pattern.set_nth_add(\"0\"); } )\n |\n\n # nth-child(odd)\n ( 'odd' %{ pattern.set_nth_mul(\"2\"); pattern.set_nth_add(\"1\"); } )\n |\n\n # nth-child(2n+1)\n ( ( [0-9]+ >{ TK_START; } %{ TK_STOP; pattern.set_nth_mul(tok); } )\n ( 'n' %{ pattern.set_nth_add(\"0\"); }\n ( '+'\n ( [0-9]+ >{ TK_START; } %{ TK_STOP; pattern.set_nth_add(tok); } )\n )?\n )?\n )\n);\n\n\n#### TRAITS ####################################################################\ntrait = ':' (\n # :empty\n ( 'empty' %{ pattern.consume_child_count(\"0\"); } )\n |\n\n # :child-count(5)\n ( 'child-count('\n ( [0-9]+ >{ TK_START; } %{ TK_STOP; pattern.consume_child_count(tok); } )\n ')' )\n |\n\n # :nth-child(2n+1)\n ( 'nth-child(' nth_pattern ')' %{ pattern.consume_nth_child(); } )\n |\n\n # :nth-last-child(2n+1)\n ( 'nth-last-child(' nth_pattern ')'\n %{ pattern.consume_nth_child(NthOff::Back); } )\n |\n\n # :nth-of-type(2n+1)\n ( 'nth-of-type(' nth_pattern ')'\n %{ pattern.consume_nth_child(NthOff::Front, rule.tag()); } )\n |\n\n # :first-child\n ( 'first-child' %{ pattern.set_nth_mul(\"1\"); pattern.consume_nth_child(); } )\n |\n\n # :first-of-type\n ( 'first-of-type'\n %{ pattern.set_nth_mul(\"1\");\n pattern.consume_nth_child(NthOff::Front, rule.tag()); } )\n |\n\n # :last-child\n ( 'last-child'\n %{ pattern.set_nth_mul(\"1\"); pattern.consume_nth_child(NthOff::Back); } )\n |\n\n # :last-of-type\n ( 'last-of-type'\n %{ pattern.set_nth_mul(\"1\");\n pattern.consume_nth_child(NthOff::Back, rule.tag()); } )\n |\n\n # :nth-last-of-type(2n+1)\n ( 'nth-last-of-type(' nth_pattern ')'\n %{ pattern.consume_nth_child(NthOff::Back, rule.tag()); } )\n |\n\n # :only-child\n ( 'only-child'\n %{ pattern.set_nth_mul(\"1\"); pattern.consume_nth_child();\n pattern.set_nth_mul(\"1\"); pattern.consume_nth_child(NthOff::Back); } )\n);\n\n\n# attr=\"literal\"\nliteral_value = '\"' ( match_literal\n >{ TK_START; } %{ TK_STOP; pattern.set_attr_literal(tok); }\n) '\"';\n\n# regular expression\nregex = '\/' ( regex_content\n >{ TK_START; }\n %{ TK_STOP; pattern.set_regex_str(tok); }\n ) '\/'\n # regex modifier:\n # 'i': case insensitive\n # 'c': collate (locale aware character groups)\n # '!': negate regex\n # Capture all characters to provide better error diagnostics.\n ( [a-zA-Z!]+ )?\n >{ TK_START; }\n %{ TK_STOP;\n if( !pattern.set_regex_mod(tok) )\n this->throw_unknown_token(tok, \"regex modifier\");\n try{ pattern.consume_regex(); }\n catch( const boost::regex_error& e )\n { \/\/ Mark whole regex as error, including slashes\n auto mark_len = pattern.regex_length() + tok.size() + 2;\n this->throw_regex_error(mark_len, e.code()); } };\n\n\n#### ATTRIBUTES ################################################################\nattributes = (\n ' '+\n (\n # attribute name\n (\n # builtin function, e.g. @text\n ( '@'\n ( builtin_name\n >{ TK_START; }\n %{ TK_STOP; { if( !pattern.set_builtin(tok) )\n this->throw_unknown_token(tok, \"builtin\"); } } ) )\n |\n\n # html node attribute, e.g. class\n ( attr_name >{ TK_START; } %{ TK_STOP; pattern.set_attr_name(tok); } )\n )\n\n # attribute value\n (\n # literal operator, e.g. @text^=\"Lorem \", class~=\"menu\"\n ( ( '^' | '*' | '!' | '~' | '$' ) >{ pattern.set_literal_op(*this->p); }\n '=' literal_value )\n |\n\n # capture variable, match regex or match literal\n ( '='\n (\n # capture variable, e.g. id={html_node_attr_id}, @text={heading}\n ( '{' cap_var >{ TK_START; }\n %{ TK_STOP;\n if( rule.path() )\n this->throw_error(\"Paths cannot have captures\", tok.size());\n pattern.set_cap_var(tok); }\n # optional capture regex, e.g. @text={time\/(\\d\\d:\\d\\d)\/}\n regex?\n '}' )\n |\n\n # match regex, e.g. id=\/article_[0-9]+\/\n regex\n |\n\n # match literal, e.g. id=\"article_23\"\n literal_value\n )\n )\n )?\n ) %{ pattern.consume_pattern(); }\n)+;\n\n\n#### RULES #####################################################################\nmain := (\n # comments may be prefixed with any spaces and must terminate with a newline\n ( ' '* '#' (any - '\\n')* ( '\\n' %act_newline ) )\n |\n\n (\n # groups of two spaces indent a rule\n ( ' ' %{ rule.increment_indent(); } )*\n\n # a rule starts with either '<' (direct descendant), '>' (any descendant)\n # or '~' (path)\n ( ( ( '<' )\n |\n ( '>' %{ rule.set_any_descendant(true); } )\n |\n ( '~' %{ rule.set_any_descendant(true); rule.set_path(true); } )\n ) %{ rule_start = true; }\n )\n\n # a rule can be optional, e.g. { TK_START; }\n %{ TK_STOP;\n if( !rule.set_tag_name(tok) )\n this->throw_unknown_token(tok, \"html-tag\"); }\n )?\n\n # a rule can have multiple traits, e.g. ' %{ rule.set_closed(true); } )?\n )\n\n # rules and comments may terminate with a newline\n ( '\\n' %act_newline )?\n)** $err(error) $\/act_newline $\/{ fbreak; };\n\n}%%\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"6aaaf6ff98551eb42120006403a4129aa586961b","subject":"* remove test code","message":"* remove test code\n","repos":"nineties\/amber","old_file":"rlc1\/main.rl","new_file":"rlc1\/main.rl","new_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: main.rl 2010-04-07 20:15:03 nineties $\n %);\n\ninclude(stddef, code);\n\nexport main;\n\nprogname : NULL;\n\n(% rename xxx.rl to xxx.p1 %);\nchange_suffix: (p0, p1) {\n allocate(3);\n x0 = strlen(p0);\n x1 = strlen(p1);\n x2 = memalloc(x0 - 2 + x1 + 1);\n memcpy(x2, p0, x0 - 2);\n memcpy(x2 + x0 - 2, p1, x1);\n wch(x2, x0 - 2 + x1, '\\0');\n return x2;\n};\n\n(% p0: asm filename, p1: header filename, p2:rowl filename %);\ncompile: (p0, p1, p2) {\n allocate(4);\n\n init_typing();\n\n puts(\"compile \");\n puts(p2);\n putc('\\n');\n\n (% lex and parse %);\n puts(\"> parsing...\\n\");\n x1 = parse(p2);\n\n (% type check %);\n puts(\"> typing...\\n\");\n x2 = typing(x1);\n\n (% generate header file %);\n puts(\"> generating header...\\n\");\n headergen(p1, x2);\n\n (% translate to two address code %);\n puts(\"> translating to tcode...\\n\");\n x3 = tcodegen(x2);\n\n (% generate assembly %);\n puts(\"> generating assembly...\\n\");\n x0 = open_out(p0);\n asmgen(x0, x3);\n close_out(x0);\n puts(\"finished\\n\");\n};\n\nascmd: [\"\/usr\/bin\/as\", NULL, \"-o\", NULL, NULL];\n(% p0: object filename, p1: asm filename %);\nassemble: (p0, p1) {\n allocate(1);\n x0 = fork(); (% pid %);\n if (x0 == 0) {\n\t(% child %);\n\tascmd[1] = p1;\n\tascmd[3] = p0;\n\texecve(ascmd[0], ascmd, 0);\n } else {\n\twaitpid(-1, &x1, 0);\n };\n};\n\n(% p0: argc, p1: argv %);\nmain: (p0, p1) {\n allocate(4);\n\n progname = strdup(p1[0]);\n\n x0 = 1;\n while (x0 < p0) {\n\tx1 = change_suffix(p1[x0], \"s\"); (% name of assembly source file %);\n\tx2 = change_suffix(p1[x0], \"o\"); (% name of object file %);\n x3 = change_suffix(p1[x0], \"rli\"); (% name of header file %);\n\n\tunlink(x1);\n\tunlink(x2);\n unlink(x3);\n\n compile(x1, x3, p1[x0]);\n\tassemble(x2, x1);\n x0 = x0 + 1;\n };\n return 0;\n};\n\n","old_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: main.rl 2010-04-07 19:49:03 nineties $\n %);\n\ninclude(stddef, code);\n\nexport main;\n\nprogname : NULL;\n\n(% rename xxx.rl to xxx.p1 %);\nchange_suffix: (p0, p1) {\n allocate(3);\n x0 = strlen(p0);\n x1 = strlen(p1);\n x2 = memalloc(x0 - 2 + x1 + 1);\n memcpy(x2, p0, x0 - 2);\n memcpy(x2 + x0 - 2, p1, x1);\n wch(x2, x0 - 2 + x1, '\\0');\n return x2;\n};\n\n(% p0: asm filename, p1: header filename, p2:rowl filename %);\ncompile: (p0, p1, p2) {\n allocate(4);\n\n init_typing();\n\n puts(\"compile \");\n puts(p2);\n putc('\\n');\n\n (% lex and parse %);\n puts(\"> parsing...\\n\");\n x1 = parse(p2);\n\n (% type check %);\n puts(\"> typing...\\n\");\n x2 = typing(x1);\n\n (% generate header file %);\n puts(\"> generating header...\\n\");\n headergen(p1, x2);\n\n (% translate to two address code %);\n puts(\"> translating to tcode...\\n\");\n x3 = tcodegen(x2);\n\n (% generate assembly %);\n puts(\"> generating assembly...\\n\");\n x0 = open_out(p0);\n asmgen(x0, x3);\n close_out(x0);\n puts(\"finished\\n\");\n};\n\nascmd: [\"\/usr\/bin\/as\", NULL, \"-o\", NULL, NULL];\n(% p0: object filename, p1: asm filename %);\nassemble: (p0, p1) {\n allocate(1);\n x0 = fork(); (% pid %);\n if (x0 == 0) {\n\t(% child %);\n\tascmd[1] = p1;\n\tascmd[3] = p0;\n\texecve(ascmd[0], ascmd, 0);\n } else {\n\twaitpid(-1, &x1, 0);\n };\n};\n\n(% p0: argc, p1: argv %);\nmain: (p0, p1) {\n allocate(4);\n\n progname = strdup(p1[0]);\n\n x0 = 1;\n while (x0 < p0) {\n\tx1 = change_suffix(p1[x0], \"s\"); (% name of assembly source file %);\n\tx2 = change_suffix(p1[x0], \"o\"); (% name of object file %);\n x3 = change_suffix(p1[x0], \"rli\"); (% name of header file %);\n\n\tunlink(x1);\n\tunlink(x2);\n unlink(x3);\n\n compile(x1, x3, p1[x0]);\n\tassemble(x2, x1);\n x0 = x0 + 1;\n };\n return 0;\n};\n\n\nfib: (p0) {\n if (p0) {\n return p0 * fib(p0-1);\n };\n return 1;\n};\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"c472ceac6fa9dbf7553a7841326cac17e801db88","subject":"Docs for the shared Ragel grammar.","message":"Docs for the shared Ragel grammar.\n","repos":"altmetric\/oga,ttasanen\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,ttasanen\/oga,altmetric\/oga,ttasanen\/oga,jeffreybaird\/oga,YorickPeterse\/oga,ttasanen\/oga,dfockler\/oga,dfockler\/oga,YorickPeterse\/oga,jeffreybaird\/oga,YorickPeterse\/oga,jeffreybaird\/oga,dfockler\/oga,altmetric\/oga,ttasanen\/oga,altmetric\/oga,altmetric\/oga","old_file":"ext\/ragel\/base_lexer.rl","new_file":"ext\/ragel\/base_lexer.rl","new_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n ^dquote+ => {\n callback(\"on_string\", data, encoding, ts, te);\n };\n\n dquote => { fret; };\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n ^squote+ => {\n callback(\"on_string\", data, encoding, ts, te);\n };\n\n squote => { fret; };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Lex the public\/system IDs as regular strings.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n callback_simple(\"on_cdata_start\");\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n any* cdata_end => {\n callback(\"on_text\", data, encoding, ts, te - 3);\n callback_simple(\"on_cdata_end\");\n fret;\n };\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n callback_simple(\"on_comment_start\");\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n any* comment_end => {\n callback(\"on_text\", data, encoding, ts, te - 3);\n callback_simple(\"on_comment_end\");\n fret;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n callback(\"on_element_start\", data, encoding, ts + 1, te);\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"on_newline\");\n };\n\n # Attribute names.\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n callback_simple(\"on_element_open_end\");\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n ^('<' | '>')+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","old_contents":"%%machine base_lexer;\n\n%%{\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n ^dquote+ => {\n callback(\"on_string\", data, encoding, ts, te);\n };\n\n dquote => { fret; };\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n ^squote+ => {\n callback(\"on_string\", data, encoding, ts, te);\n };\n\n squote => { fret; };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' {\n callback(\"on_doctype_type\", data, encoding, ts, te);\n };\n\n # Lex the public\/system IDs as regular strings.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => {\n callback(\"on_doctype_name\", data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(\"on_doctype_end\");\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n callback_simple(\"on_cdata_start\");\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n any* cdata_end => {\n callback(\"on_text\", data, encoding, ts, te - 3);\n callback_simple(\"on_cdata_end\");\n fret;\n };\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n callback_simple(\"on_comment_start\");\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n any* comment_end => {\n callback(\"on_text\", data, encoding, ts, te - 3);\n callback_simple(\"on_comment_end\");\n fret;\n };\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(\"on_xml_decl_start\");\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n callback_simple(\"on_xml_decl_end\");\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n callback(\"on_element_start\", data, encoding, ts + 1, te);\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => {\n callback_simple(\"on_newline\");\n };\n\n # Attribute names.\n identifier => {\n callback(\"on_attribute\", data, encoding, ts, te);\n };\n\n # Attribute values.\n dquote => { fcall string_dquote; };\n squote => { fcall string_squote; };\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n callback_simple(\"on_element_open_end\");\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n callback_simple(\"on_element_end\");\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n ^('<' | '>')+ => {\n callback(\"on_text\", data, encoding, ts, te);\n };\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"fbd5b695d3ed35c411d6c630e46964cd9ba1b896","subject":"Add more fields to the scanner","message":"Add more fields to the scanner\n","repos":"yanfali\/gomkv","old_file":"src\/handbrake\/handbrake.rl","new_file":"src\/handbrake\/handbrake.rl","new_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\nfunc parseOutput(data string) (HandBrakeMeta) {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\t_,_,_,_ = top, ts, te, act\n\tstack := []int{0}\n\t_ = eof\n\tline := 1\n\tcapture := false\n\tcsp := 0\n\tmeta := HandBrakeMeta{}\n\tfmt.Printf(\"%02d: \", line)\n\t_ = capture\n\t_ = csp\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\ttitle := |*\n\t\t\t(alnum|space)+[.]*alnum* => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tduration := |*\n\t\t\tspace*;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t*|;\n\t\tpaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1,4} \"\/\" digit{1,4} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tdaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1} . \".\" . digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tfps := |*\n\t\t\t\"\\n\" => { ts=ts-12; fmt.Printf(\"%s\\n\", data[ts:te-4]); fret; };\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tspace+ \"+\" space+ \"stream:\" space* @{ fcall title; } |\n\t\t\tspace+ \"+\" space+ \"duration:\" @{ fcall duration; } |\n\t\t\tspace+ \"+\" space+ \"size:\" @{ fcall picture; } |\n\t\t\tspace+ \"+\" any+ \"pixel\" space+ \"aspect:\" @{ fcall paspect; } |\n\t\t\tspace+ \"+\" any+ \"display\" space+ \"aspect:\" @{ fcall daspect; } |\n\t\t\tspace+ \"+\" any+ \"fps\" @{ fcall fps; } |\n\t\t\tspace+ \"+\" space+ \"autocrop:\" @{ fcall crop; }\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","old_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\nfunc parseOutput(data string) (HandBrakeMeta) {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\t_,_,_,_ = top, ts, te, act\n\tstack := []int{0}\n\t_ = eof\n\tline := 1\n\tcapture := false\n\tcsp := 0\n\tmeta := HandBrakeMeta{}\n\tfmt.Printf(\"%02d: \", line)\n\t_ = capture\n\t_ = csp\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\ttitle := |*\n\t\t\t(alnum|space)+[.]*alnum* => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tduration := |*\n\t\t\tspace*;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t*|;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tspace+ \"+\" space+ \"stream:\" space* @{ fcall title; } |\n\t\t\tspace+ \"+\" space+ \"duration:\" @{ fcall duration; } |\n\t\t\tspace+ \"+\" space+ \"size:\" @{ fcall picture; }\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"ede63072e714304e931af936fa924ae1608329fc","subject":"Add missing comma","message":"Add missing comma\n","repos":"ajwans\/libtoml","old_file":"toml_parse.rl","new_file":"toml_parse.rl","new_contents":"#include \"toml.h\"\n#include \"toml_private.h\"\n\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct toml_stack_item {\n\tstruct list_node list;\n\tenum toml_type list_type;\n\tstruct toml_node *node;\n};\n\nstatic size_t\nutf32ToUTF8(char* dst, int len, uint32_t utf32)\n{\n\tif (utf32 < 0x80) {\n\t\tif (len < 1)\n\t\t\treturn 0;\n\n\t\t*dst = (uint8_t)utf32;\n\t\treturn 1;\n\t}\n\n\tif (utf32 < 0x000800)\n\t{\n\t\tif (len < 2)\n\t\t\treturn 0;\n\n\t\tdst[0] = (uint8_t)(0xc0 | (utf32 >> 6));\n\t\tdst[1] = (uint8_t)(0x80 | (utf32 & 0x3f));\n\t\treturn 2;\n\t}\n\n\tif (utf32 < 0x10000)\n\t{\n\t\tif (len < 3)\n\t\t\treturn 0;\n\n\t\tdst[0] = (uint8_t)(0xE0 | (utf32 >> 12));\n\t\tdst[1] = (uint8_t)(0x80 | ((utf32 & 0x0FC0) >> 6));\n\t\tdst[2] = (uint8_t)(0x80 | (utf32 & 0x003F));\n\t\treturn 3;\n\t}\n\n\tif (len < 4)\n\t\treturn 0;\n\n\tdst[0] = (uint8_t)(0xF0 | (utf32 >> 18));\n\tdst[1] = (uint8_t)(0x80 | ((utf32 & 0x03F000) >> 12));\n\tdst[2] = (uint8_t)(0x80 | ((utf32 & 0x000FC0) >> 6));\n\tdst[3] = (uint8_t)(0x80 | (utf32 & 0x00003F));\n\n\treturn 4;\n}\n\nbool add_node_to_tree(struct list_head* list_stack, struct toml_node* cur_table, struct toml_node* node, char* name, char** parse_error, int* malloc_error, int cur_line)\n{\n\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(list_stack, struct toml_stack_item, list);\n\n\tif (cur_list) {\n\t\tif (cur_list->list_type && cur_list->list_type != node->type) {\n\t\t\tasprintf(parse_error,\n\t\t\t\t\t\"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\ttoml_type_to_str(node->type), cur_line);\n\t\t\treturn false;\n\t\t}\n\t\tcur_list->list_type = node->type;\n\n\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\tif (!item) {\n\t\t\t*malloc_error = 1;\n\t\t\treturn false;\n\t\t}\n\n\t\tmemcpy(&item->node, node, sizeof(*node));\n\t\titem->node.name = NULL;\n\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\t} else {\n\t\tstruct toml_table_item *item = malloc(sizeof(*item));\n\t\tif (!item) {\n\t\t\t*malloc_error = 1;\n\t\t\treturn false;\n\t\t}\n\t\tmemcpy(&item->node, node, sizeof(*node));\n\t\titem->node.name = name;\n\t\tlist_add_tail(&cur_table->value.map, &item->map);\n\t}\n\n\treturn true;\n}\n\n%%{\n\tmachine toml;\n\n\twhitespace = [\\t ]*;\n\n\tname = (print - ('#'|'='|'\"'|whitespace))+\t\t\t\t\t>{ts = p;};\n\tname_in_double_quotes = (print - '\"')+\t\t\t\t\t\t>{ts = p;};\n\tname_in_single_quotes = (print - \"'\")+\t\t\t\t\t\t>{ts = p;};\n\ttablename = (print - ('#'|']'|'['|'\"'|whitespace))+\t\t>{ts = p;};\n\ttablename_in_double_quotes = (print - '\"')+\t\t\t\t>{ts = p;};\n\ttablename_in_single_quotes = (print - \"'\")+\t\t\t\t>{ts = p;};\n\n\taction saw_key {\n\t\tstruct toml_table_item* item = NULL;\n\t\tlist_for_each(&cur_table->value.map, item, map) {\n\t\t\tif (strncmp(item->node.name, ts, namelen + 1) != 0)\n\t\t\t\tcontinue;\n\n\t\t\tasprintf(&parse_error,\n\t\t\t\t\t\"duplicate key %s line %d\\n\",\n\t\t\t\t\titem->node.name, cur_line);\n\t\t\tfbreak;\n\t\t}\n\n\t\twhile (ts[namelen] == ' ' || ts[namelen] == '\\t')\n\t\t\tnamelen--;\n\n\t\tname = strndup(ts, namelen + 1);\n\t}\n\n\taction saw_bool {\n\t\tstruct toml_node node;\n\n\t\tnode.type = TOML_BOOLEAN;\n\t\tnode.value.integer = number;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_int {\n\t\tchar*\t\t\t\tte = p;\n\t\tstruct toml_node\tnode;\n\n\t\tnode.type = TOML_INT;\n\t\tnode.value.integer = negative ? -number : number;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_float {\n\t\tchar*\t\t\t\tte = p;\n\t\tstruct toml_node\tnode;\n\n\t\tfloating = strtod(ts, &te);\n\n\t\tnode.type = TOML_FLOAT;\n\t\tnode.value.floating.value = floating;\n\t\tnode.value.floating.precision = precision;\n\n\t\tif (!node.value.floating.precision && !exponent) {\n\t\t\tasprintf(&parse_error, \"bad float\\n\");\n\t\t\tfbreak;\n\t\t}\n\n\t\texponent = false;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_string {\n\t\tint\t\t\t\t\tlen = strp - string + 1;\n\t\tstruct toml_node\tnode;\n\n\t\t*strp = 0;\n\n\t\tnode.type = TOML_STRING;\n\t\tnode.value.string = malloc(len);\n\t\tif (!node.value.string) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\t\tmemcpy(node.value.string, string, len);\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_date {\n\t\tchar*\tte = p;\n\t\tstruct\ttoml_node node;\n\n\t\tnode.type = TOML_DATE;\n\t\tnode.value.rfc3339_time.epoch = timegm(&tm);\n\t\tnode.value.rfc3339_time.offset_sign_negative = time_offset_is_negative;\n\t\tnode.value.rfc3339_time.offset = time_offset;\n\t\tnode.value.rfc3339_time.offset_is_zulu = time_offset_is_zulu;\n\t\tif (secfrac_ptr)\n\t\t\tnode.value.rfc3339_time.sec_frac = strtol(secfrac_ptr, &te, 10);\n\t\telse\n\t\t\tnode.value.rfc3339_time.sec_frac = -1;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction start_list {\n\t\tstruct toml_node *node;\n\n\t\t\/*\n\t\t * if the list stack is empty add this list to the table\n\t\t * otherwise it should be added the to list on top of the stack\n\t\t *\/\n\t\tif (list_empty(&list_stack)) {\n\t\t\tstruct toml_table_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\t\/* first add it to the table *\/\n\t\t\titem->node.type = TOML_LIST;\n\t\t\tlist_head_init(&item->node.value.list);\n\t\t\tlist_add_tail(&cur_table->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\tnode = &item->node;\n\t\t} else {\n\t\t\tstruct toml_stack_item* tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\t\tif (tail->list_type && tail->list_type != TOML_LIST) {\n\t\t\t\tasprintf(&parse_error,\n\t\t\t\t\t\t\"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(tail->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_BOOLEAN), cur_line);\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\ttail->list_type = TOML_LIST;\n\t\t\titem->node.type = TOML_LIST;\n\t\t\titem->node.name = NULL;\n\t\t\tlist_head_init(&item->node.value.list);\n\n\t\t\tlist_add_tail(&tail->node->value.list, &item->list);\n\t\t\tnode = &item->node;\n\t\t}\n\n\t\t\/* push this list onto the stack *\/\n\t\tstruct toml_stack_item *stack_item = malloc(sizeof(*stack_item));\n\t\tif (!stack_item) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\t\tstack_item->node = node;\n\t\tstack_item->list_type = 0;\n\t\tlist_add_tail(&list_stack, &stack_item->list);\n\t}\n\n\taction end_list {\n\t\tstruct toml_stack_item *tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tlist_del(&tail->list);\n\t\tfree(tail);\n\n\t\tif (!list_empty(&list_stack))\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_inline_table {\n\t\tchar*\t\t\t\t\ttablename = name;\n\t\tstruct toml_table_item*\titem;\n\t\tstruct toml_node*\t\tplace = cur_table ? cur_table : toml_root;\n\t\tbool\t\t\t\t\tfound = false;\n\n\t\tinline_table = true;\n\n\t\tlist_for_each(&place->value.map, item, map) {\n\t\t\tif (strcmp(item->node.name, tablename) != 0)\n\t\t\t\tcontinue;\n\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (found)\n\t\t{\n\t\t\tasprintf(&parse_error, \"duplicate entry %s\\n\", tablename);\n\t\t\tfbreak;\n\t\t}\n\n\t\titem = malloc(sizeof(*item));\n\t\tif (!item) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\n\t\titem->node.name = strdup(tablename);\n\t\titem->node.type = TOML_TABLE;\n\t\tlist_head_init(&item->node.value.map);\n\t\tlist_add_tail(&place->value.map, &item->map);\n\n\t\tcur_table = &item->node;\n\n\t\tfree(tablename);\n\t}\n\n\taction saw_table {\n\t\tchar *ancestor, *tofree = NULL, *tablename;\n\t\tint item_added = 0;\n\t\tint len = (int)(p-ts);\n\n\t\tstruct toml_node *place = toml_root;\n\n\t\ttofree = tablename = strndup(ts, len);\n\n\t\twhile ((ancestor = strsep(&tablename, \".\"))) {\n\t\t\tstruct toml_table_item *item = NULL;\n\t\t\tint found = 0;\n\n\t\t\tif (strcmp(ancestor, \"\") == 0) {\n\t\t\t\tasprintf(&parse_error, \"empty implicit table\");\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tlist_for_each(&place->value.map, item, map) {\n\t\t\t\tif (strcmp(item->node.name, ancestor) == 0) {\n\t\t\t\t\tplace = &item->node;\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found)\n\t\t\t\tcontinue;\n\n\t\t\t\/* this is the auto-vivification *\/\n\t\t\titem = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\titem->node.name = strdup(ancestor);\n\t\t\titem->node.type = TOML_TABLE;\n\t\t\tlist_head_init(&item->node.value.map);\n\t\t\tlist_add_tail(&place->value.map, &item->map);\n\n\t\t\tplace = &item->node;\n\t\t\titem_added = 1;\n\t\t}\n\n\t\tif (!item_added) {\n\t\t\tasprintf(&parse_error, \"Duplicate item %.*s\", len, ts);\n\t\t\tfbreak;\n\t\t}\n\n\t\tif (place->type != TOML_TABLE) {\n\t\t\tasprintf(&parse_error, \"Attempt to overwrite table %.*s\", len, ts);\n\t\t\tfbreak;\n\t\t}\n\n\t\tfree(tofree);\n\n\t\tcur_table = place;\n\t}\n\n\taction saw_table_array {\n\t\tint\t\tret;\n\t\tchar*\ttableName;\n\n\t\ttableName = strndup(ts, (int)(p-ts-1));\n\t\tret = SawTableArray(toml_root, tableName, &cur_table, &parse_error);\n\t\tfree(tableName);\n\t\tif (ret)\n\t\t\tfbreak;\n\t}\n\n\taction saw_utf16 {\n\t\tUChar\t\tutf16[2] = { 0 };\n\t\tint32_t\t\tlen = sizeof(string) - (strp - string);\n\t\tint32_t\t\toutLen;\n\t\tUErrorCode\terr = U_ZERO_ERROR;\n\t\tchar\t\tutf16_str[5] = { 0 };\n\n\t\tmemcpy(utf16_str, utf_start, 4);\n\t\t*utf16 = strtoul(utf16_str, NULL, 16);\n\n\t\tu_strToUTF8(strp, len, &outLen, utf16, 1, &err);\n\t\tstrp += outLen;\n\t\tfret;\n\t}\n\n\taction saw_utf32 {\n\t\tuint32_t\tutf32;\n\t\tint32_t\t\tlen = sizeof(string) - (strp - string);\n\t\tint32_t\t\toutLen;\n\t\tchar\t\tutf32_str[9] = { 0 };\n\n\t\tmemcpy(utf32_str, utf_start, 8);\n\t\tutf32 = strtoul(utf32_str, NULL, 16);\n\n\t\toutLen = utf32ToUTF8(strp, len, utf32);\n\t\tstrp += outLen;\n\t\tfret;\n\t}\n\n\taction bad_escape {\n\t\tasprintf(&parse_error, \"bad escape \\\\%c\", *p);\n\t\tfbreak;\n\t}\n\n\tlines = (\n\t\tstart: (\n\t\t\t# count the indentation to know where the tables end\n\t\t\t'#'\t\t\t>{in_text = 0; fcall comment;}\t\t\t\t->start\t|\n\t\t\t[\\t ]+\t\t>{in_text = 0; indent = 0;} @{indent++;}\t->start\t|\n\t\t\t[\\n]\t\t>{in_text = 0; cur_line++;}\t\t\t\t\t->start\t|\n\t\t\t[\\0]\t\t>{in_text = 0; fbreak;}\t\t\t\t\t\t->start\t|\n\t\t\t[^\\t \\n]\t@{fhold;} %{in_text = 1;}\t\t\t\t\t->text\n\t\t),\n\n\t\t# just discard everything until newline\n\t\tcomment: ( [^\\n]*[\\n] ${cur_line++; fret;} ),\n\n\t\t# a table\n\t\ttable: (\n\t\t\ttablename ']' @saw_table\t\t\t\t\t\t\t\t\t\t->start\t|\n\t\t\t'\"' tablename_in_double_quotes '\"' @saw_table ']'\t\t\t\t->start\t|\n\t\t\t\"'\" tablename_in_single_quotes \"'\" @saw_table ']'\t\t\t\t->start\t|\n\t\t\t'[' tablename ']' ']' @saw_table_array\t\t\t\t\t\t\t->start\t|\n\t\t\t'[' '\"' tablename_in_double_quotes '\"' ']' @saw_table_array ']'\t->start\t|\n\t\t\t'[' \"'\" tablename_in_single_quotes \"'\" ']' @saw_table_array ']'\t->start\n\t\t),\n\n\t\t# the boolean data type\n\t\ttrue:\t( any\t>{fhold;} $saw_bool\t->start ),\n\t\tfalse:\t( any\t>{fhold;} $saw_bool\t->start ),\n\n\t\tbasic_string: (\n\t\t\t[\"]\t\t\t\t-> basic_empty_or_multi_line\t|\n\t\t\t[^\"] ${fhold;}\t-> basic_string_contents\n\t\t),\n\n\t\tbasic_empty_or_multi_line: (\n\t\t\t[\"]\t\t\t\t\t\t\t-> basic_multi_line_start\t|\n\t\t\t[^\"] $saw_string ${fhold;}\t-> start\n\t\t),\n\n\t\tbasic_multi_line_start: (\n\t\t\t'\\n' ${cur_line++;}\t-> basic_multi_line |\n\t\t\t[^\\n] ${fhold;}\t\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line: (\n\t\t\t[\"]\t\t\t\t\t\t\t\t\t\t-> basic_multi_line_quote\t|\n\t\t\t[\\n]\t\t${cur_line++;*strp++=fc;}\t-> basic_multi_line\t\t\t|\n\t\t\t[\\\\]\t\t\t\t\t\t\t\t\t-> basic_multi_line_escape\t|\n\t\t\t[^\"\\n\\\\]\t${*strp++=fc;}\t\t\t\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_escape: (\n\t\t\t[\\n]\t${cur_line++;}\t\t\t-> basic_multi_line_rm_ws\t|\n\t\t\t[^\\n]\t${fcall str_escape;}\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_rm_ws: (\n\t\t\t[\\n]\t${cur_line++;}\t-> basic_multi_line_rm_ws |\n\t\t\t[ \\t]\t\t\t\t\t-> basic_multi_line_rm_ws |\n\t\t\t[^ \\t\\n]\t${fhold;}\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_quote: (\n\t\t\t[\"]\t\t\t\t\t\t\t\t-> basic_multi_line_quote_2\t|\n\t\t\t[^\"]\t${fhold;*strp++='\"';}\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_quote_2: (\n\t\t\t[\"]\t\t$saw_string\t\t\t\t\t\t\t-> start |\n\t\t\t[^\"]\t${fhold;*strp++='\"';*strp++='\"';}\t-> basic_multi_line\n\t\t),\n\n\t\t# String, we have to escape \\0, \\t, \\n, \\r, everything else can\n\t\t# be prefixed with a slash and the slash just gets dropped\n\t\tbasic_string_contents: (\n\t\t\t'\"'\t\t\t$saw_string\t\t\t\t\t-> start\t\t\t\t\t|\n\t\t\t[\\n]\t\t${cur_line++; *strp++=fc;}\t-> basic_string_contents\t|\n\t\t\t[\\\\]\t\t${fcall str_escape;}\t\t-> basic_string_contents\t|\n\t\t\t[^\"\\n\\\\]\t${*strp++=fc;}\t\t\t\t-> basic_string_contents\n\t\t),\n\n\t\tstr_escape: (\n\t\t\t'b'\t${*strp++=0x8;}\t\t\t${fret;}\t|\n\t\t\t't'\t${*strp++='\\t';}\t\t${fret;}\t|\n\t\t\t'n'\t${*strp++='\\n';}\t\t${fret;}\t|\n\t\t\t'f'\t${*strp++=0xc;}\t\t\t${fret;}\t|\n\t\t\t'r'\t${*strp++='\\r';}\t\t${fret;}\t|\n\t\t\t'0'\t${*strp++=0;}\t\t\t${fret;}\t|\n\t\t\t'\"'\t${*strp++='\"';}\t\t\t${fret;}\t|\n\t\t\t'\/'\t${*strp++='\/';}\t\t\t${fret;}\t|\n\t\t\t'\\\\'\t${*strp++='\\\\';}\t${fret;}\t|\n\t\t\t'u'\t\t\t\t\t\t\t-> unicode4\t|\n\t\t\t'U'\t\t\t\t\t\t\t-> unicode8\t|\n\t\t\t[^btnfr0uU\"\/\\\\] $bad_escape\n\t\t),\n\n\t\tunicode4: (\n\t\t\txdigit{4} >{utf_start=p;} @saw_utf16\n\t\t),\n\n\t\tunicode8: (\n\t\t\txdigit{8} >{utf_start=p;} @saw_utf32\n\t\t),\n\n\t\t# When we don't know yet if this is going to be a date or a number\n\t\t# this is the state\n\t\tnumber_or_date: (\n\t\t\t'_' ? digit ${number *= 10; number += fc-'0';}\t->number_or_date\t|\n\t\t\t'-'\t${tm.tm_year = number - 1900;}\t\t\t\t->date\t\t\t\t|\n\t\t\t[eE]\t\t\t\t\t\t\t\t\t\t\t->exponent_part\t\t|\n\t\t\t[.]\t>{precision = 0;}\t\t\t\t\t\t\t->fractional_part\t|\n\t\t\t[\\t ,\\]\\n\\0] $saw_int ${fhold;}\t\t\t\t\t->start\n\t\t),\n\n\t\t# Fractional part of a double\n\t\tfractional_part: (\n\t\t\t[0-9]\t${precision++;}\t\t\t\t->fractional_part\t|\n\t\t\t[eE]\t\t\t\t\t\t\t\t->exponent_part\t\t|\n\t\t\t[^0-9eE]\t$saw_float ${fhold;}\t->start\n\t\t),\n\n\t\texponent_part: (\n\t\t\t[\\-\\+0-9]\t${exponent=true;}\t\t->exponent_part\t|\n\t\t\t[^\\-\\+0-9]\t$saw_float ${fhold;}\t->start\n\t\t),\n\n\t\t# Zulu date, we've already picked up the first four digits and the '-'\n\t\t# when figuring this was a date and not a number\n\t\tdate: ( '' >{secfrac_ptr = NULL; time_offset = 0; time_offset_is_negative = 0; time_offset_is_zulu = 0;}\n\t\t\tdigit{2} @{tm.tm_mon = atoi(fpc-1) - 1;}\n\t\t\t'-'\n\t\t\tdigit{2} @{tm.tm_mday = atoi(fpc-1);}\n\t\t\t'T'\n\t\t\tdigit{2} @{tm.tm_hour = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_min = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_sec = atoi(fpc-1);} -> fractional_second_or_offset\n\t\t),\n\n\t\tfractional_second_or_offset: (\n\t\t\t'.' digit* >{secfrac_ptr=p;} >{fhold;}\t-> time_offset\t|\n\t\t\t[^.] @{fhold;}\t\t\t\t\t\t\t-> time_offset\n\t\t),\n\n\t\ttime_offset: (\n\t\t\t('-' @{time_offset_is_negative=1;}|'+')\n\t\t\t\tdigit{2} @{time_offset = atoi(fpc-1) * 60;}\n\t\t\t\t':'\n\t\t\t\tdigit{2} @{time_offset += atoi(fpc-1);}\n\t\t\t\t@saw_date\t\t\t\t\t\t\t\t-> start |\n\t\t\t'Z' >{time_offset_is_zulu = 1;} @saw_date\t-> start\n\t\t),\n\n\t\tliteral_string: (\n\t\t\t[']\t\t\t\t\t-> literal_empty_or_multi_line\t\t|\n\t\t\t[^']\t${fhold;}\t-> literal_string_contents\n\t\t),\n\n\t\tliteral_string_contents: (\n\t\t\t[']\t\t$saw_string\t\t->start\t\t\t\t\t\t|\n\t\t\t[^']\t${*strp++=fc;}\t->literal_string_contents\n\t\t),\n\n\t\tliteral_empty_or_multi_line: (\n\t\t\t[']\t\t\t\t\t\t\t\t-> literal_multi_line_start\t|\n\t\t\t[^']\t${fhold;} $saw_string\t-> start\n\t\t),\n\n\t\tliteral_multi_line_start: (\n\t\t\t'\\n' ${cur_line++;}\t-> literal_multi_line\t|\n\t\t\t[^\\n] ${fhold;}\t\t-> literal_multi_line\n\t\t),\n\n\t\tliteral_multi_line: (\n\t\t\t[']\t\t\t\t\t\t\t\t\t-> literal_multi_line_quote\t|\n\t\t\t[\\n]\t${cur_line++;*strp++=fc;}\t-> literal_multi_line\t\t|\n\t\t\t[^'\\n]\t${*strp++=fc;}\t\t\t\t-> literal_multi_line\n\t\t),\n\n\t\t# saw 1 quote, if there's not another one go back to literalMultiLine\n\t\tliteral_multi_line_quote: (\n\t\t\t[']\t\t\t\t\t\t\t\t\t-> literal_multi_line_second_quote |\n\t\t\t[^']\t${fhold;*strp++='\\'';}\t\t-> literal_multi_line\n\t\t),\n\n\t\t# saw 2 quotes, if there's not another one go back to literalMultiLine\n\t\t# if there is another then terminate the string\n\t\tliteral_multi_line_second_quote: (\n\t\t\t[']\t\t$saw_string\t\t\t\t\t\t\t-> start\t\t\t\t|\n\t\t\t[^']\t${fhold;*strp++='\\'';*strp++='\\'';}\t-> literal_multi_line\n\t\t),\n\n\t\t# Non-list value\n\t\tsingular: (\n\t\t\t'true'\t\t@{number = 1;}\t\t\t\t\t\t\t\t\t-> true\t\t\t\t|\n\t\t\t'false'\t\t@{number = 0;}\t\t\t\t\t\t\t\t\t-> false\t\t\t|\n\t\t\t'\"'\t\t\t${strp = string;}\t\t\t\t\t\t\t\t-> basic_string\t\t|\n\t\t\t[']\t\t\t${strp = string;}\t\t\t\t\t\t\t\t-> literal_string\t|\n\t\t\t('-'|'+')\t${negative = fc == '-'; number = 0; ts = p;}\t-> number_or_date\t|\n\t\t\tdigit\t\t${negative = false; ts = p; number = fc-'0';}\t-> number_or_date\n\t\t),\n\n\t\t# A list of values\n\t\tlist: (\n\t\t\t'#'\t\t>{fcall comment;}\t->list\t|\n\t\t\t'\\n'\t${cur_line++;}\t\t->list\t|\n\t\t\t[\\t ]\t\t\t\t\t\t->list\t|\n\t\t\t','\t\t\t\t\t\t\t->list\t|\n\t\t\t']'\t$end_list\t\t\t\t->start\t|\n\t\t\t[^#\\t, \\n\\]] ${fhold;}\t\t->val\n\t\t),\n\n\t\tinline_table: (\n\t\t\t','\t\t\t\t\t\t\t\t-> inline_table |\n\t\t\t[\\t ]\t\t\t\t\t\t\t-> inline_table |\n\t\t\t'}'\t@{inline_table = false;}\t-> start\t\t|\n\t\t\t[^\\t ,}] @{fhold;}\t\t\t\t-> key\n\t\t),\n\n\t\t# A val can be either a list or a singular value\n\t\tval: (\n\t\t\t'#'\t>{fcall comment;}\t->val\t\t\t|\n\t\t\t'\\n' ${ cur_line++; }\t->val\t\t\t|\n\t\t\t[\\t ]\t\t\t\t\t->val\t\t\t|\n\t\t\t'['\t$start_list\t\t\t->list\t\t\t|\n\t\t\t']'\t$end_list\t\t\t->start\t\t\t|\n\t\t\t'{'\t$saw_inline_table\t->inline_table\t|\n\t\t\t[^#\\t \\n[\\]{] ${fhold;}\t->singular\n\t\t),\n\n\t\t# A regular key\n\t\tkey: (\n\t\t\tname @{namelen = (int)(p-ts);} whitespace '=' $saw_key\t\t\t\t\t\t\t\t->val\t|\n\t\t\t'\"' name_in_double_quotes '\"' @{namelen = (int)(p-ts-1);} whitespace '=' $saw_key\t->val\t|\n\t\t\t\"'\" name_in_single_quotes \"'\" @{namelen = (int)(p-ts-1);} whitespace '=' $saw_key\t->val\n\t\t),\n\n\t\t# Text stripped of leading whitespace\n\t\ttext: (\n\t\t\t'#'\t>{fcall comment;}\t->text\t|\n\t\t\t'['\t\t\t\t\t\t->table\t|\n\t\t\t[\\t ]\t\t\t\t\t->text\t|\n\t\t\t'\\n' ${cur_line++;}\t\t->start\t|\n\t\t\t[^#[\\t \\n]\t${fhold;}\t->key\n\t\t)\n\t);\n\n\tmain := lines?;\n}%%\n\n%%write data;\n\nint\ntoml_parse(struct toml_node* toml_root, char* buf, int buflen)\n{\n\tint indent = 0, cs, cur_line = 1;\n\tchar *p, *pe;\n\tchar *ts;\n\tchar string[1024], *strp;\n\tint precision;\n\tint namelen;\n\tint64_t number;\n\tbool negative;\n\tstruct tm tm;\n\tdouble floating;\n\tchar *name;\n\tchar *parse_error = NULL;\n\tint malloc_error = 0;\n\tchar* utf_start;\n\tint top = 0, stack[1024];\n\tint in_text = 0;\n\tint time_offset = 0;\n\tchar* secfrac_ptr;\n\tbool time_offset_is_negative = 0;\n\tbool time_offset_is_zulu = 0;\n\tbool inline_table = false;\n\tbool exponent = false;\n\n\tstruct toml_node *cur_table = toml_root;\n\n\tstruct list_head list_stack;\n\tlist_head_init(&list_stack);\n\n\tassert(toml_root->type == TOML_ROOT);\n\n\t%% write init;\n\n\tp = buf;\n\tpe = buf + buflen + 1;\n\n\t%% write exec;\n\n\tif (malloc_error) {\n\t\tfprintf(stderr, \"malloc failed, line %d\\n\", cur_line);\n\t\treturn 1;\n\t}\n\n\tif (parse_error) {\n\t\tfprintf(stderr, \"%s at %d p = %.5s\\n\", parse_error, cur_line, p);\n\t\tfree(parse_error);\n\t\treturn 1;\n\t}\n\n\tif (in_text) {\n\t\tfprintf(stderr, \"not in start, line %d\\n\", cur_line);\n\t\treturn 1;\n\t}\n\n\t\/* check we have consumed the entire buffer *\/\n\tif (p != pe) {\n\t\tfprintf(stderr, \"entire buffer unconsumed, line %d\\n\", cur_line);\n\t\treturn 1;\n\t}\n\n\tif (cs == toml_error) {\n\t\tfprintf(stderr, \"PARSE_ERROR, line %d, p = '%.5s'\", cur_line, p);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n","old_contents":"#include \"toml.h\"\n#include \"toml_private.h\"\n\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct toml_stack_item {\n\tstruct list_node list;\n\tenum toml_type list_type;\n\tstruct toml_node *node;\n};\n\nstatic size_t\nutf32ToUTF8(char* dst, int len, uint32_t utf32)\n{\n\tif (utf32 < 0x80) {\n\t\tif (len < 1)\n\t\t\treturn 0;\n\n\t\t*dst = (uint8_t)utf32;\n\t\treturn 1;\n\t}\n\n\tif (utf32 < 0x000800)\n\t{\n\t\tif (len < 2)\n\t\t\treturn 0;\n\n\t\tdst[0] = (uint8_t)(0xc0 | (utf32 >> 6));\n\t\tdst[1] = (uint8_t)(0x80 | (utf32 & 0x3f));\n\t\treturn 2;\n\t}\n\n\tif (utf32 < 0x10000)\n\t{\n\t\tif (len < 3)\n\t\t\treturn 0;\n\n\t\tdst[0] = (uint8_t)(0xE0 | (utf32 >> 12));\n\t\tdst[1] = (uint8_t)(0x80 | ((utf32 & 0x0FC0) >> 6));\n\t\tdst[2] = (uint8_t)(0x80 | (utf32 & 0x003F));\n\t\treturn 3;\n\t}\n\n\tif (len < 4)\n\t\treturn 0;\n\n\tdst[0] = (uint8_t)(0xF0 | (utf32 >> 18));\n\tdst[1] = (uint8_t)(0x80 | ((utf32 & 0x03F000) >> 12));\n\tdst[2] = (uint8_t)(0x80 | ((utf32 & 0x000FC0) >> 6));\n\tdst[3] = (uint8_t)(0x80 | (utf32 & 0x00003F));\n\n\treturn 4;\n}\n\nbool add_node_to_tree(struct list_head* list_stack, struct toml_node* cur_table, struct toml_node* node, char* name, char** parse_error, int* malloc_error, int cur_line)\n{\n\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(list_stack, struct toml_stack_item, list);\n\n\tif (cur_list) {\n\t\tif (cur_list->list_type && cur_list->list_type != node->type) {\n\t\t\tasprintf(parse_error,\n\t\t\t\t\t\"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\ttoml_type_to_str(node->type), cur_line);\n\t\t\treturn false;\n\t\t}\n\t\tcur_list->list_type = node->type;\n\n\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\tif (!item) {\n\t\t\t*malloc_error = 1;\n\t\t\treturn false;\n\t\t}\n\n\t\tmemcpy(&item->node, node, sizeof(*node));\n\t\titem->node.name = NULL;\n\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\t} else {\n\t\tstruct toml_table_item *item = malloc(sizeof(*item));\n\t\tif (!item) {\n\t\t\t*malloc_error = 1;\n\t\t\treturn false;\n\t\t}\n\t\tmemcpy(&item->node, node, sizeof(*node));\n\t\titem->node.name = name;\n\t\tlist_add_tail(&cur_table->value.map, &item->map);\n\t}\n\n\treturn true;\n}\n\n%%{\n\tmachine toml;\n\n\twhitespace = [\\t ]*;\n\n\tname = (print - ('#'|'='|'\"'|whitespace))+\t\t\t\t\t>{ts = p;};\n\tname_in_double_quotes = (print - '\"')+\t\t\t\t\t\t>{ts = p;};\n\tname_in_single_quotes = (print - \"'\")+\t\t\t\t\t\t>{ts = p;};\n\ttablename = (print - ('#'|']'|'['|'\"'|whitespace))+\t\t>{ts = p;};\n\ttablename_in_double_quotes = (print - '\"')+\t\t\t\t>{ts = p;};\n\ttablename_in_single_quotes = (print - \"'\")+\t\t\t\t>{ts = p;};\n\n\taction saw_key {\n\t\tstruct toml_table_item* item = NULL;\n\t\tlist_for_each(&cur_table->value.map, item, map) {\n\t\t\tif (strncmp(item->node.name, ts, namelen + 1) != 0)\n\t\t\t\tcontinue;\n\n\t\t\tasprintf(&parse_error,\n\t\t\t\t\t\"duplicate key %s line %d\\n\",\n\t\t\t\t\titem->node.name, cur_line);\n\t\t\tfbreak;\n\t\t}\n\n\t\twhile (ts[namelen] == ' ' || ts[namelen] == '\\t')\n\t\t\tnamelen--;\n\n\t\tname = strndup(ts, namelen + 1);\n\t}\n\n\taction saw_bool {\n\t\tstruct toml_node node;\n\n\t\tnode.type = TOML_BOOLEAN;\n\t\tnode.value.integer = number;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_int {\n\t\tchar*\t\t\t\tte = p;\n\t\tstruct toml_node\tnode;\n\n\t\tnode.type = TOML_INT;\n\t\tnode.value.integer = negative ? -number : number;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_float {\n\t\tchar*\t\t\t\tte = p;\n\t\tstruct toml_node\tnode;\n\n\t\tfloating = strtod(ts, &te);\n\n\t\tnode.type = TOML_FLOAT;\n\t\tnode.value.floating.value = floating;\n\t\tnode.value.floating.precision = precision;\n\n\t\tif (!node.value.floating.precision && !exponent) {\n\t\t\tasprintf(&parse_error, \"bad float\\n\");\n\t\t\tfbreak;\n\t\t}\n\n\t\texponent = false;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_string {\n\t\tint\t\t\t\t\tlen = strp - string + 1;\n\t\tstruct toml_node\tnode;\n\n\t\t*strp = 0;\n\n\t\tnode.type = TOML_STRING;\n\t\tnode.value.string = malloc(len);\n\t\tif (!node.value.string) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\t\tmemcpy(node.value.string, string, len);\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_date {\n\t\tchar*\tte = p;\n\t\tstruct\ttoml_node node;\n\n\t\tnode.type = TOML_DATE;\n\t\tnode.value.rfc3339_time.epoch = timegm(&tm);\n\t\tnode.value.rfc3339_time.offset_sign_negative = time_offset_is_negative;\n\t\tnode.value.rfc3339_time.offset = time_offset;\n\t\tnode.value.rfc3339_time.offset_is_zulu = time_offset_is_zulu;\n\t\tif (secfrac_ptr)\n\t\t\tnode.value.rfc3339_time.sec_frac = strtol(secfrac_ptr, &te, 10);\n\t\telse\n\t\t\tnode.value.rfc3339_time.sec_frac = -1;\n\n\t\tif (!add_node_to_tree(&list_stack, cur_table, &node, name, &parse_error, &malloc_error, cur_line))\n\t\t\tfbreak;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\t\tif (cur_list)\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction start_list {\n\t\tstruct toml_node *node;\n\n\t\t\/*\n\t\t * if the list stack is empty add this list to the table\n\t\t * otherwise it should be added the to list on top of the stack\n\t\t *\/\n\t\tif (list_empty(&list_stack)) {\n\t\t\tstruct toml_table_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\t\/* first add it to the table *\/\n\t\t\titem->node.type = TOML_LIST;\n\t\t\tlist_head_init(&item->node.value.list);\n\t\t\tlist_add_tail(&cur_table->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\tnode = &item->node;\n\t\t} else {\n\t\t\tstruct toml_stack_item* tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\t\tif (tail->list_type && tail->list_type != TOML_LIST) {\n\t\t\t\tasprintf(&parse_error,\n\t\t\t\t\t\t\"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(tail->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_BOOLEAN), cur_line);\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\ttail->list_type = TOML_LIST;\n\t\t\titem->node.type = TOML_LIST;\n\t\t\titem->node.name = NULL;\n\t\t\tlist_head_init(&item->node.value.list);\n\n\t\t\tlist_add_tail(&tail->node->value.list, &item->list);\n\t\t\tnode = &item->node;\n\t\t}\n\n\t\t\/* push this list onto the stack *\/\n\t\tstruct toml_stack_item *stack_item = malloc(sizeof(*stack_item));\n\t\tif (!stack_item) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\t\tstack_item->node = node;\n\t\tstack_item->list_type = 0;\n\t\tlist_add_tail(&list_stack, &stack_item->list);\n\t}\n\n\taction end_list {\n\t\tstruct toml_stack_item *tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tlist_del(&tail->list);\n\t\tfree(tail);\n\n\t\tif (!list_empty(&list_stack))\n\t\t\tfnext list;\n\t\telse if (inline_table)\n\t\t\tfnext inline_table;\n\t}\n\n\taction saw_inline_table {\n\t\tchar*\t\t\t\t\ttablename = name;\n\t\tstruct toml_table_item*\titem;\n\t\tstruct toml_node*\t\tplace = cur_table ? cur_table : toml_root;\n\t\tbool\t\t\t\t\tfound = false;\n\n\t\tinline_table = true;\n\n\t\tlist_for_each(&place->value.map, item, map) {\n\t\t\tif (strcmp(item->node.name, tablename) != 0)\n\t\t\t\tcontinue;\n\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (found)\n\t\t{\n\t\t\tasprintf(&parse_error, \"duplicate entry %s\\n\", tablename);\n\t\t\tfbreak;\n\t\t}\n\n\t\titem = malloc(sizeof(*item));\n\t\tif (!item) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\n\t\titem->node.name = strdup(tablename);\n\t\titem->node.type = TOML_TABLE;\n\t\tlist_head_init(&item->node.value.map);\n\t\tlist_add_tail(&place->value.map, &item->map);\n\n\t\tcur_table = &item->node;\n\n\t\tfree(tablename);\n\t}\n\n\taction saw_table {\n\t\tchar *ancestor, *tofree = NULL, *tablename;\n\t\tint item_added = 0;\n\t\tint len = (int)(p-ts);\n\n\t\tstruct toml_node *place = toml_root;\n\n\t\ttofree = tablename = strndup(ts, len);\n\n\t\twhile ((ancestor = strsep(&tablename, \".\"))) {\n\t\t\tstruct toml_table_item *item = NULL;\n\t\t\tint found = 0;\n\n\t\t\tif (strcmp(ancestor, \"\") == 0) {\n\t\t\t\tasprintf(&parse_error, \"empty implicit table\");\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tlist_for_each(&place->value.map, item, map) {\n\t\t\t\tif (strcmp(item->node.name, ancestor) == 0) {\n\t\t\t\t\tplace = &item->node;\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found)\n\t\t\t\tcontinue;\n\n\t\t\t\/* this is the auto-vivification *\/\n\t\t\titem = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\titem->node.name = strdup(ancestor);\n\t\t\titem->node.type = TOML_TABLE;\n\t\t\tlist_head_init(&item->node.value.map);\n\t\t\tlist_add_tail(&place->value.map, &item->map);\n\n\t\t\tplace = &item->node;\n\t\t\titem_added = 1;\n\t\t}\n\n\t\tif (!item_added) {\n\t\t\tasprintf(&parse_error, \"Duplicate item %.*s\", len, ts);\n\t\t\tfbreak;\n\t\t}\n\n\t\tif (place->type != TOML_TABLE) {\n\t\t\tasprintf(&parse_error, \"Attempt to overwrite table %.*s\", len, ts);\n\t\t\tfbreak;\n\t\t}\n\n\t\tfree(tofree);\n\n\t\tcur_table = place;\n\t}\n\n\taction saw_table_array {\n\t\tint\t\tret;\n\t\tchar*\ttableName;\n\n\t\ttableName = strndup(ts, (int)(p-ts-1));\n\t\tret = SawTableArray(toml_root, tableName, &cur_table, &parse_error);\n\t\tfree(tableName);\n\t\tif (ret)\n\t\t\tfbreak;\n\t}\n\n\taction saw_utf16 {\n\t\tUChar\t\tutf16[2] = { 0 };\n\t\tint32_t\t\tlen = sizeof(string) - (strp - string);\n\t\tint32_t\t\toutLen;\n\t\tUErrorCode\terr = U_ZERO_ERROR;\n\t\tchar\t\tutf16_str[5] = { 0 };\n\n\t\tmemcpy(utf16_str, utf_start, 4);\n\t\t*utf16 = strtoul(utf16_str, NULL, 16);\n\n\t\tu_strToUTF8(strp, len, &outLen, utf16, 1, &err);\n\t\tstrp += outLen;\n\t\tfret;\n\t}\n\n\taction saw_utf32 {\n\t\tuint32_t\tutf32;\n\t\tint32_t\t\tlen = sizeof(string) - (strp - string);\n\t\tint32_t\t\toutLen;\n\t\tchar\t\tutf32_str[9] = { 0 };\n\n\t\tmemcpy(utf32_str, utf_start, 8);\n\t\tutf32 = strtoul(utf32_str, NULL, 16);\n\n\t\toutLen = utf32ToUTF8(strp, len, utf32);\n\t\tstrp += outLen;\n\t\tfret;\n\t}\n\n\taction bad_escape {\n\t\tasprintf(&parse_error, \"bad escape \\\\%c\", *p);\n\t\tfbreak;\n\t}\n\n\tlines = (\n\t\tstart: (\n\t\t\t# count the indentation to know where the tables end\n\t\t\t'#'\t\t\t>{in_text = 0; fcall comment;}\t\t\t\t->start\t|\n\t\t\t[\\t ]+\t\t>{in_text = 0; indent = 0;} @{indent++;}\t->start\t|\n\t\t\t[\\n]\t\t>{in_text = 0; cur_line++;}\t\t\t\t\t->start\t|\n\t\t\t[\\0]\t\t>{in_text = 0; fbreak;}\t\t\t\t\t\t->start\t|\n\t\t\t[^\\t \\n]\t@{fhold;} %{in_text = 1;}\t\t\t\t\t->text\n\t\t),\n\n\t\t# just discard everything until newline\n\t\tcomment: ( [^\\n]*[\\n] ${cur_line++; fret;} ),\n\n\t\t# a table\n\t\ttable: (\n\t\t\ttablename ']' @saw_table\t\t\t\t\t\t\t\t\t\t->start\t|\n\t\t\t'\"' tablename_in_double_quotes '\"' @saw_table ']'\t\t\t\t->start\t|\n\t\t\t\"'\" tablename_in_single_quotes \"'\" @saw_table ']'\t\t\t\t->start\t|\n\t\t\t'[' tablename ']' ']' @saw_table_array\t\t\t\t\t\t\t->start\t|\n\t\t\t'[' '\"' tablename_in_double_quotes '\"' ']' @saw_table_array ']'\t->start\t|\n\t\t\t'[' \"'\" tablename_in_single_quotes \"'\" ']' @saw_table_array ']'\t->start\n\t\t),\n\n\t\t# the boolean data type\n\t\ttrue:\t( any\t>{fhold;} $saw_bool\t->start ),\n\t\tfalse:\t( any\t>{fhold;} $saw_bool\t->start ),\n\n\t\tbasic_string: (\n\t\t\t[\"]\t\t\t\t-> basic_empty_or_multi_line\t|\n\t\t\t[^\"] ${fhold;}\t-> basic_string_contents\n\t\t),\n\n\t\tbasic_empty_or_multi_line: (\n\t\t\t[\"]\t\t\t\t\t\t\t-> basic_multi_line_start\t|\n\t\t\t[^\"] $saw_string ${fhold;}\t-> start\n\t\t),\n\n\t\tbasic_multi_line_start: (\n\t\t\t'\\n' ${cur_line++;}\t-> basic_multi_line |\n\t\t\t[^\\n] ${fhold;}\t\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line: (\n\t\t\t[\"]\t\t\t\t\t\t\t\t\t\t-> basic_multi_line_quote\t|\n\t\t\t[\\n]\t\t${cur_line++;*strp++=fc;}\t-> basic_multi_line\t\t\t|\n\t\t\t[\\\\]\t\t\t\t\t\t\t\t\t-> basic_multi_line_escape\t|\n\t\t\t[^\"\\n\\\\]\t${*strp++=fc;}\t\t\t\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_escape: (\n\t\t\t[\\n]\t${cur_line++;}\t\t\t-> basic_multi_line_rm_ws\t|\n\t\t\t[^\\n]\t${fcall str_escape;}\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_rm_ws: (\n\t\t\t[\\n]\t${cur_line++;}\t-> basic_multi_line_rm_ws |\n\t\t\t[ \\t]\t\t\t\t\t-> basic_multi_line_rm_ws |\n\t\t\t[^ \\t\\n]\t${fhold;}\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_quote: (\n\t\t\t[\"]\t\t\t\t\t\t\t\t-> basic_multi_line_quote_2\t|\n\t\t\t[^\"]\t${fhold;*strp++='\"';}\t-> basic_multi_line\n\t\t),\n\n\t\tbasic_multi_line_quote_2: (\n\t\t\t[\"]\t\t$saw_string\t\t\t\t\t\t\t-> start |\n\t\t\t[^\"]\t${fhold;*strp++='\"';*strp++='\"';}\t-> basic_multi_line\n\t\t),\n\n\t\t# String, we have to escape \\0, \\t, \\n, \\r, everything else can\n\t\t# be prefixed with a slash and the slash just gets dropped\n\t\tbasic_string_contents: (\n\t\t\t'\"'\t\t\t$saw_string\t\t\t\t\t-> start\t\t\t\t\t|\n\t\t\t[\\n]\t\t${cur_line++; *strp++=fc;}\t-> basic_string_contents\t|\n\t\t\t[\\\\]\t\t${fcall str_escape;}\t\t-> basic_string_contents\t|\n\t\t\t[^\"\\n\\\\]\t${*strp++=fc;}\t\t\t\t-> basic_string_contents\n\t\t),\n\n\t\tstr_escape: (\n\t\t\t'b'\t${*strp++=0x8;}\t\t\t${fret;}\t|\n\t\t\t't'\t${*strp++='\\t';}\t\t${fret;}\t|\n\t\t\t'n'\t${*strp++='\\n';}\t\t${fret;}\t|\n\t\t\t'f'\t${*strp++=0xc;}\t\t\t${fret;}\t|\n\t\t\t'r'\t${*strp++='\\r';}\t\t${fret;}\t|\n\t\t\t'0'\t${*strp++=0;}\t\t\t${fret;}\t|\n\t\t\t'\"'\t${*strp++='\"';}\t\t\t${fret;}\t|\n\t\t\t'\/'\t${*strp++='\/';}\t\t\t${fret;}\t|\n\t\t\t'\\\\'\t${*strp++='\\\\';}\t${fret;}\t|\n\t\t\t'u'\t\t\t\t\t\t\t-> unicode4\t|\n\t\t\t'U'\t\t\t\t\t\t\t-> unicode8\t|\n\t\t\t[^btnfr0uU\"\/\\\\] $bad_escape\n\t\t),\n\n\t\tunicode4: (\n\t\t\txdigit{4} >{utf_start=p;} @saw_utf16\n\t\t),\n\n\t\tunicode8: (\n\t\t\txdigit{8} >{utf_start=p;} @saw_utf32\n\t\t),\n\n\t\t# When we don't know yet if this is going to be a date or a number\n\t\t# this is the state\n\t\tnumber_or_date: (\n\t\t\t'_' ? digit ${number *= 10; number += fc-'0';}\t->number_or_date\t|\n\t\t\t'-'\t${tm.tm_year = number - 1900;}\t\t\t\t->date\t\t\t\t|\n\t\t\t[eE]\t\t\t\t\t\t\t\t\t\t\t->exponent_part\t\t|\n\t\t\t[.]\t>{precision = 0;}\t\t\t\t\t\t\t->fractional_part\t|\n\t\t\t[\\t ,\\]\\n\\0] $saw_int ${fhold;}\t\t\t\t\t->start\n\t\t),\n\n\t\t# Fractional part of a double\n\t\tfractional_part: (\n\t\t\t[0-9]\t${precision++;}\t\t\t\t->fractional_part\t|\n\t\t\t[eE]\t\t\t\t\t\t\t\t->exponent_part\t\t|\n\t\t\t[^0-9eE]\t$saw_float ${fhold;}\t->start\n\t\t),\n\n\t\texponent_part: (\n\t\t\t[\\-\\+0-9]\t${exponent=true;}\t\t->exponent_part\t|\n\t\t\t[^\\-\\+0-9]\t$saw_float ${fhold;}\t->start\n\t\t),\n\n\t\t# Zulu date, we've already picked up the first four digits and the '-'\n\t\t# when figuring this was a date and not a number\n\t\tdate: ( '' >{secfrac_ptr = NULL; time_offset = 0; time_offset_is_negative = 0; time_offset_is_zulu = 0;}\n\t\t\tdigit{2} @{tm.tm_mon = atoi(fpc-1) - 1;}\n\t\t\t'-'\n\t\t\tdigit{2} @{tm.tm_mday = atoi(fpc-1);}\n\t\t\t'T'\n\t\t\tdigit{2} @{tm.tm_hour = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_min = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_sec = atoi(fpc-1);} -> fractional_second_or_offset\n\t\t),\n\n\t\tfractional_second_or_offset: (\n\t\t\t'.' digit* >{secfrac_ptr=p;} >{fhold;}\t-> time_offset\t|\n\t\t\t[^.] @{fhold;}\t\t\t\t\t\t\t-> time_offset\n\t\t),\n\n\t\ttime_offset: (\n\t\t\t('-' @{time_offset_is_negative=1;}|'+')\n\t\t\t\tdigit{2} @{time_offset = atoi(fpc-1) * 60;}\n\t\t\t\t':'\n\t\t\t\tdigit{2} @{time_offset += atoi(fpc-1);}\n\t\t\t\t@saw_date\t\t\t\t\t\t\t\t-> start |\n\t\t\t'Z' >{time_offset_is_zulu = 1;} @saw_date\t-> start\n\t\t),\n\n\t\tliteral_string: (\n\t\t\t[']\t\t\t\t\t-> literal_empty_or_multi_line\t\t|\n\t\t\t[^']\t${fhold;}\t-> literal_string_contents\n\t\t),\n\n\t\tliteral_string_contents: (\n\t\t\t[']\t\t$saw_string\t\t->start\t\t\t\t\t\t|\n\t\t\t[^']\t${*strp++=fc;}\t->literal_string_contents\n\t\t),\n\n\t\tliteral_empty_or_multi_line: (\n\t\t\t[']\t\t\t\t\t\t\t\t-> literal_multi_line_start\t|\n\t\t\t[^']\t${fhold;} $saw_string\t-> start\n\t\t),\n\n\t\tliteral_multi_line_start: (\n\t\t\t'\\n' ${cur_line++;}\t-> literal_multi_line\t|\n\t\t\t[^\\n] ${fhold;}\t\t-> literal_multi_line\n\t\t),\n\n\t\tliteral_multi_line: (\n\t\t\t[']\t\t\t\t\t\t\t\t\t-> literal_multi_line_quote\t|\n\t\t\t[\\n]\t${cur_line++;*strp++=fc;}\t-> literal_multi_line\t\t|\n\t\t\t[^'\\n]\t${*strp++=fc;}\t\t\t\t-> literal_multi_line\n\t\t),\n\n\t\t# saw 1 quote, if there's not another one go back to literalMultiLine\n\t\tliteral_multi_line_quote: (\n\t\t\t[']\t\t\t\t\t\t\t\t\t-> literal_multi_line_second_quote |\n\t\t\t[^']\t${fhold;*strp++='\\'';}\t\t-> literal_multi_line\n\t\t),\n\n\t\t# saw 2 quotes, if there's not another one go back to literalMultiLine\n\t\t# if there is another then terminate the string\n\t\tliteral_multi_line_second_quote: (\n\t\t\t[']\t\t$saw_string\t\t\t\t\t\t\t-> start\t\t\t\t|\n\t\t\t[^']\t${fhold;*strp++='\\'';*strp++='\\'';}\t-> literal_multi_line\n\t\t),\n\n\t\t# Non-list value\n\t\tsingular: (\n\t\t\t'true'\t\t@{number = 1;}\t\t\t\t\t\t\t\t\t-> true\t\t\t\t|\n\t\t\t'false'\t\t@{number = 0;}\t\t\t\t\t\t\t\t\t-> false\t\t\t|\n\t\t\t'\"'\t\t\t${strp = string;}\t\t\t\t\t\t\t\t-> basic_string\t\t|\n\t\t\t[']\t\t\t${strp = string;}\t\t\t\t\t\t\t\t-> literal_string\t|\n\t\t\t('-'|'+')\t${negative = fc == '-'; number = 0; ts = p;}\t-> number_or_date\t|\n\t\t\tdigit\t\t${negative = false; ts = p; number = fc-'0';}\t-> number_or_date\n\t\t),\n\n\t\t# A list of values\n\t\tlist: (\n\t\t\t'#'\t\t>{fcall comment;}\t->list\t|\n\t\t\t'\\n'\t${cur_line++;}\t\t->list\t|\n\t\t\t[\\t ]\t\t\t\t\t\t->list\t|\n\t\t\t','\t\t\t\t\t\t\t->list\t|\n\t\t\t']'\t$end_list\t\t\t\t->start\t|\n\t\t\t[^#\\t, \\n\\]] ${fhold;}\t\t->val\n\t\t),\n\n\t\tinline_table: (\n\t\t\t','\t\t\t\t\t\t\t\t-> inline_table |\n\t\t\t[\\t ]\t\t\t\t\t\t\t-> inline_table |\n\t\t\t'}'\t@{inline_table = false;}\t-> start\t\t|\n\t\t\t[^\\t ,}] @{fhold;}\t\t\t\t-> key\n\t\t),\n\n\t\t# A val can be either a list or a singular value\n\t\tval: (\n\t\t\t'#'\t>{fcall comment;}\t->val\t\t\t|\n\t\t\t'\\n' ${ cur_line++; }\t->val\t\t\t|\n\t\t\t[\\t ]\t\t\t\t\t->val\t\t\t|\n\t\t\t'['\t$start_list\t\t\t->list\t\t\t|\n\t\t\t']'\t$end_list\t\t\t->start\t\t\t|\n\t\t\t'{'\t$saw_inline_table\t->inline_table\t|\n\t\t\t[^#\\t \\n[\\]{] ${fhold;}\t->singular\n\t\t)\n\n\t\t# A regular key\n\t\tkey: (\n\t\t\tname @{namelen = (int)(p-ts);} whitespace '=' $saw_key\t\t\t\t\t\t\t\t->val\t|\n\t\t\t'\"' name_in_double_quotes '\"' @{namelen = (int)(p-ts-1);} whitespace '=' $saw_key\t->val\t|\n\t\t\t\"'\" name_in_single_quotes \"'\" @{namelen = (int)(p-ts-1);} whitespace '=' $saw_key\t->val\n\t\t),\n\n\t\t# Text stripped of leading whitespace\n\t\ttext: (\n\t\t\t'#'\t>{fcall comment;}\t->text\t|\n\t\t\t'['\t\t\t\t\t\t->table\t|\n\t\t\t[\\t ]\t\t\t\t\t->text\t|\n\t\t\t'\\n' ${cur_line++;}\t\t->start\t|\n\t\t\t[^#[\\t \\n]\t${fhold;}\t->key\n\t\t)\n\t);\n\n\tmain := lines?;\n}%%\n\n%%write data;\n\nint\ntoml_parse(struct toml_node* toml_root, char* buf, int buflen)\n{\n\tint indent = 0, cs, cur_line = 1;\n\tchar *p, *pe;\n\tchar *ts;\n\tchar string[1024], *strp;\n\tint precision;\n\tint namelen;\n\tint64_t number;\n\tbool negative;\n\tstruct tm tm;\n\tdouble floating;\n\tchar *name;\n\tchar *parse_error = NULL;\n\tint malloc_error = 0;\n\tchar* utf_start;\n\tint top = 0, stack[1024];\n\tint in_text = 0;\n\tint time_offset = 0;\n\tchar* secfrac_ptr;\n\tbool time_offset_is_negative = 0;\n\tbool time_offset_is_zulu = 0;\n\tbool inline_table = false;\n\tbool exponent = false;\n\n\tstruct toml_node *cur_table = toml_root;\n\n\tstruct list_head list_stack;\n\tlist_head_init(&list_stack);\n\n\tassert(toml_root->type == TOML_ROOT);\n\n\t%% write init;\n\n\tp = buf;\n\tpe = buf + buflen + 1;\n\n\t%% write exec;\n\n\tif (malloc_error) {\n\t\tfprintf(stderr, \"malloc failed, line %d\\n\", cur_line);\n\t\treturn 1;\n\t}\n\n\tif (parse_error) {\n\t\tfprintf(stderr, \"%s at %d p = %.5s\\n\", parse_error, cur_line, p);\n\t\tfree(parse_error);\n\t\treturn 1;\n\t}\n\n\tif (in_text) {\n\t\tfprintf(stderr, \"not in start, line %d\\n\", cur_line);\n\t\treturn 1;\n\t}\n\n\t\/* check we have consumed the entire buffer *\/\n\tif (p != pe) {\n\t\tfprintf(stderr, \"entire buffer unconsumed, line %d\\n\", cur_line);\n\t\treturn 1;\n\t}\n\n\tif (cs == toml_error) {\n\t\tfprintf(stderr, \"PARSE_ERROR, line %d, p = '%.5s'\", cur_line, p);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"0c34cac050c164604a54613e7a41979022a6a576","subject":"Fix typos introduced in CL9207","message":"Fix typos introduced in CL9207\n\n~$0x1f => $~0x1f\nenum with kNoRestrictedReg is not removed from ValidateChunkAMD64\n\nBUG=http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=2597\nTEST=trybots\nReview URL: https:\/\/chromiumcodereview.appspot.com\/10815055\n\ngit-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@9227 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2\n","repos":"sbc100\/native_client,sbc100\/native_client,nacl-webkit\/native_client,sbc100\/native_client,nacl-webkit\/native_client,nacl-webkit\/native_client,sbc100\/native_client,nacl-webkit\/native_client,sbc100\/native_client,sbc100\/native_client,nacl-webkit\/native_client","old_file":"src\/trusted\/validator_ragel\/unreviewed\/validator_x86_64.rl","new_file":"src\/trusted\/validator_ragel\/unreviewed\/validator_x86_64.rl","new_contents":"\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"native_client\/src\/trusted\/validator_ragel\/unreviewed\/validator_internal.h\"\n\n#include \"native_client\/src\/trusted\/validator_ragel\/gen\/validator_x86_64_instruction_consts.c\"\n\n%%{\n machine x86_64_decoder;\n alphtype unsigned char;\n\n action check_access {\n check_access(begin - data, base, index, restricted_register, valid_targets,\n &errors_detected);\n }\n\n action rel8_operand {\n rel8_operand(p + 1, data, jump_dests, size, &errors_detected);\n }\n action rel16_operand {\n #error rel16_operand should never be used in nacl\n }\n action rel32_operand {\n rel32_operand(p + 1, data, jump_dests, size, &errors_detected);\n }\n\n # Do nothing when IMM operand is detected for now. Will be used later for\n # dynamic code modification support.\n action imm2_operand { }\n action imm8_operand { }\n action imm16_operand { }\n action imm32_operand { }\n action imm64_operand { }\n action imm8_second_operand { }\n action imm16_second_operand { }\n action imm32_second_operand { }\n action imm64_second_operand { }\n\n action process_0_operands {\n process_0_operands(&restricted_register, &errors_detected);\n }\n action process_1_operands {\n process_1_operands(&restricted_register, &errors_detected, rex_prefix,\n operand_states, begin, &sandboxed_rsi_restricted_rdi);\n }\n action process_2_operands {\n process_2_operands(&restricted_register, &errors_detected, rex_prefix,\n operand_states, begin, &sandboxed_rsi_restricted_rdi);\n }\n\n include decode_x86_64 \"validator_x86_64_instruction.rl\";\n\n data16condrep = (data16 | condrep data16 | data16 condrep);\n data16rep = (data16 | rep data16 | data16 rep);\n\n # Special %rbp modifications without required sandboxing\n rbp_modifications =\n (0x48 0x89 0xe5) | # mov %rsp,%rbp\n (0x48 0x81 0xe5 any{3} (0x80 .. 0xff)) | # and $XXX,%rbp\n (0x48 0x83 0xe5 (0x80 .. 0xff)) # and $XXX,%rbp\n @process_0_operands;\n\n # Special instructions used for %rbp sandboxing\n rbp_sandboxing =\n (0x4c 0x01 0xfd | # add %r15,%rbp\n 0x49 0x8d 0x2c 0x2f | # lea (%r15,%rbp,1),%rbp\n 0x4a 0x8d 0x6c 0x3d 0x00) # lea 0x0(%rbp,%r15,1),%rbp\n @{ if (restricted_register != REG_RBP) {\n errors_detected |= RESTRICTED_RBP_UNPROCESSED;\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n };\n\n # Special %rbp modifications without required sandboxing\n rsp_modifications =\n (0x48 0x89 0xec) | # mov %rbp,%rsp\n (0x48 0x81 0xe4 any{3} (0x80 .. 0xff)) | # and $XXX,%rsp\n (0x48 0x83 0xe4 (0x80 .. 0xff)) # and $XXX,%rsp\n @process_0_operands;\n\n # Special instructions used for %rbp sandboxing\n rsp_sandboxing =\n (0x4c 0x01 0xfc | # add %r15,%rsp\n 0x4a 0x8d 0x24 0x3c) # lea (%rsp,%r15,1),%rsp\n @{ if (restricted_register != REG_RSP) {\n errors_detected |= RESTRICTED_RSP_UNPROCESSED;\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n };\n\n # naclcall - old version (is not used by contemporary toolchain)\n # Note: first \"and $~0x1f, %eXX\" is normal instruction and as such will detect\n # case where %rbp\/%rsp is illegally modified.\n old_naclcall_or_nacljmp =\n (((0x83 0xe0 0xe0 0x49 0x8d any 0x07 any{2}) | # and $~0x1f, %eax\n (0x83 0xe1 0xe0 0x49 0x8d any 0x0f any{2}) | # lea (%r15,%rax),%rXX\n (0x83 0xe2 0xe0 0x49 0x8d any 0x17 any{2}) | # ...\n (0x83 0xe3 0xe0 0x49 0x8d any 0x1f any{2}) | # ...\n (0x83 0xe6 0xe0 0x49 0x8d any 0x37 any{2}) | # and $~0x1f, %edi\n (0x83 0xe7 0xe0 0x49 0x8d any 0x3f any{2}) | # lea (%r15,%rdi),%rXX\n (0x41 0x83 0xe0 0xe0 0x49 0x8d any 0x07 any{2}) | # and $~0x1f, %r8d\n (0x41 0x83 0xe1 0xe0 0x49 0x8d any 0x0f any{2}) | # lea (%r15,%rax),%rXX\n (0x41 0x83 0xe2 0xe0 0x49 0x8d any 0x17 any{2}) | #\n (0x41 0x83 0xe3 0xe0 0x49 0x8d any 0x1f any{2}) | # ...\n (0x41 0x83 0xe4 0xe0 0x49 0x8d any 0x27 any{2}) | #\n (0x41 0x83 0xe5 0xe0 0x49 0x8d any 0x2f any{2}) | # and $~0x1f, %r14d\n (0x41 0x83 0xe6 0xe0 0x49 0x8d any 0x37 any{2})) & # lea (%r15,%rdi),%rXX\n ((any{3,4} 0x49 0x8d 0x04 any 0xff (0xd0|0xe0)) | # lea (%r15,%rXX),%rax\n (any{3,4} 0x49 0x8d 0x0c any 0xff (0xd1|0xe1)) | # call\/jmp %rax\n (any{3,4} 0x49 0x8d 0x14 any 0xff (0xd2|0xe2)) | # ...\n (any{3,4} 0x49 0x8d 0x1c any 0xff (0xd3|0xe3)) | # ...\n (any{3,4} 0x49 0x8d 0x34 any 0xff (0xd6|0xe6)) | # lea (%r15,%rXX),%rdi\n (any{3,4} 0x49 0x8d 0x3c any 0xff (0xd7|0xe7)))) # call\/jmp %rdi\n @{\n BitmapClearBit(valid_targets, (p - data) - 6);\n BitmapClearBit(valid_targets, (p - data) - 1);\n restricted_register = kNoRestrictedReg;\n } |\n (((0x83 0xe0 0xe0 0x4d 0x8d any 0x07 any{3}) | # and $~0x1f, %eax\n (0x83 0xe1 0xe0 0x4d 0x8d any 0x0f any{3}) | # lea (%r15,%rax),%rXX\n (0x83 0xe2 0xe0 0x4d 0x8d any 0x17 any{3}) | # ...\n (0x83 0xe3 0xe0 0x4d 0x8d any 0x1f any{3}) | # ...\n (0x83 0xe6 0xe0 0x4d 0x8d any 0x37 any{3}) | # and $~0x1f, %edi\n (0x83 0xe7 0xe0 0x4d 0x8d any 0x3f any{3}) | # lea (%r15,%rdi),%rXX\n (0x41 0x83 0xe0 0xe0 0x4d 0x8d any 0x07 any{3}) | # and $~0x1f, %r8d\n (0x41 0x83 0xe1 0xe0 0x4d 0x8d any 0x0f any{3}) | # lea (%r15,%rax),%rXX\n (0x41 0x83 0xe2 0xe0 0x4d 0x8d any 0x17 any{3}) | #\n (0x41 0x83 0xe3 0xe0 0x4d 0x8d any 0x1f any{3}) | # ...\n (0x41 0x83 0xe4 0xe0 0x4d 0x8d any 0x27 any{3}) | #\n (0x41 0x83 0xe5 0xe0 0x4d 0x8d any 0x2f any{3}) | # and $~0x1f, %r14d\n (0x41 0x83 0xe6 0xe0 0x4d 0x8d any 0x37 any{3})) & # lea (%r15,%rdi),%rXX\n ((any{3,4} 0x4d 0x8d 0x04 any 0x41 0xff (0xd0|0xe0)) | # lea (%r15,%rXX),\n (any{3,4} 0x4d 0x8d 0x0c any 0x41 0xff (0xd1|0xe1)) | # %r8\n (any{3,4} 0x4d 0x8d 0x14 any 0x41 0xff (0xd2|0xe2)) | # call\/jmp %r8\n (any{3,4} 0x4d 0x8d 0x1c any 0x41 0xff (0xd3|0xe3)) | # ...\n (any{3,4} 0x4d 0x8d 0x24 any 0x41 0xff (0xd4|0xe4)) | # lea (%r15,%rXX),\n (any{3,4} 0x4d 0x8d 0x2c any 0x41 0xff (0xd5|0xe5)) | # %r14\n (any{3,4} 0x4d 0x8d 0x34 any 0x41 0xff (0xd6|0xe6)))) # call\/jmp %r14\n @{\n BitmapClearBit(valid_targets, (p - data) - 7);\n BitmapClearBit(valid_targets, (p - data) - 2);\n restricted_register = kNoRestrictedReg;\n };\n\n # naclcall or nacljmp - this the form used by contemporary toolchain\n # Note: first \"and $~0x1f, %eXX\" is normal instruction and as such will detect\n # case where %rbp\/%rsp is illegally modified.\n naclcall_or_nacljmp =\n (0x83 0xe0 0xe0 0x4c 0x01 0xf8 0xff (0xd0|0xe0) | # naclcall\/jmp %eax, %r15\n 0x83 0xe1 0xe0 0x4c 0x01 0xf9 0xff (0xd1|0xe1) | # naclcall\/jmp %ecx, %r15\n 0x83 0xe2 0xe0 0x4c 0x01 0xfa 0xff (0xd2|0xe2) | # naclcall\/jmp %edx, %r15\n 0x83 0xe3 0xe0 0x4c 0x01 0xfb 0xff (0xd3|0xe3) | # naclcall\/jmp %ebx, %r15\n 0x83 0xe6 0xe0 0x4c 0x01 0xfe 0xff (0xd6|0xe6) | # naclcall\/jmp %esi, %r15\n 0x83 0xe7 0xe0 0x4c 0x01 0xff 0xff (0xd7|0xe7)) # naclcall\/jmp %edi, %r15\n @{\n BitmapClearBit(valid_targets, (p - data) - 4);\n BitmapClearBit(valid_targets, (p - data) - 1);\n restricted_register = kNoRestrictedReg;\n } |\n (0x41 0x83 0xe0 0xe0 0x4d 0x01 0xf8 0x41 0xff (0xd0|0xe0) | # naclcall\/jmp\n 0x41 0x83 0xe1 0xe0 0x4d 0x01 0xf9 0x41 0xff (0xd1|0xe1) | # %r8d, %r15\n 0x41 0x83 0xe2 0xe0 0x4d 0x01 0xfa 0x41 0xff (0xd2|0xe2) | #\n 0x41 0x83 0xe3 0xe0 0x4d 0x01 0xfb 0x41 0xff (0xd3|0xe3) | # ...\n 0x41 0x83 0xe4 0xe0 0x4d 0x01 0xfc 0x41 0xff (0xd4|0xe4) | #\n 0x41 0x83 0xe5 0xe0 0x4d 0x01 0xfd 0x41 0xff (0xd5|0xe5) | # naclcall\/jmp\n 0x41 0x83 0xe6 0xe0 0x4d 0x01 0xfe 0x41 0xff (0xd6|0xe6)) # %r14d, %r15\n @{\n BitmapClearBit(valid_targets, (p - data) - 5);\n BitmapClearBit(valid_targets, (p - data) - 2);\n restricted_register = kNoRestrictedReg;\n };\n\n # Special %rsi sandboxing for string instructions\n rsi_sandboxing =\n (0x49 0x8d 0x34 0x37) # lea (%r15,%rsi,1),%rsi\n @{ if (restricted_register == REG_RSI) {\n sandboxed_rsi = begin;\n restricted_register = kSandboxedRsi;\n } else {\n restricted_register = kNoRestrictedReg;\n }\n };\n\n # Special %rdi sandboxing for string instructions\n rdi_sandboxing =\n (0x49 0x8d 0x3c 0x3f) # lea (%r15,%rdi,1),%rdi\n @{ if (restricted_register == REG_RDI) {\n sandboxed_rdi = begin;\n restricted_register = kSandboxedRdi;\n } else if (restricted_register == kSandboxedRsiRestrictedRdi) {\n sandboxed_rdi = begin;\n restricted_register = kSandboxedRsiSandboxedRdi;\n } else {\n restricted_register = kNoRestrictedReg;\n }\n };\n\n # String instructions which use only %ds:(%rsi)\n string_instructions_rsi_no_rdi =\n (rep? 0xac | # lods %ds:(%rsi),%al\n data16rep 0xad | # lods %ds:(%rsi),%ax\n rep? REXW_NONE? 0xad) # lods %ds:(%rsi),%eax\/%rax\n @{ if (restricted_register != kSandboxedRsi) {\n errors_detected |= RSI_UNSANDBOXDED;\n } else {\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n }\n restricted_register = kNoRestrictedReg;\n };\n\n # String instructions which use only %ds:(%rdi)\n string_instructions_rdi_no_rsi =\n (condrep? 0xae | # scas %es:(%rdi),%al\n data16condrep 0xaf | # scas %es:(%rdi),%ax\n condrep? REXW_NONE? 0xaf | # scas %es:(%rdi),%eax\/%rax\n\n rep? 0xaa | # stos %al,%es:(%rdi)\n data16rep 0xab | # stos %ax,%es:(%rdi)\n rep? REXW_NONE? 0xab) # stos %eax\/%rax,%es:(%rdi)\n @{ if (restricted_register != kSandboxedRdi &&\n restricted_register != kSandboxedRsiSandboxedRdi) {\n errors_detected |= RDI_UNSANDBOXDED;\n } else {\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n }\n restricted_register = kNoRestrictedReg;\n };\n\n # String instructions which use both %ds:(%rsi) and %ds:(%rdi)\n string_instructions_rsi_rdi =\n (condrep? 0xa6 | # cmpsb %es:(%rdi),%ds:(%rsi)\n data16condrep 0xa7 | # cmpsw %es:(%rdi),%ds:(%rsi)\n condrep? REXW_NONE? 0xa7 | # cmps[lq] %es:(%rdi),%ds:(%rsi)\n\n rep? 0xa4 | # movsb %es:(%rdi),%ds:(%rsi)\n data16rep 0xa5 | # movsw %es:(%rdi),%ds:(%rsi)\n rep? REXW_NONE? 0xa5) # movs[lq] %es:(%rdi),%ds:(%rsi)\n @{ if (restricted_register != kSandboxedRsiSandboxedRdi) {\n errors_detected |= RDI_UNSANDBOXDED;\n if (restricted_register != kSandboxedRsi) {\n errors_detected |= RSI_UNSANDBOXDED;\n }\n } else {\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi_restricted_rdi - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n }\n restricted_register = kNoRestrictedReg;\n };\n\n special_instruction =\n rbp_modifications |\n rsp_modifications |\n rbp_sandboxing |\n rsp_sandboxing |\n old_naclcall_or_nacljmp |\n naclcall_or_nacljmp |\n rsi_sandboxing |\n rdi_sandboxing |\n string_instructions_rsi_no_rdi |\n string_instructions_rdi_no_rsi |\n string_instructions_rsi_rdi;\n\n # Remove special instructions which are only allowed in special cases.\n normal_instruction = one_instruction - special_instruction;\n\n main := ((normal_instruction | special_instruction) >{\n begin = p;\n errors_detected = 0;\n BitmapSetBit(valid_targets, p - data);\n SET_REX_PREFIX(FALSE);\n SET_VEX_PREFIX2(0xe0);\n SET_VEX_PREFIX3(0x00);\n operand_states = 0;\n }\n @{\n if (errors_detected) {\n process_error(begin, errors_detected, userdata);\n result = 1;\n }\n \/* On successful match the instruction start must point to the next byte\n * to be able to report the new offset as the start of instruction\n * causing error. *\/\n begin = p + 1;\n })*\n $err{\n process_error(begin, UNRECOGNIZED_INSTRUCTION, userdata);\n result = 1;\n goto error_detected;\n };\n\n}%%\n\n%% write data;\n\nint ValidateChunkAMD64(const uint8_t *data, size_t size,\n const NaClCPUFeaturesX86 *cpu_features,\n process_validation_error_func process_error,\n void *userdata) {\n uint8_t *valid_targets = BitmapAllocate(size);\n uint8_t *jump_dests = BitmapAllocate(size);\n\n const uint8_t *p = data;\n const uint8_t *begin = p; \/* Start of the instruction being processed. *\/\n\n uint8_t rex_prefix = FALSE;\n uint8_t vex_prefix2 = 0xe0;\n uint8_t vex_prefix3 = 0x00;\n \/* Keeps one byte of information per operand in the current instruction:\n * 2 bits for register kinds,\n * 5 bits for register numbers (16 regs plus RIZ). *\/\n uint32_t operand_states = 0;\n enum register_name base = NO_REG;\n enum register_name index = NO_REG;\n int result = 0;\n \/* These are borders of the appropriate instructions. Initialize them to make\n * compiler happy: they are never used uninitialized even without explicit\n * initialization but GCC is not sophysicated enough to prove that. *\/\n const uint8_t *sandboxed_rsi = 0;\n const uint8_t *sandboxed_rsi_restricted_rdi = 0;\n const uint8_t *sandboxed_rdi = 0;\n\n size_t i;\n\n uint32_t errors_detected = 0;\n\n assert(size % kBundleSize == 0);\n\n while (p < data + size) {\n const uint8_t *pe = p + kBundleSize;\n const uint8_t *eof = pe;\n int cs;\n uint8_t restricted_register = kNoRestrictedReg;\n\n %% write init;\n %% write exec;\n\n if (restricted_register == REG_RBP) {\n process_error(begin, RESTRICTED_RBP_UNPROCESSED, userdata);\n result = 1;\n } else if (restricted_register == REG_RSP) {\n process_error(begin, RESTRICTED_RSP_UNPROCESSED, userdata);\n result = 1;\n }\n }\n\n for (i = 0; i < size \/ 32; i++) {\n uint32_t jump_dest_mask = ((uint32_t *) jump_dests)[i];\n uint32_t valid_target_mask = ((uint32_t *) valid_targets)[i];\n if ((jump_dest_mask & ~valid_target_mask) != 0) {\n process_error(data + i * 32, BAD_JUMP_TARGET, userdata);\n result = 1;\n break;\n }\n }\n\nerror_detected:\n return result;\n}\n","old_contents":"\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"native_client\/src\/trusted\/validator_ragel\/unreviewed\/validator_internal.h\"\n\n#include \"native_client\/src\/trusted\/validator_ragel\/gen\/validator_x86_64_instruction_consts.c\"\n\n%%{\n machine x86_64_decoder;\n alphtype unsigned char;\n\n action check_access {\n check_access(begin - data, base, index, restricted_register, valid_targets,\n &errors_detected);\n }\n\n action rel8_operand {\n rel8_operand(p + 1, data, jump_dests, size, &errors_detected);\n }\n action rel16_operand {\n #error rel16_operand should never be used in nacl\n }\n action rel32_operand {\n rel32_operand(p + 1, data, jump_dests, size, &errors_detected);\n }\n\n # Do nothing when IMM operand is detected for now. Will be used later for\n # dynamic code modification support.\n action imm2_operand { }\n action imm8_operand { }\n action imm16_operand { }\n action imm32_operand { }\n action imm64_operand { }\n action imm8_second_operand { }\n action imm16_second_operand { }\n action imm32_second_operand { }\n action imm64_second_operand { }\n\n action process_0_operands {\n process_0_operands(&restricted_register, &errors_detected);\n }\n action process_1_operands {\n process_1_operands(&restricted_register, &errors_detected, rex_prefix,\n operand_states, begin, &sandboxed_rsi_restricted_rdi);\n }\n action process_2_operands {\n process_2_operands(&restricted_register, &errors_detected, rex_prefix,\n operand_states, begin, &sandboxed_rsi_restricted_rdi);\n }\n\n include decode_x86_64 \"validator_x86_64_instruction.rl\";\n\n data16condrep = (data16 | condrep data16 | data16 condrep);\n data16rep = (data16 | rep data16 | data16 rep);\n\n # Special %rbp modifications without required sandboxing\n rbp_modifications =\n (0x48 0x89 0xe5) | # mov %rsp,%rbp\n (0x48 0x81 0xe5 any{3} (0x80 .. 0xff)) | # and $XXX,%rbp\n (0x48 0x83 0xe5 (0x80 .. 0xff)) # and $XXX,%rbp\n @process_0_operands;\n\n # Special instructions used for %rbp sandboxing\n rbp_sandboxing =\n (0x4c 0x01 0xfd | # add %r15,%rbp\n 0x49 0x8d 0x2c 0x2f | # lea (%r15,%rbp,1),%rbp\n 0x4a 0x8d 0x6c 0x3d 0x00) # lea 0x0(%rbp,%r15,1),%rbp\n @{ if (restricted_register != REG_RBP) {\n errors_detected |= RESTRICTED_RBP_UNPROCESSED;\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n };\n\n # Special %rbp modifications without required sandboxing\n rsp_modifications =\n (0x48 0x89 0xec) | # mov %rbp,%rsp\n (0x48 0x81 0xe4 any{3} (0x80 .. 0xff)) | # and $XXX,%rsp\n (0x48 0x83 0xe4 (0x80 .. 0xff)) # and $XXX,%rsp\n @process_0_operands;\n\n # Special instructions used for %rbp sandboxing\n rsp_sandboxing =\n (0x4c 0x01 0xfc | # add %r15,%rsp\n 0x4a 0x8d 0x24 0x3c) # lea (%rsp,%r15,1),%rsp\n @{ if (restricted_register != REG_RSP) {\n errors_detected |= RESTRICTED_RSP_UNPROCESSED;\n }\n restricted_register = kNoRestrictedReg;\n BitmapClearBit(valid_targets, (begin - data));\n };\n\n # naclcall - old version (is not used by contemporary toolchain)\n # Note: first \"and ~$0x1f, %eXX\" is normal instruction and as such will detect\n # case where %rbp\/%rsp is illegally modified.\n old_naclcall_or_nacljmp =\n (((0x83 0xe0 0xe0 0x49 0x8d any 0x07 any{2}) | # and ~$0x1f, %eax\n (0x83 0xe0 0xe1 0x49 0x8d any 0x0f any{2}) | # lea (%r15,%rax),%rXX\n (0x83 0xe0 0xe2 0x49 0x8d any 0x17 any{2}) | # ...\n (0x83 0xe0 0xe3 0x49 0x8d any 0x1f any{2}) | # ...\n (0x83 0xe0 0xe6 0x49 0x8d any 0x37 any{2}) | # and ~$0x1f, %edi\n (0x83 0xe0 0xe7 0x49 0x8d any 0x3f any{2}) | # lea (%r15,%rdi),%rXX\n (0x41 0x83 0xe0 0xe0 0x49 0x8d any 0x07 any{2}) | # and ~$0x1f, %r8d\n (0x41 0x83 0xe0 0xe1 0x49 0x8d any 0x0f any{2}) | # lea (%r15,%rax),%rXX\n (0x41 0x83 0xe0 0xe2 0x49 0x8d any 0x17 any{2}) | #\n (0x41 0x83 0xe0 0xe3 0x49 0x8d any 0x1f any{2}) | # ...\n (0x41 0x83 0xe0 0xe4 0x49 0x8d any 0x27 any{2}) | #\n (0x41 0x83 0xe0 0xe5 0x49 0x8d any 0x2f any{2}) | # and ~$0x1f, %r14d\n (0x41 0x83 0xe0 0xe6 0x49 0x8d any 0x37 any{2})) & # lea (%r15,%rdi),%rXX\n ((any{3,4} 0x49 0x8d 0x04 any 0xff (0xd0|0xe0)) | # lea (%r15,%rXX),%rax\n (any{3,4} 0x49 0x8d 0x0c any 0xff (0xd1|0xe1)) | # call\/jmp %rax\n (any{3,4} 0x49 0x8d 0x14 any 0xff (0xd2|0xe2)) | # ...\n (any{3,4} 0x49 0x8d 0x1c any 0xff (0xd3|0xe3)) | # ...\n (any{3,4} 0x49 0x8d 0x34 any 0xff (0xd6|0xe6)) | # lea (%r15,%rXX),%rdi\n (any{3,4} 0x49 0x8d 0x3c any 0xff (0xd7|0xe7)))) # call\/jmp %rdi\n @{\n BitmapClearBit(valid_targets, (p - data) - 6);\n BitmapClearBit(valid_targets, (p - data) - 1);\n restricted_register = kNoRestrictedReg;\n } |\n (((0x83 0xe0 0xe0 0x4d 0x8d any 0x07 any{3}) | # and ~$0x1f, %eax\n (0x83 0xe0 0xe1 0x4d 0x8d any 0x0f any{3}) | # lea (%r15,%rax),%rXX\n (0x83 0xe0 0xe2 0x4d 0x8d any 0x17 any{3}) | # ...\n (0x83 0xe0 0xe3 0x4d 0x8d any 0x1f any{3}) | # ...\n (0x83 0xe0 0xe6 0x4d 0x8d any 0x37 any{3}) | # and ~$0x1f, %edi\n (0x83 0xe0 0xe7 0x4d 0x8d any 0x3f any{3}) | # lea (%r15,%rdi),%rXX\n (0x41 0x83 0xe0 0xe0 0x4d 0x8d any 0x07 any{3}) | # and ~$0x1f, %r8d\n (0x41 0x83 0xe0 0xe1 0x4d 0x8d any 0x0f any{3}) | # lea (%r15,%rax),%rXX\n (0x41 0x83 0xe0 0xe2 0x4d 0x8d any 0x17 any{3}) | #\n (0x41 0x83 0xe0 0xe3 0x4d 0x8d any 0x1f any{3}) | # ...\n (0x41 0x83 0xe0 0xe4 0x4d 0x8d any 0x27 any{3}) | #\n (0x41 0x83 0xe0 0xe5 0x4d 0x8d any 0x2f any{3}) | # and ~$0x1f, %r14d\n (0x41 0x83 0xe0 0xe6 0x4d 0x8d any 0x37 any{3})) & # lea (%r15,%rdi),%rXX\n ((any{3,4} 0x4d 0x8d 0x04 any 0x41 0xff (0xd0|0xe0)) | # lea (%r15,%rXX),\n (any{3,4} 0x4d 0x8d 0x0c any 0x41 0xff (0xd1|0xe1)) | # %r8\n (any{3,4} 0x4d 0x8d 0x14 any 0x41 0xff (0xd2|0xe2)) | # call\/jmp %r8\n (any{3,4} 0x4d 0x8d 0x1c any 0x41 0xff (0xd3|0xe3)) | # ...\n (any{3,4} 0x4d 0x8d 0x24 any 0x41 0xff (0xd4|0xe4)) | # lea (%r15,%rXX),\n (any{3,4} 0x4d 0x8d 0x2c any 0x41 0xff (0xd5|0xe5)) | # %r14\n (any{3,4} 0x4d 0x8d 0x34 any 0x41 0xff (0xd6|0xe6)))) # call\/jmp %r14\n @{\n BitmapClearBit(valid_targets, (p - data) - 7);\n BitmapClearBit(valid_targets, (p - data) - 2);\n restricted_register = kNoRestrictedReg;\n };\n\n # naclcall or nacljmp - this the form used by contemporary toolchain\n # Note: first \"and ~$0x1f, %eXX\" is normal instruction and as such will detect\n # case where %rbp\/%rsp is illegally modified.\n naclcall_or_nacljmp =\n (0x83 0xe0 0xe0 0x4c 0x01 0xf8 0xff (0xd0|0xe0) | # naclcall\/jmp %eax, %r15\n 0x83 0xe1 0xe0 0x4c 0x01 0xf9 0xff (0xd1|0xe1) | # naclcall\/jmp %ecx, %r15\n 0x83 0xe2 0xe0 0x4c 0x01 0xfa 0xff (0xd2|0xe2) | # naclcall\/jmp %edx, %r15\n 0x83 0xe3 0xe0 0x4c 0x01 0xfb 0xff (0xd3|0xe3) | # naclcall\/jmp %ebx, %r15\n 0x83 0xe6 0xe0 0x4c 0x01 0xfe 0xff (0xd6|0xe6) | # naclcall\/jmp %esi, %r15\n 0x83 0xe7 0xe0 0x4c 0x01 0xff 0xff (0xd7|0xe7)) # naclcall\/jmp %edi, %r15\n @{\n BitmapClearBit(valid_targets, (p - data) - 4);\n BitmapClearBit(valid_targets, (p - data) - 1);\n restricted_register = kNoRestrictedReg;\n } |\n (0x41 0x83 0xe0 0xe0 0x4d 0x01 0xf8 0x41 0xff (0xd0|0xe0) | # naclcall\/jmp\n 0x41 0x83 0xe1 0xe0 0x4d 0x01 0xf9 0x41 0xff (0xd1|0xe1) | # %r8d, %r15\n 0x41 0x83 0xe2 0xe0 0x4d 0x01 0xfa 0x41 0xff (0xd2|0xe2) | #\n 0x41 0x83 0xe3 0xe0 0x4d 0x01 0xfb 0x41 0xff (0xd3|0xe3) | # ...\n 0x41 0x83 0xe4 0xe0 0x4d 0x01 0xfc 0x41 0xff (0xd4|0xe4) | #\n 0x41 0x83 0xe5 0xe0 0x4d 0x01 0xfd 0x41 0xff (0xd5|0xe5) | # naclcall\/jmp\n 0x41 0x83 0xe6 0xe0 0x4d 0x01 0xfe 0x41 0xff (0xd6|0xe6)) # %r14d, %r15\n @{\n BitmapClearBit(valid_targets, (p - data) - 5);\n BitmapClearBit(valid_targets, (p - data) - 2);\n restricted_register = kNoRestrictedReg;\n };\n\n # Special %rsi sandboxing for string instructions\n rsi_sandboxing =\n (0x49 0x8d 0x34 0x37) # lea (%r15,%rsi,1),%rsi\n @{ if (restricted_register == REG_RSI) {\n sandboxed_rsi = begin;\n restricted_register = kSandboxedRsi;\n } else {\n restricted_register = kNoRestrictedReg;\n }\n };\n\n # Special %rdi sandboxing for string instructions\n rdi_sandboxing =\n (0x49 0x8d 0x3c 0x3f) # lea (%r15,%rdi,1),%rdi\n @{ if (restricted_register == REG_RDI) {\n sandboxed_rdi = begin;\n restricted_register = kSandboxedRdi;\n } else if (restricted_register == kSandboxedRsiRestrictedRdi) {\n sandboxed_rdi = begin;\n restricted_register = kSandboxedRsiSandboxedRdi;\n } else {\n restricted_register = kNoRestrictedReg;\n }\n };\n\n # String instructions which use only %ds:(%rsi)\n string_instructions_rsi_no_rdi =\n (rep? 0xac | # lods %ds:(%rsi),%al\n data16rep 0xad | # lods %ds:(%rsi),%ax\n rep? REXW_NONE? 0xad) # lods %ds:(%rsi),%eax\/%rax\n @{ if (restricted_register != kSandboxedRsi) {\n errors_detected |= RSI_UNSANDBOXDED;\n } else {\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n }\n restricted_register = kNoRestrictedReg;\n };\n\n # String instructions which use only %ds:(%rdi)\n string_instructions_rdi_no_rsi =\n (condrep? 0xae | # scas %es:(%rdi),%al\n data16condrep 0xaf | # scas %es:(%rdi),%ax\n condrep? REXW_NONE? 0xaf | # scas %es:(%rdi),%eax\/%rax\n\n rep? 0xaa | # stos %al,%es:(%rdi)\n data16rep 0xab | # stos %ax,%es:(%rdi)\n rep? REXW_NONE? 0xab) # stos %eax\/%rax,%es:(%rdi)\n @{ if (restricted_register != kSandboxedRdi &&\n restricted_register != kSandboxedRsiSandboxedRdi) {\n errors_detected |= RDI_UNSANDBOXDED;\n } else {\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n }\n restricted_register = kNoRestrictedReg;\n };\n\n # String instructions which use both %ds:(%rsi) and %ds:(%rdi)\n string_instructions_rsi_rdi =\n (condrep? 0xa6 | # cmpsb %es:(%rdi),%ds:(%rsi)\n data16condrep 0xa7 | # cmpsw %es:(%rdi),%ds:(%rsi)\n condrep? REXW_NONE? 0xa7 | # cmps[lq] %es:(%rdi),%ds:(%rsi)\n\n rep? 0xa4 | # movsb %es:(%rdi),%ds:(%rsi)\n data16rep 0xa5 | # movsw %es:(%rdi),%ds:(%rsi)\n rep? REXW_NONE? 0xa5) # movs[lq] %es:(%rdi),%ds:(%rsi)\n @{ if (restricted_register != kSandboxedRsiSandboxedRdi) {\n errors_detected |= RDI_UNSANDBOXDED;\n if (restricted_register != kSandboxedRsi) {\n errors_detected |= RSI_UNSANDBOXDED;\n }\n } else {\n BitmapClearBit(valid_targets, (begin - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi - data));\n BitmapClearBit(valid_targets, (sandboxed_rsi_restricted_rdi - data));\n BitmapClearBit(valid_targets, (sandboxed_rdi - data));\n }\n restricted_register = kNoRestrictedReg;\n };\n\n special_instruction =\n rbp_modifications |\n rsp_modifications |\n rbp_sandboxing |\n rsp_sandboxing |\n old_naclcall_or_nacljmp |\n naclcall_or_nacljmp |\n rsi_sandboxing |\n rdi_sandboxing |\n string_instructions_rsi_no_rdi |\n string_instructions_rdi_no_rsi |\n string_instructions_rsi_rdi;\n\n # Remove special instructions which are only allowed in special cases.\n normal_instruction = one_instruction - special_instruction;\n\n main := ((normal_instruction | special_instruction) >{\n begin = p;\n errors_detected = 0;\n BitmapSetBit(valid_targets, p - data);\n SET_REX_PREFIX(FALSE);\n SET_VEX_PREFIX2(0xe0);\n SET_VEX_PREFIX3(0x00);\n operand_states = 0;\n }\n @{\n if (errors_detected) {\n process_error(begin, errors_detected, userdata);\n result = 1;\n }\n \/* On successful match the instruction start must point to the next byte\n * to be able to report the new offset as the start of instruction\n * causing error. *\/\n begin = p + 1;\n })*\n $err{\n process_error(begin, UNRECOGNIZED_INSTRUCTION, userdata);\n result = 1;\n goto error_detected;\n };\n\n}%%\n\n%% write data;\n\nint ValidateChunkAMD64(const uint8_t *data, size_t size,\n const NaClCPUFeaturesX86 *cpu_features,\n process_validation_error_func process_error,\n void *userdata) {\n uint8_t *valid_targets = BitmapAllocate(size);\n uint8_t *jump_dests = BitmapAllocate(size);\n\n const uint8_t *p = data;\n const uint8_t *begin = p; \/* Start of the instruction being processed. *\/\n\n uint8_t rex_prefix = FALSE;\n uint8_t vex_prefix2 = 0xe0;\n uint8_t vex_prefix3 = 0x00;\n \/* Keeps one byte of information per operand in the current instruction:\n * 2 bits for register kinds,\n * 5 bits for register numbers (16 regs plus RIZ). *\/\n uint32_t operand_states = 0;\n enum register_name base = NO_REG;\n enum register_name index = NO_REG;\n int result = 0;\n \/* These are borders of the appropriate instructions. Initialize them to make\n * compiler happy: they are never used uninitialized even without explicit\n * initialization but GCC is not sophysicated enough to prove that. *\/\n const uint8_t *sandboxed_rsi = 0;\n const uint8_t *sandboxed_rsi_restricted_rdi = 0;\n const uint8_t *sandboxed_rdi = 0;\n\n size_t i;\n\n uint32_t errors_detected = 0;\n\n assert(size % kBundleSize == 0);\n\n while (p < data + size) {\n const uint8_t *pe = p + kBundleSize;\n const uint8_t *eof = pe;\n int cs;\n enum {\n kNoRestrictedReg = 32,\n kSandboxedRsi,\n kSandboxedRdi,\n kSandboxedRsiRestrictedRdi,\n kSandboxedRsiSandboxedRdi\n }; uint8_t restricted_register = kNoRestrictedReg;\n\n %% write init;\n %% write exec;\n\n if (restricted_register == REG_RBP) {\n process_error(begin, RESTRICTED_RBP_UNPROCESSED, userdata);\n result = 1;\n } else if (restricted_register == REG_RSP) {\n process_error(begin, RESTRICTED_RSP_UNPROCESSED, userdata);\n result = 1;\n }\n }\n\n for (i = 0; i < size \/ 32; i++) {\n uint32_t jump_dest_mask = ((uint32_t *) jump_dests)[i];\n uint32_t valid_target_mask = ((uint32_t *) valid_targets)[i];\n if ((jump_dest_mask & ~valid_target_mask) != 0) {\n process_error(data + i * 32, BAD_JUMP_TARGET, userdata);\n result = 1;\n break;\n }\n }\n\nerror_detected:\n return result;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"c7f65c2c6a3628e6054f7117165be4a8e710d246","subject":"There is no need to keep the parser#mark around with an appended buffer","message":"There is no need to keep the parser#mark around with an appended buffer","repos":"elabs\/stomp_parser,elabs\/stompede,elabs\/stompede,elabs\/stomp_parser","old_file":"lib\/stompede\/stomp\/parser.rb.rl","new_file":"lib\/stompede\/stomp\/parser.rb.rl","new_contents":"%%{\n machine message;\n\n # data, p, pe, eof, cs, top, stack, ts, te and act\n getkey data.getbyte(p); # code for retrieving current char\n\n ## Action state - needs resetting once consumed!\n action mark {\n buffer = \"\".force_encoding(\"BINARY\")\n }\n action buffer {\n buffer << fc\n raise BufferLimitExceeded if buffer.bytesize > buffer_size\n }\n action mark_key {\n mk = buffer # needs reset\n buffer = nil\n }\n action mark_message { message = Stomp::Message.new(nil, nil) }\n\n ## Action commands - should reset used state!\n action write_command {\n message.write_command(buffer)\n buffer = nil\n }\n\n action write_header {\n message.write_header(mk, buffer)\n mk = buffer = nil\n }\n\n action write_body {\n message.write_body(buffer)\n buffer = nil\n }\n\n action finish_headers {\n }\n\n action finish_message {\n yield message\n message = nil\n }\n\n ## Stomp message grammar\n\n NULL = \"\\0\";\n EOL = \"\\r\"? . \"\\n\";\n OCTET = any;\n\n client_command = \"CONNECT\" > mark;\n command = client_command $ buffer % write_command . EOL;\n\n HEADER_ESCAPE = \"\\\\\" . (\"\\\\\" | \"n\" | \"r\" | \"c\");\n HEADER_OCTET = HEADER_ESCAPE | (OCTET - \"\\r\" - \"\\n\" - \"\\\\\" - \":\");\n header_key = HEADER_OCTET+ > mark $ buffer % mark_key;\n header_value = HEADER_OCTET* > mark $ buffer;\n header = header_key . \":\" . header_value;\n headers = (header % write_header . EOL)* % finish_headers . EOL;\n\n dynamic_body = (OCTET* > mark) $ buffer % write_body :> NULL;\n\n message = (command > mark_message) :> headers :> (dynamic_body @ finish_message);\n\n stream := (EOL | message)*;\n}%%\n\nmodule Stompede\n module Stomp\n # Provides an API for running parsers.\n #\n # It:\n # - provides a .parse method which remembers state between invocations\n # - buffering of data between chunks\n class Parser\n # this manipulates the singleton class of our context,\n # so we do not want to run this code very often or we\n # bust our ruby method caching\n %% write data noprefix;\n\n # Parse a chunk of Stomp-formatted data into a Message.\n #\n # @param [String] data\n # @param [Parser] state\n # @return [Stomp::Message, nil]\n def self.parse(data, state)\n pe = data.bytesize # end of chunk\n eof = :ignored # end of input\n\n p = 0 # pointer to current character\n message = state.message # message currently being parsed, if any\n cs = state.current_state # current state\n mk = state.mark_key # key for header currently being read\n buffer = state.buffer # buffered data for marks\n buffer_size = state.buffer_size\n\n %% write exec;\n\n if cs == Stomp::Parser.error\n # build error message context\n ctx = 7\n min = [0, p - ctx].max\n cur = p - min\n err = data.byteslice(min, ctx + 1 + ctx)\n chr = err[cur]\n err[cur] = \" -->#{err[cur]}<-- \"\n\n raise ParseError.new(\"unexpected #{chr.inspect} in data (#{err.inspect})\")\n else\n state.message = message\n state.current_state = cs\n state.mark_key = mk\n state.buffer = buffer\n end\n\n nil\n end\n\n # Construct the parser.\n #\n # The buffer_size parameter determines how big the largest\n # chunk of data may become. This includes commands, header\n # keys, header values, and the body. If this size is reached,\n # the parser will throw a #{BufferLimitExceeded} error.\n #\n # The message_size parameter determines how big the largest\n # message may become. This includes all of the content in the\n # message being parsed. If this size is reached for an individual\n # message, the parser will throw a #{MessageSizeExceeded} error.\n #\n # @param [Integer] buffer_size (10K) maximum buffer size\n # @param [Integer] message_size (buffer_size) maximum message size\n def initialize(buffer_size = 1024 * 1024, message_size = buffer_size)\n @buffer_size = buffer_size\n @message_size = message_size\n @error = nil\n @buffer = nil\n\n @current_state = Stomp::Parser.start\n @message = nil\n @mark_key = nil\n end\n\n # @return [Integer] maximum buffer size for parsed values\n attr_reader :buffer_size\n\n # @return [Integer] maximum message size for parsed messages\n attr_reader :message_size\n\n # @return [StandardError] error raised during parsing\n attr_accessor :error\n\n # @return [String] binary string of current parsing buffer\n attr_accessor :buffer\n\n # @return [Integer] current parsing state\n attr_accessor :current_state\n\n # @return [Stomp::Message] stomp message currently being parsed\n attr_accessor :message\n\n # @return [String] header key currently being parsed\n attr_accessor :mark_key\n\n # Parse a chunk of data. Retains state beteween invocations.\n #\n # @param [String] data\n # @raise [ParseError]\n def parse(data)\n raise error if error\n\n begin\n Parser.parse(data, self) do |message|\n yield message\n end\n rescue => error\n self.error = error\n raise\n end\n end\n end\n end\nend\n","old_contents":"%%{\n machine message;\n\n # data, p, pe, eof, cs, top, stack, ts, te and act\n getkey data.getbyte(p); # code for retrieving current char\n\n ## Action state - needs resetting once consumed!\n action mark {\n m = p\n buffer = \"\".force_encoding(\"BINARY\")\n }\n action buffer {\n buffer << fc\n raise BufferLimitExceeded if buffer.bytesize > buffer_size\n }\n action mark_key {\n mk = buffer # needs reset\n m = buffer = nil\n }\n action mark_message { message = Stomp::Message.new(nil, nil) }\n\n ## Action commands - should reset used state!\n action write_command {\n message.write_command(buffer)\n m = buffer = nil\n }\n\n action write_header {\n message.write_header(mk, buffer)\n m = mk = buffer = nil\n }\n\n action write_body {\n message.write_body(buffer)\n m = buffer = nil\n }\n\n action finish_headers {\n }\n\n action finish_message {\n yield message\n message = nil\n }\n\n ## Stomp message grammar\n\n NULL = \"\\0\";\n EOL = \"\\r\"? . \"\\n\";\n OCTET = any;\n\n client_command = \"CONNECT\" > mark;\n command = client_command $ buffer % write_command . EOL;\n\n HEADER_ESCAPE = \"\\\\\" . (\"\\\\\" | \"n\" | \"r\" | \"c\");\n HEADER_OCTET = HEADER_ESCAPE | (OCTET - \"\\r\" - \"\\n\" - \"\\\\\" - \":\");\n header_key = HEADER_OCTET+ > mark $ buffer % mark_key;\n header_value = HEADER_OCTET* > mark $ buffer;\n header = header_key . \":\" . header_value;\n headers = (header % write_header . EOL)* % finish_headers . EOL;\n\n dynamic_body = (OCTET* > mark) $ buffer % write_body :> NULL;\n\n message = (command > mark_message) :> headers :> (dynamic_body @ finish_message);\n\n stream := (EOL | message)*;\n}%%\n\nmodule Stompede\n module Stomp\n # Provides an API for running parsers.\n #\n # It:\n # - provides a .parse method which remembers state between invocations\n # - buffering of data between chunks\n class Parser\n # this manipulates the singleton class of our context,\n # so we do not want to run this code very often or we\n # bust our ruby method caching\n %% write data noprefix;\n\n # Parse a chunk of Stomp-formatted data into a Message.\n #\n # @param [String] data\n # @param [Parser] state\n # @return [Stomp::Message, nil]\n def self.parse(data, state)\n pe = data.bytesize # end of chunk\n eof = :ignored # end of input\n\n p = 0 # pointer to current character\n message = state.message # message currently being parsed, if any\n cs = state.current_state # current state\n m = state.mark # pointer to marked character (for data buffering)\n mk = state.mark_key # key for header currently being read\n buffer = state.buffer # buffered data for marks\n buffer_size = state.buffer_size\n\n %% write exec;\n\n if cs == Stomp::Parser.error\n # build error message context\n ctx = 7\n min = [0, p - ctx].max\n cur = p - min\n err = data.byteslice(min, ctx + 1 + ctx)\n chr = err[cur]\n err[cur] = \" -->#{err[cur]}<-- \"\n\n raise ParseError.new(\"unexpected #{chr.inspect} in data (#{err.inspect})\")\n else\n state.message = message\n state.current_state = cs\n state.mark = m\n state.mark_key = mk\n state.buffer = buffer\n end\n\n nil\n end\n\n # Construct the parser.\n #\n # The buffer_size parameter determines how big the largest\n # chunk of data may become. This includes commands, header\n # keys, header values, and the body. If this size is reached,\n # the parser will throw a #{BufferLimitExceeded} error.\n #\n # The message_size parameter determines how big the largest\n # message may become. This includes all of the content in the\n # message being parsed. If this size is reached for an individual\n # message, the parser will throw a #{MessageSizeExceeded} error.\n #\n # @param [Integer] buffer_size (10K) maximum buffer size\n # @param [Integer] message_size (buffer_size) maximum message size\n def initialize(buffer_size = 1024 * 1024, message_size = buffer_size)\n @buffer_size = buffer_size\n @message_size = message_size\n @error = nil\n @buffer = nil\n\n @current_state = Stomp::Parser.start\n @message = nil\n @mark = nil\n @mark_key = nil\n end\n\n # @return [Integer] maximum buffer size for parsed values\n attr_reader :buffer_size\n\n # @return [Integer] maximum message size for parsed messages\n attr_reader :message_size\n\n # @return [StandardError] error raised during parsing\n attr_accessor :error\n\n # @return [String] binary string of current parsing buffer\n attr_accessor :buffer\n\n # @return [Integer] current parsing state\n attr_accessor :current_state\n\n # @return [Stomp::Message] stomp message currently being parsed\n attr_accessor :message\n\n # @return [Integer] pointer to beginning of current buffer\n attr_accessor :mark\n\n # @return [String] header key currently being parsed\n attr_accessor :mark_key\n\n # Parse a chunk of data. Retains state beteween invocations.\n #\n # @param [String] data\n # @raise [ParseError]\n def parse(data)\n raise error if error\n\n begin\n Parser.parse(data, self) do |message|\n yield message\n end\n rescue => error\n self.error = error\n raise\n end\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"4282198435c320e7a23685514b6a50699e7d47b4","subject":"Remove scary todo warning; there is nothing being allocated in parser","message":"Remove scary todo warning; there is nothing being allocated in parser","repos":"elabs\/stomp_parser,elabs\/stomp_parser","old_file":"ext\/stomp_parser\/c_parser.c.rl","new_file":"ext\/stomp_parser\/c_parser.c.rl","new_contents":"#include \n\n#if DEBUG_H\n# define DEBUG(fmt, ...) do { fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__); } while(0)\n#else\n# define DEBUG(...)\n#endif\n\n#define UNUSED(x) (void)(x)\n#define MARK_LEN (p - mark)\n#define MARK_STR_NEW() rb_str_new(mark, MARK_LEN)\n\n#define true 1\n#define false 0\n\ntypedef struct {\n VALUE error;\n long max_frame_size;\n\n VALUE chunk;\n const char *p;\n int cs;\n const char *mark;\n VALUE mark_key;\n VALUE mark_frame;\n long mark_frame_size;\n long mark_content_length;\n} parser_state_t;\n\nVALUE mStompParser = Qnil;\nVALUE cFrame = Qnil;\nVALUE eFrameSizeExceeded = Qnil;\nID g_new;\nID g_write_command;\nID g_write_header;\nID g_write_body;\nID g_content_length;\nID g_build_parse_error;\nID g_max_frame_size;\n\n%%{\n machine frame;\n\n action mark {\n mark = p;\n }\n\n action mark_frame {\n mark_frame = rb_funcallv(cFrame, g_new, 0, NULL);\n mark_frame_size = 0;\n }\n\n action write_command {\n VALUE command = MARK_STR_NEW();\n rb_funcallv(mark_frame, g_write_command, 1, &command);\n mark = NULL;\n }\n\n action mark_key {\n mark_key = MARK_STR_NEW();\n mark = NULL;\n }\n\n action write_header {\n VALUE args[2] = { mark_key, MARK_STR_NEW() };\n rb_funcallv(mark_frame, g_write_header, 2, args);\n mark_key = Qnil;\n mark = NULL;\n }\n\n action finish_headers {\n VALUE length = rb_funcallv(mark_frame, g_content_length, 0, NULL);\n if ( ! NIL_P(length)) {\n mark_content_length = NUM2LONG(length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n VALUE body = MARK_STR_NEW();\n rb_funcallv(mark_frame, g_write_body, 1, &body);\n mark = NULL;\n }\n\n action consume_null {\n ((mark_content_length != -1) && (MARK_LEN < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || (MARK_LEN < mark_content_length))\n }\n\n action check_frame_size {\n mark_frame_size += 1;\n if (mark_frame_size > max_frame_size) {\n rb_raise(eFrameSizeExceeded, \"\");\n }\n }\n\n action finish_frame {\n rb_yield(mark_frame);\n mark_frame = Qnil;\n }\n\n include frame_common \"parser_common.rl\";\n\n write data noprefix;\n}%%\n\nstatic void parser_free(parser_state_t *state) {\n xfree(state);\n}\n\nstatic void parser_mark(parser_state_t *state) {\n rb_gc_mark(state->error);\n rb_gc_mark(state->mark_key);\n rb_gc_mark(state->mark_frame);\n rb_gc_mark(state->chunk);\n}\n\nstatic VALUE parser_alloc(VALUE klass) {\n parser_state_t *state = ALLOC(parser_state_t);\n return Data_Wrap_Struct(klass, parser_mark, parser_free, state);\n}\n\nstatic VALUE parser_initialize(int argc, VALUE *argv, VALUE self) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n VALUE max_frame_size;\n rb_scan_args(argc, argv, \"01\", &max_frame_size);\n\n if (max_frame_size == Qnil) {\n max_frame_size = rb_funcall(mStompParser, g_max_frame_size, 0);\n }\n\n state->error = Qnil;\n state->max_frame_size = FIX2LONG(max_frame_size);\n state->chunk = Qnil;\n state->cs = start;\n state->mark = NULL;\n state->mark_key = Qnil;\n state->mark_frame = Qnil;\n state->mark_frame_size = 0;\n state->mark_content_length = 0;\n\n return self;\n}\n\nstatic VALUE parser_parse(VALUE self, VALUE new_chunk) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n if (NIL_P(state->error)) {\n VALUE chunk = Qnil;\n const char *p = NULL;\n const char *mark = NULL;\n\n if ( ! NIL_P(state->chunk)) {\n long offset = RSTRING_LEN(state->chunk);\n long mark_offset = state->mark - RSTRING_PTR(state->chunk);\n\n chunk = rb_str_append(state->chunk, new_chunk);\n p = RSTRING_PTR(chunk) + offset;\n mark = RSTRING_PTR(chunk) + mark_offset;\n } else {\n chunk = new_chunk;\n p = RSTRING_PTR(chunk);\n }\n\n const char *pe = RSTRING_END(chunk);\n long max_frame_size = state->max_frame_size;\n\n int cs = state->cs;\n VALUE mark_key = state->mark_key;\n VALUE mark_frame = state->mark_frame;\n long mark_frame_size = state->mark_frame_size;\n long mark_content_length = state->mark_content_length;\n\n %% write exec;\n\n if (mark != NULL) {\n state->chunk = chunk;\n } else {\n state->chunk = Qnil;\n }\n\n state->cs = cs;\n state->mark = mark;\n state->mark_key = mark_key;\n state->mark_frame = mark_frame;\n state->mark_frame_size = mark_frame_size;\n state->mark_content_length = mark_content_length;\n\n if (cs == error) {\n long index = p - RSTRING_PTR(chunk);\n state->error = rb_funcall(mStompParser, g_build_parse_error, 2, chunk, LONG2NUM(index));\n }\n }\n\n if ( ! NIL_P(state->error)) {\n rb_exc_raise(state->error);\n }\n\n return Qnil;\n}\n\nvoid Init_c_parser(void) {\n mStompParser = rb_const_get(rb_cObject, rb_intern(\"StompParser\"));\n cFrame = rb_const_get(mStompParser, rb_intern(\"Frame\"));\n eFrameSizeExceeded = rb_const_get(mStompParser, rb_intern(\"FrameSizeExceeded\"));\n\n g_new = rb_intern(\"new\");\n g_write_command = rb_intern(\"write_command\");\n g_write_header = rb_intern(\"write_header\");\n g_write_body = rb_intern(\"write_body\");\n g_content_length = rb_intern(\"content_length\");\n g_build_parse_error = rb_intern(\"build_parse_error\");\n g_max_frame_size = rb_intern(\"max_frame_size\");\n\n VALUE cParser = rb_define_class_under(mStompParser, \"CParser\", rb_cObject);\n rb_define_alloc_func(cParser, parser_alloc);\n\n rb_define_method(cParser, \"initialize\", parser_initialize, -1);\n rb_define_method(cParser, \"parse\", parser_parse, 1);\n}\n","old_contents":"#include \n\n#if DEBUG_H\n# define DEBUG(fmt, ...) do { fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__); } while(0)\n#else\n# define DEBUG(...)\n#endif\n\n#define UNUSED(x) (void)(x)\n#define MARK_LEN (p - mark)\n#define MARK_STR_NEW() rb_str_new(mark, MARK_LEN)\n\n#define true 1\n#define false 0\n\ntypedef struct {\n VALUE error;\n long max_frame_size;\n\n VALUE chunk;\n const char *p;\n int cs;\n const char *mark;\n VALUE mark_key;\n VALUE mark_frame;\n long mark_frame_size;\n long mark_content_length;\n} parser_state_t;\n\nVALUE mStompParser = Qnil;\nVALUE cFrame = Qnil;\nVALUE eFrameSizeExceeded = Qnil;\nID g_new;\nID g_write_command;\nID g_write_header;\nID g_write_body;\nID g_content_length;\nID g_build_parse_error;\nID g_max_frame_size;\n\n%%{\n machine frame;\n\n action mark {\n mark = p;\n }\n\n action mark_frame {\n mark_frame = rb_funcallv(cFrame, g_new, 0, NULL);\n mark_frame_size = 0;\n }\n\n action write_command {\n VALUE command = MARK_STR_NEW();\n rb_funcallv(mark_frame, g_write_command, 1, &command);\n mark = NULL;\n }\n\n action mark_key {\n mark_key = MARK_STR_NEW();\n mark = NULL;\n }\n\n action write_header {\n VALUE args[2] = { mark_key, MARK_STR_NEW() };\n rb_funcallv(mark_frame, g_write_header, 2, args);\n mark_key = Qnil;\n mark = NULL;\n }\n\n action finish_headers {\n VALUE length = rb_funcallv(mark_frame, g_content_length, 0, NULL);\n if ( ! NIL_P(length)) {\n mark_content_length = NUM2LONG(length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n VALUE body = MARK_STR_NEW();\n rb_funcallv(mark_frame, g_write_body, 1, &body);\n mark = NULL;\n }\n\n action consume_null {\n ((mark_content_length != -1) && (MARK_LEN < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || (MARK_LEN < mark_content_length))\n }\n\n action check_frame_size {\n mark_frame_size += 1;\n if (mark_frame_size > max_frame_size) {\n rb_raise(eFrameSizeExceeded, \"\");\n }\n }\n\n action finish_frame {\n rb_yield(mark_frame);\n mark_frame = Qnil;\n }\n\n include frame_common \"parser_common.rl\";\n\n write data noprefix;\n}%%\n\nstatic void parser_free(parser_state_t *state) {\n \/\/ TODO: free memory inside struct!\n xfree(state);\n}\n\nstatic void parser_mark(parser_state_t *state) {\n rb_gc_mark(state->error);\n rb_gc_mark(state->mark_key);\n rb_gc_mark(state->mark_frame);\n rb_gc_mark(state->chunk);\n}\n\nstatic VALUE parser_alloc(VALUE klass) {\n parser_state_t *state = ALLOC(parser_state_t);\n return Data_Wrap_Struct(klass, parser_mark, parser_free, state);\n}\n\nstatic VALUE parser_initialize(int argc, VALUE *argv, VALUE self) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n VALUE max_frame_size;\n rb_scan_args(argc, argv, \"01\", &max_frame_size);\n\n if (max_frame_size == Qnil) {\n max_frame_size = rb_funcall(mStompParser, g_max_frame_size, 0);\n }\n\n state->error = Qnil;\n state->max_frame_size = FIX2LONG(max_frame_size);\n state->chunk = Qnil;\n state->cs = start;\n state->mark = NULL;\n state->mark_key = Qnil;\n state->mark_frame = Qnil;\n state->mark_frame_size = 0;\n state->mark_content_length = 0;\n\n return self;\n}\n\nstatic VALUE parser_parse(VALUE self, VALUE new_chunk) {\n parser_state_t *state;\n Data_Get_Struct(self, parser_state_t, state);\n\n if (NIL_P(state->error)) {\n VALUE chunk = Qnil;\n const char *p = NULL;\n const char *mark = NULL;\n\n if ( ! NIL_P(state->chunk)) {\n long offset = RSTRING_LEN(state->chunk);\n long mark_offset = state->mark - RSTRING_PTR(state->chunk);\n\n chunk = rb_str_append(state->chunk, new_chunk);\n p = RSTRING_PTR(chunk) + offset;\n mark = RSTRING_PTR(chunk) + mark_offset;\n } else {\n chunk = new_chunk;\n p = RSTRING_PTR(chunk);\n }\n\n const char *pe = RSTRING_END(chunk);\n long max_frame_size = state->max_frame_size;\n\n int cs = state->cs;\n VALUE mark_key = state->mark_key;\n VALUE mark_frame = state->mark_frame;\n long mark_frame_size = state->mark_frame_size;\n long mark_content_length = state->mark_content_length;\n\n %% write exec;\n\n if (mark != NULL) {\n state->chunk = chunk;\n } else {\n state->chunk = Qnil;\n }\n\n state->cs = cs;\n state->mark = mark;\n state->mark_key = mark_key;\n state->mark_frame = mark_frame;\n state->mark_frame_size = mark_frame_size;\n state->mark_content_length = mark_content_length;\n\n if (cs == error) {\n long index = p - RSTRING_PTR(chunk);\n state->error = rb_funcall(mStompParser, g_build_parse_error, 2, chunk, LONG2NUM(index));\n }\n }\n\n if ( ! NIL_P(state->error)) {\n rb_exc_raise(state->error);\n }\n\n return Qnil;\n}\n\nvoid Init_c_parser(void) {\n mStompParser = rb_const_get(rb_cObject, rb_intern(\"StompParser\"));\n cFrame = rb_const_get(mStompParser, rb_intern(\"Frame\"));\n eFrameSizeExceeded = rb_const_get(mStompParser, rb_intern(\"FrameSizeExceeded\"));\n\n g_new = rb_intern(\"new\");\n g_write_command = rb_intern(\"write_command\");\n g_write_header = rb_intern(\"write_header\");\n g_write_body = rb_intern(\"write_body\");\n g_content_length = rb_intern(\"content_length\");\n g_build_parse_error = rb_intern(\"build_parse_error\");\n g_max_frame_size = rb_intern(\"max_frame_size\");\n\n VALUE cParser = rb_define_class_under(mStompParser, \"CParser\", rb_cObject);\n rb_define_alloc_func(cParser, parser_alloc);\n\n rb_define_method(cParser, \"initialize\", parser_initialize, -1);\n rb_define_method(cParser, \"parse\", parser_parse, 1);\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"2c0ded256690a4c7faf909d3ee594e6107721c1f","subject":"whoops, re-enable IP literals in URIs","message":"whoops, re-enable IP literals in URIs\n","repos":"ccutrer\/mordor,ccutrer\/mordor,ccutrer\/mordor","old_file":"mordor\/uri.rl","new_file":"mordor\/uri.rl","new_contents":"\/\/ Copyright (c) 2009 - Mozy, Inc.\n\/* To compile to .cpp:\n ragel uri.rl -G2 -o uri.cpp\n*\/\n\n#include \"mordor\/pch.h\"\n\n#include \"mordor\/uri.h\"\n\n#include \n\n#include \"mordor\/ragel.h\"\n#include \"mordor\/string.h\"\n#include \"mordor\/version.h\"\n\nnamespace Mordor {\n\nstatic const std::string unreserved(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\");\nstatic const std::string sub_delims(\"!$&'()*+,;=\");\nstatic const std::string scheme(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.\");\nstatic const std::string userinfo(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string host(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string pchar(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\");\nstatic const std::string path(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/\");\nstatic const std::string segment_nc(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \"@\");\nstatic const std::string query(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/?\");\nstatic const std::string queryString(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$'()*,\" \":@\" \"\/?\");\n\nstatic std::string escape(const std::string& str, const std::string& allowedChars, bool spaceAsPlus = false)\n{\n const char *hexdigits = \"0123456789ABCDEF\";\n std::string result(str);\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while(c < end)\n {\n if (allowedChars.find(*c) == std::string::npos) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n if (*c == ' ' && spaceAsPlus) {\n result.append(1, '+');\n } else {\n result.append(1, '%');\n result.append(1, hexdigits[(unsigned char)*c >> 4]);\n result.append(1, hexdigits[*c & 0xf]);\n }\n } else {\n if (differed) {\n result.append(1, *c);\n }\n }\n ++c;\n }\n\n if (differed) {\n MORDOR_ASSERT(result.length() >= str.length());\n } else {\n MORDOR_ASSERT(result == str);\n }\n return result;\n}\n\nstd::string unescape(const std::string& str, bool spaceAsPlus = false)\n{\n std::string result = str;\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while (c < end)\n {\n if (*c == '%') {\n MORDOR_ASSERT(c + 2 < end);\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n char decoded;\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded = (*c - 'a' + 10) << 4;\n else if (*c >= 'A' && *c <= 'F')\n decoded = (*c - 'A' + 10) << 4;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded = (*c - '0') << 4;\n }\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded |= *c - 'a' + 10;\n else if (*c >= 'A' && *c <= 'F')\n decoded |= *c - 'A' + 10;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded |= *c - '0';\n }\n result.append(1, decoded);\n } else if (*c == '+' && spaceAsPlus) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n result.append(1, ' ');\n } else if (differed) {\n result.append(1, *c);\n }\n ++c;\n }\n return result;\n}\n\nstd::string\nURI::encode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return escape(str, unreserved, false);\n case QUERYSTRING:\n return escape(str, Mordor::queryString, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\nstd::string\nURI::decode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return unescape(str, false);\n case QUERYSTRING:\n return unescape(str, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\n%%{\n # See RFC 3986: http:\/\/www.ietf.org\/rfc\/rfc3986.txt\n\n machine uri_parser;\n\n gen_delims = \":\" | \"\/\" | \"?\" | \"#\" | \"[\" | \"]\" | \"@\";\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\" | \"=\";\n reserved = gen_delims | sub_delims;\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n\n action marku { mark = fpc; }\n action markh { mark = fpc; }\n action save_scheme\n {\n m_uri->scheme(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n scheme = (alpha (alpha | digit | \"+\" | \"-\" | \".\")*) >marku %save_scheme;\n\n action save_port\n {\n if (fpc == mark)\n m_authority->port(-1);\n else\n m_authority->port(atoi(mark));\n mark = NULL;\n }\n action save_userinfo\n {\n m_authority->userinfo(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n action save_host\n {\n if (mark != NULL) {\n m_authority->host(unescape(std::string(mark, fpc - mark)));\n \/\/ This could have been part of the userinfo, so don't clear the mark\n \/\/ mark = NULL;\n }\n }\n\n userinfo = (unreserved | pct_encoded | sub_delims | \":\")*;\n dec_octet = digit | [1-9] digit | \"1\" digit{2} | 2 [0-4] digit | \"25\" [0-5];\n IPv4address = dec_octet \".\" dec_octet \".\" dec_octet \".\" dec_octet;\n h16 = xdigit{1,4};\n ls32 = (h16 \":\" h16) | IPv4address;\n IPv6address = ( (h16 \":\"){6} ls32) |\n ( \"::\" (h16 \":\"){5} ls32) |\n (( h16)? \"::\" (h16 \":\"){4} ls32) |\n (((h16 \":\"){1} h16)? \"::\" (h16 \":\"){3} ls32) |\n (((h16 \":\"){2} h16)? \"::\" (h16 \":\"){2} ls32) |\n (((h16 \":\"){3} h16)? \"::\" (h16 \":\"){1} ls32) |\n (((h16 \":\"){4} h16)? \"::\" ls32) |\n (((h16 \":\"){5} h16)? \"::\" h16 ) |\n (((h16 \":\"){6} h16)? \"::\" );\n IPvFuture = \"v\" xdigit+ \".\" (unreserved | sub_delims | \":\")+;\n IP_literal = \"[\" (IPv6address | IPvFuture) \"]\";\n reg_name = (unreserved | pct_encoded | sub_delims)*;\n host = IP_literal | IPv4address | reg_name;\n port = digit*;\n\n authority = ( (userinfo %save_userinfo \"@\")? host >markh %save_host (\":\" port >markh %save_port)? ) >markh;\n\n action save_segment\n {\n m_segments->push_back(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n segment = pchar* >marku %save_segment;\n segment_nz = pchar+ >marku %save_segment;\n segment_nz_nc = (pchar - \":\")+ >marku %save_segment;\n\n action clear_segments\n {\n m_segments->clear();\n }\n\n path_abempty = ((\"\/\" >marku >save_segment segment) %marku %save_segment)? (\"\/\" segment)*;\n path_absolute = (\"\/\" >marku >save_segment (segment_nz (\"\/\" segment)*)?) %marku %save_segment;\n path_noscheme = segment_nz_nc (\"\/\" segment)*;\n path_rootless = segment_nz (\"\/\" segment)*;\n path_empty = \"\";\n path = (path_abempty | path_absolute | path_noscheme | path_rootless | path_empty);\n\n action save_query\n {\n m_uri->m_query = std::string(mark, fpc - mark);\n m_uri->m_queryDefined = true;\n mark = NULL;\n }\n action save_fragment\n {\n m_uri->fragment(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n query = (pchar | \"\/\" | \"?\")* >marku %save_query;\n fragment = (pchar | \"\/\" | \"?\")* >marku %save_fragment;\n\n hier_part = (\"\/\/\" %clear_segments authority path_abempty) | path_absolute | path_rootless | path_empty;\n\n relative_part = (\"\/\/\" %clear_segments authority path_abempty) | path_absolute | path_noscheme | path_empty;\n relative_ref = relative_part ( \"?\" query )? ( \"#\" fragment )?;\n\n absolute_URI = scheme \":\" hier_part ( \"?\" query )? ;\n # Obsolete, but referenced from HTTP, so we translate\n relative_URI = relative_part ( \"?\" query )?;\n\n URI = scheme \":\" hier_part ( \"?\" query )? ( \"#\" fragment )?;\n URI_reference = URI | relative_ref;\n}%%\n\n%%{\n machine uri_parser_proper;\n include uri_parser;\n main := URI_reference;\n write data;\n}%%\n\nclass URIParser : public RagelParser\n{\npublic:\n URIParser(URI& uri)\n {\n m_uri = &uri;\n m_segments = &m_uri->path.segments;\n m_authority = &m_uri->authority;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_parser_proper_first_final;\n }\n\n bool error() const\n {\n return cs == uri_parser_proper_error;\n }\n\nprivate:\n URI *m_uri;\n std::vector *m_segments;\n URI::Authority *m_authority;\n};\n\n%%{\n machine uri_path_parser;\n include uri_parser;\n main := path;\n write data;\n}%%\nclass URIPathParser : public RagelParser\n{\npublic:\n URIPathParser(std::vector &segments)\n {\n m_segments = &segments;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_path_parser_first_final;\n }\n\n bool error() const\n {\n return cs == uri_path_parser_error;\n }\n\nprivate:\n std::vector *m_segments;\n};\n\n%%{\n machine uri_authority_parser;\n include uri_parser;\n main := authority;\n write data;\n}%%\nclass URIAuthorityParser : public RagelParser\n{\npublic:\n URIAuthorityParser(URI::Authority &authority)\n {\n m_authority = &authority;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_authority_parser_first_final;\n }\n\n bool error() const\n {\n return cs == uri_authority_parser_error;\n }\n\nprivate:\n URI::Authority *m_authority;\n};\n\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable: 4355)\n#endif\nURI::URI()\n : path(*this)\n{\n reset();\n}\n\nURI::URI(const std::string& uri)\n : path(*this)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const char *uri)\n : path(*this)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const Buffer &uri)\n : path(*this)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const URI &uri)\n : authority(uri.authority),\n path(*this, uri.path),\n m_scheme(uri.m_scheme),\n m_query(uri.m_query),\n m_fragment(uri.m_fragment),\n m_schemeDefined(uri.m_schemeDefined),\n m_queryDefined(uri.m_queryDefined),\n m_fragmentDefined(uri.m_fragmentDefined)\n{}\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n\nURI&\nURI::operator=(const std::string& uri)\n{\n reset();\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"uri\"));\n return *this;\n}\n\nURI&\nURI::operator=(const Buffer &uri)\n{\n reset();\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"uri\"));\n return *this;\n}\n\nvoid\nURI::reset()\n{\n schemeDefined(false);\n authority.hostDefined(false);\n path.segments.clear();\n queryDefined(false);\n fragmentDefined(false);\n}\n\nURI::Authority::Authority()\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n}\n\nURI::Authority::Authority(const char *authority)\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n *this = authority;\n}\n\nURI::Authority::Authority(const std::string& authority)\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n *this = authority;\n}\n\nURI::Authority&\nURI::Authority::operator=(const std::string& authority)\n{\n URIAuthorityParser parser(*this);\n parser.run(authority);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"authority\"));\n return *this;\n}\n\nvoid\nURI::Authority::normalize(const std::string& defaultHost, bool emptyHostValid,\n int defaultPort, bool emptyPortValid)\n{\n for(size_t i = 0; i < m_host.length(); ++i)\n m_host[i] = tolower(m_host[i]);\n if (m_port == defaultPort)\n m_port = -1;\n if (m_port == -1 && !emptyPortValid)\n m_portDefined = false;\n if (m_host == defaultHost)\n m_host.clear();\n if (m_host.empty() && !emptyHostValid && !m_userinfoDefined && !m_portDefined)\n m_hostDefined = false;\n}\n\nstd::string\nURI::Authority::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstatic int boolcmp(bool lhs, bool rhs)\n{\n if (!lhs && rhs)\n return -1;\n if (lhs && !rhs)\n return 1;\n return 0;\n}\n\nint\nURI::Authority::cmp(const Authority &rhs) const\n{\n int x = boolcmp(m_hostDefined, rhs.m_hostDefined);\n if (x != 0) return x;\n x = strcmp(m_host.c_str(), rhs.m_host.c_str());\n if (x != 0) return x;\n x = boolcmp(m_portDefined, rhs.m_portDefined);\n if (x != 0) return x;\n x = m_port - rhs.m_port;\n if (x != 0) return x;\n x = boolcmp(m_userinfoDefined, rhs.m_userinfoDefined);\n if (x != 0) return x;\n return strcmp(m_userinfo.c_str(), rhs.m_userinfo.c_str());\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Authority& authority)\n{\n MORDOR_ASSERT(authority.hostDefined());\n if (authority.userinfoDefined()) {\n os << escape(authority.userinfo(), userinfo) << \"@\";\n }\n os << escape(authority.host(), host);\n if (authority.portDefined()) {\n os << \":\";\n if (authority.port() > 0) {\n os << authority.port();\n }\n }\n return os;\n}\n\nURI::Path::Path(const URI &uri)\n : m_uri(&uri)\n{}\n\nURI::Path::Path(const URI &uri, const Path &path)\n : segments(path.segments),\n m_uri(&uri)\n{}\n\nURI::Path::Path()\n : m_uri(NULL)\n {}\n\nURI::Path::Path(const char *path)\n : m_uri(NULL)\n{\n *this = path;\n}\n\nURI::Path::Path(const std::string &path)\n : m_uri(NULL)\n{\n *this = path;\n}\n\nURI::Path::Path(const Path &path)\n : segments(path.segments),\n m_uri(NULL)\n{\n segments = path.segments;\n}\n\nURI::Path &\nURI::Path::operator=(const std::string &path)\n{\n std::vector result;\n URIPathParser parser(result);\n parser.run(path);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"path\"));\n segments.swap(result);\n return *this;\n}\n\nURI::Path &\nURI::Path::operator=(const Path &path)\n{\n segments = path.segments;\n \/\/ Do not copy m_uri\n return *this;\n}\n\nvoid\nURI::Path::makeAbsolute()\n{\n if (segments.empty()) {\n segments.push_back(std::string());\n segments.push_back(std::string());\n } else if (!segments.front().empty()) {\n segments.insert(segments.begin(), std::string());\n }\n}\n\nvoid\nURI::Path::makeRelative()\n{\n if (!segments.empty() && segments.front().empty()) {\n segments.erase(segments.begin());\n if (segments.size() == 1u && segments.front().empty())\n segments.clear();\n }\n}\n\nvoid\nURI::Path::append(const std::string &segment)\n{\n if (m_uri && segments.empty() && m_uri->authority.hostDefined()) {\n segments.push_back(std::string());\n segments.push_back(segment);\n } else if (segments.empty() || !segments[segments.size() - 1].empty() ||\n \/\/ Special case for degenerate single-empty-segment path\n (segments.size() == 1 && segments.front().empty())) {\n segments.push_back(segment);\n } else {\n segments[segments.size() - 1] = segment;\n }\n}\n\nvoid\nURI::Path::removeDotComponents()\n{\n for(size_t i = 0; i < segments.size(); ++i) {\n if (i == 0 && segments[i].empty())\n continue;\n if (segments[i] == \".\") {\n if (i + 1 == segments.size()) {\n segments[i].clear();\n continue;\n } else {\n segments.erase(segments.begin() + i);\n --i;\n continue;\n }\n }\n if (segments[i] == \"..\") {\n if (i == 0) {\n segments.erase(segments.begin());\n --i;\n continue;\n }\n if (i == 1 && segments.front().empty()) {\n segments.erase(segments.begin() + i);\n --i;\n continue;\n }\n if (i + 1 == segments.size()) {\n segments.resize(segments.size() - 1);\n segments.back().clear();\n --i;\n continue;\n }\n segments.erase(segments.begin() + i - 1, segments.begin() + i + 1);\n i -= 2;\n continue;\n }\n }\n}\n\nvoid\nURI::Path::normalize(bool emptyPathValid)\n{\n removeDotComponents();\n}\n\nvoid\nURI::Path::merge(const Path& rhs)\n{\n MORDOR_ASSERT(rhs.isRelative());\n if (!segments.empty()) {\n segments.pop_back();\n segments.insert(segments.end(), rhs.segments.begin(), rhs.segments.end());\n } else {\n segments = rhs.segments;\n }\n}\n\nURI::Path::path_serializer\nURI::Path::serialize(bool schemeless) const\n{\n path_serializer result;\n result.p = this;\n result.schemeless = schemeless;\n return result;\n}\n\nstd::string\nURI::Path::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path::path_serializer &p)\n{\n const std::vector &segments = p.p->segments;\n for (std::vector::const_iterator it = segments.begin();\n it != segments.end();\n ++it) {\n if (it != segments.begin())\n os << '\/';\n if (it == segments.begin() && p.schemeless)\n os << escape(*it, segment_nc);\n else\n os << escape(*it, pchar);\n }\n return os;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path& path)\n{\n return os << path.serialize();\n}\n\nint\nURI::Path::cmp(const Path &rhs) const\n{\n std::vector::const_iterator itl, itr;\n itl = segments.begin(); itr = rhs.segments.begin();\n while (true) {\n if (itl == segments.end() && itr != rhs.segments.end())\n return -1;\n if (itl != segments.end() && itr == rhs.segments.end())\n return 1;\n if (itl == segments.end() && itr == rhs.segments.end())\n return 0;\n int x = strcmp(itl->c_str(), itr->c_str());\n if (x != 0) return x;\n ++itl; ++itr;\n }\n}\n\nvoid\nURI::normalize()\n{\n for (size_t i = 0; i < m_scheme.size(); ++i)\n m_scheme[i] = tolower(m_scheme[i]);\n\n if (m_scheme == \"http\" || m_scheme == \"https\") {\n authority.normalize(\"\", false, m_scheme.size() == 4 ? 80 : 443, false);\n path.normalize();\n } else if (m_scheme == \"file\") {\n authority.normalize(\"localhost\", true);\n path.normalize();\n } else if (m_scheme == \"socks\") {\n authority.normalize(\"\", false, 1080, false);\n path.normalize();\n } else {\n authority.normalize();\n path.normalize();\n }\n}\n\nstd::string\nURI::query() const\n{\n MORDOR_ASSERT(m_queryDefined);\n return unescape(m_query);\n}\n\nvoid\nURI::query(const std::string &q)\n{\n m_queryDefined = true;\n m_query = escape(q, Mordor::query);\n}\n\nstd::string\nURI::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI& uri)\n{\n MORDOR_ASSERT(!uri.authority.hostDefined() || uri.path.isAbsolute() ||\n uri.path.isEmpty());\n if (uri.schemeDefined())\n os << escape(uri.scheme(), scheme) << \":\";\n\n if (uri.authority.hostDefined()) {\n os << \"\/\/\" << uri.authority;\n \/\/ authority is always part of hier_part, which only allows\n \/\/ path_abempty\n MORDOR_ASSERT(uri.path.isAbsolute() || uri.path.isEmpty());\n }\n\n \/\/ Has scheme, but no authority, must ensure that an absolute path\n \/\/ doesn't begin with an empty segment (or could be mistaken for authority)\n if (uri.schemeDefined() && !uri.authority.hostDefined() &&\n uri.path.isAbsolute() &&\n uri.path.segments.size() >= 3 && uri.path.segments[1].empty()) {\n os << \"\/\/\";\n }\n os << uri.path.serialize(!uri.schemeDefined());\n\n if (uri.queryDefined())\n os << \"?\" << uri.m_query;\n\n if (uri.fragmentDefined())\n os << \"#\" << escape(uri.fragment(), query);\n return os;\n}\n\nURI\nURI::transform(const URI& base, const URI& relative)\n{\n MORDOR_ASSERT(base.schemeDefined());\n\n URI target;\n if (relative.schemeDefined()) {\n target.scheme(relative.scheme());\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.authority.hostDefined()) {\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.path.isEmpty()) {\n target.path = base.path;\n if (relative.queryDefined()) {\n target.query(relative.query());\n } else {\n target.m_query = base.m_query;\n target.m_queryDefined = base.m_queryDefined;\n }\n } else {\n if (relative.path.isAbsolute()) {\n target.path = relative.path;\n } else {\n if (base.authority.hostDefined() && base.path.isEmpty()) {\n target.path.segments.push_back(std::string());\n target.path.segments.push_back(std::string());\n } else {\n target.path = base.path;\n }\n target.path.merge(relative.path);\n }\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n }\n target.authority = base.authority;\n }\n target.scheme(base.scheme());\n }\n target.m_fragment = relative.m_fragment;\n target.m_fragmentDefined = relative.m_fragmentDefined;\n return target;\n}\n\nint\nURI::cmp(const URI &rhs) const\n{\n int x = boolcmp(m_schemeDefined, rhs.m_schemeDefined);\n if (x != 0) return x;\n x = strcmp(m_scheme.c_str(), rhs.m_scheme.c_str());\n if (x != 0) return x;\n x = authority.cmp(rhs.authority);\n if (x != 0) return x;\n x = path.cmp(rhs.path);\n if (x != 0) return x;\n x = boolcmp(m_queryDefined, rhs.m_queryDefined);\n if (x != 0) return x;\n x = strcmp(m_query.c_str(), rhs.m_query.c_str());\n if (x != 0) return x;\n x = boolcmp(m_fragmentDefined, rhs.m_fragmentDefined);\n if (x != 0) return x;\n return strcmp(m_fragment.c_str(), rhs.m_fragment.c_str());\n}\n\n%%{\n machine querystring_parser;\n\n action mark { mark = fpc; }\n action saveKey {\n m_iterator = m_qs.insert(std::make_pair(\n unescape(std::string(mark, fpc - mark), true), std::string()));\n mark = NULL;\n }\n action saveValue {\n MORDOR_ASSERT(m_iterator != m_qs.end());\n if (fpc - mark == 0 && m_iterator->first.empty())\n m_qs.erase(m_iterator);\n else\n m_iterator->second = unescape(std::string(mark, fpc - mark), true);\n m_iterator = m_qs.end();\n mark = NULL;\n }\n action saveNoValue {\n if (m_iterator != m_qs.end() && m_iterator->first.empty()) {\n m_qs.erase(m_iterator);\n mark = NULL;\n }\n }\n\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\";\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n querychar = (pchar | \"\/\" | \"?\") -- '&' -- ';';\n key = querychar*;\n value = (querychar | '=')*;\n keyValue = key >mark %saveKey ('=' value >mark %saveValue)? %saveNoValue;\n main := keyValue? ( ('&' | ';') keyValue? )*;\n write data;\n}%%\n\nclass QueryStringParser : public RagelParser\n{\npublic:\n QueryStringParser(URI::QueryString &qs)\n : m_qs(qs),\n m_iterator(m_qs.end())\n {}\n\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\n bool complete() const { return false; }\n bool final() const\n {\n return cs >= querystring_parser_first_final;\n }\n\n bool error() const\n {\n return cs == querystring_parser_error;\n }\n\nprivate:\n URI::QueryString &m_qs;\n URI::QueryString::iterator m_iterator;\n};\n\nURI::QueryString &\nURI::QueryString::operator =(const std::string &string)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(string);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nURI::QueryString &\nURI::QueryString::operator =(Stream &stream)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(stream);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nstd::string\nURI::QueryString::toString() const\n{\n std::ostringstream os;\n for (const_iterator it = begin();\n it != end();\n ++it) {\n if (it != begin()) {\n os << '&';\n }\n os << escape(it->first, Mordor::queryString, true);\n if (!it->second.empty())\n os << '=' << escape(it->second, Mordor::queryString, true);\n }\n return os.str();\n}\n\nstd::string &\nURI::QueryString::operator[](const std::string &key)\n{\n std::pair its = equal_range(key);\n \/\/ Did not exist; create it\n if (its.first == its.second)\n return insert(std::make_pair(key, std::string()))->second;\n \/\/ Multiple instances; remove all but the first\n iterator next = its.first;\n ++next;\n erase(next, its.second);\n \/\/ Left with a single (first) instance; return it\n return its.first->second;\n}\n\nstd::string\nURI::QueryString::operator[](const std::string &key) const\n{\n std::pair its = equal_range(key);\n \/\/ Did not exist\n if (its.first == its.second)\n return std::string();\n \/\/ Return only the first instance\n return its.first->second;\n}\n\n}\n","old_contents":"\/\/ Copyright (c) 2009 - Mozy, Inc.\n\/* To compile to .cpp:\n ragel uri.rl -G2 -o uri.cpp\n*\/\n\n#include \"mordor\/pch.h\"\n\n#include \"mordor\/uri.h\"\n\n#include \n\n#include \"mordor\/ragel.h\"\n#include \"mordor\/string.h\"\n#include \"mordor\/version.h\"\n\nnamespace Mordor {\n\nstatic const std::string unreserved(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\");\nstatic const std::string sub_delims(\"!$&'()*+,;=\");\nstatic const std::string scheme(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.\");\nstatic const std::string userinfo(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string host(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string pchar(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\");\nstatic const std::string path(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/\");\nstatic const std::string segment_nc(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \"@\");\nstatic const std::string query(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/?\");\nstatic const std::string queryString(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$'()*,\" \":@\" \"\/?\");\n\nstatic std::string escape(const std::string& str, const std::string& allowedChars, bool spaceAsPlus = false)\n{\n const char *hexdigits = \"0123456789ABCDEF\";\n std::string result(str);\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while(c < end)\n {\n if (allowedChars.find(*c) == std::string::npos) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n if (*c == ' ' && spaceAsPlus) {\n result.append(1, '+');\n } else {\n result.append(1, '%');\n result.append(1, hexdigits[(unsigned char)*c >> 4]);\n result.append(1, hexdigits[*c & 0xf]);\n }\n } else {\n if (differed) {\n result.append(1, *c);\n }\n }\n ++c;\n }\n\n if (differed) {\n MORDOR_ASSERT(result.length() >= str.length());\n } else {\n MORDOR_ASSERT(result == str);\n }\n return result;\n}\n\nstd::string unescape(const std::string& str, bool spaceAsPlus = false)\n{\n std::string result = str;\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while (c < end)\n {\n if (*c == '%') {\n MORDOR_ASSERT(c + 2 < end);\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n char decoded;\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded = (*c - 'a' + 10) << 4;\n else if (*c >= 'A' && *c <= 'F')\n decoded = (*c - 'A' + 10) << 4;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded = (*c - '0') << 4;\n }\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded |= *c - 'a' + 10;\n else if (*c >= 'A' && *c <= 'F')\n decoded |= *c - 'A' + 10;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded |= *c - '0';\n }\n result.append(1, decoded);\n } else if (*c == '+' && spaceAsPlus) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n result.append(1, ' ');\n } else if (differed) {\n result.append(1, *c);\n }\n ++c;\n }\n return result;\n}\n\nstd::string\nURI::encode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return escape(str, unreserved, false);\n case QUERYSTRING:\n return escape(str, Mordor::queryString, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\nstd::string\nURI::decode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return unescape(str, false);\n case QUERYSTRING:\n return unescape(str, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\n%%{\n # See RFC 3986: http:\/\/www.ietf.org\/rfc\/rfc3986.txt\n\n machine uri_parser;\n\n gen_delims = \":\" | \"\/\" | \"?\" | \"#\" | \"[\" | \"]\" | \"@\";\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\" | \"=\";\n reserved = gen_delims | sub_delims;\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n\n action marku { mark = fpc; }\n action markh { mark = fpc; }\n action save_scheme\n {\n m_uri->scheme(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n scheme = (alpha (alpha | digit | \"+\" | \"-\" | \".\")*) >marku %save_scheme;\n\n action save_port\n {\n if (fpc == mark)\n m_authority->port(-1);\n else\n m_authority->port(atoi(mark));\n mark = NULL;\n }\n action save_userinfo\n {\n m_authority->userinfo(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n action save_host\n {\n if (mark != NULL) {\n m_authority->host(unescape(std::string(mark, fpc - mark)));\n \/\/ This could have been part of the userinfo, so don't clear the mark\n \/\/ mark = NULL;\n }\n }\n\n userinfo = (unreserved | pct_encoded | sub_delims | \":\")*;\n dec_octet = digit | [1-9] digit | \"1\" digit{2} | 2 [0-4] digit | \"25\" [0-5];\n IPv4address = dec_octet \".\" dec_octet \".\" dec_octet \".\" dec_octet;\n h16 = xdigit{1,4};\n ls32 = (h16 \":\" h16) | IPv4address;\n IPv6address = ( (h16 \":\"){6} ls32) |\n ( \"::\" (h16 \":\"){5} ls32) |\n (( h16)? \"::\" (h16 \":\"){4} ls32) |\n (((h16 \":\"){1} h16)? \"::\" (h16 \":\"){3} ls32) |\n (((h16 \":\"){2} h16)? \"::\" (h16 \":\"){2} ls32) |\n (((h16 \":\"){3} h16)? \"::\" (h16 \":\"){1} ls32) |\n (((h16 \":\"){4} h16)? \"::\" ls32) |\n (((h16 \":\"){5} h16)? \"::\" h16 ) |\n (((h16 \":\"){6} h16)? \"::\" );\n IPvFuture = \"v\" xdigit+ \".\" (unreserved | sub_delims | \":\")+;\n IP_literal = \"[\" (IPv6address | IPvFuture) \"]\";\n reg_name = (unreserved | pct_encoded | sub_delims)*;\n host = reg_name;#IP_literal | IPv4address | reg_name;\n port = digit*;\n\n authority = ( (userinfo %save_userinfo \"@\")? host >markh %save_host (\":\" port >markh %save_port)? ) >markh;\n\n action save_segment\n {\n m_segments->push_back(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n segment = pchar* >marku %save_segment;\n segment_nz = pchar+ >marku %save_segment;\n segment_nz_nc = (pchar - \":\")+ >marku %save_segment;\n\n action clear_segments\n {\n m_segments->clear();\n }\n\n path_abempty = ((\"\/\" >marku >save_segment segment) %marku %save_segment)? (\"\/\" segment)*;\n path_absolute = (\"\/\" >marku >save_segment (segment_nz (\"\/\" segment)*)?) %marku %save_segment;\n path_noscheme = segment_nz_nc (\"\/\" segment)*;\n path_rootless = segment_nz (\"\/\" segment)*;\n path_empty = \"\";\n path = (path_abempty | path_absolute | path_noscheme | path_rootless | path_empty);\n\n action save_query\n {\n m_uri->m_query = std::string(mark, fpc - mark);\n m_uri->m_queryDefined = true;\n mark = NULL;\n }\n action save_fragment\n {\n m_uri->fragment(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n query = (pchar | \"\/\" | \"?\")* >marku %save_query;\n fragment = (pchar | \"\/\" | \"?\")* >marku %save_fragment;\n\n hier_part = (\"\/\/\" %clear_segments authority path_abempty) | path_absolute | path_rootless | path_empty;\n\n relative_part = (\"\/\/\" %clear_segments authority path_abempty) | path_absolute | path_noscheme | path_empty;\n relative_ref = relative_part ( \"?\" query )? ( \"#\" fragment )?;\n\n absolute_URI = scheme \":\" hier_part ( \"?\" query )? ;\n # Obsolete, but referenced from HTTP, so we translate\n relative_URI = relative_part ( \"?\" query )?;\n\n URI = scheme \":\" hier_part ( \"?\" query )? ( \"#\" fragment )?;\n URI_reference = URI | relative_ref;\n}%%\n\n%%{\n machine uri_parser_proper;\n include uri_parser;\n main := URI_reference;\n write data;\n}%%\n\nclass URIParser : public RagelParser\n{\npublic:\n URIParser(URI& uri)\n {\n m_uri = &uri;\n m_segments = &m_uri->path.segments;\n m_authority = &m_uri->authority;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_parser_proper_first_final;\n }\n\n bool error() const\n {\n return cs == uri_parser_proper_error;\n }\n\nprivate:\n URI *m_uri;\n std::vector *m_segments;\n URI::Authority *m_authority;\n};\n\n%%{\n machine uri_path_parser;\n include uri_parser;\n main := path;\n write data;\n}%%\nclass URIPathParser : public RagelParser\n{\npublic:\n URIPathParser(std::vector &segments)\n {\n m_segments = &segments;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_path_parser_first_final;\n }\n\n bool error() const\n {\n return cs == uri_path_parser_error;\n }\n\nprivate:\n std::vector *m_segments;\n};\n\n%%{\n machine uri_authority_parser;\n include uri_parser;\n main := authority;\n write data;\n}%%\nclass URIAuthorityParser : public RagelParser\n{\npublic:\n URIAuthorityParser(URI::Authority &authority)\n {\n m_authority = &authority;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_authority_parser_first_final;\n }\n\n bool error() const\n {\n return cs == uri_authority_parser_error;\n }\n\nprivate:\n URI::Authority *m_authority;\n};\n\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable: 4355)\n#endif\nURI::URI()\n : path(*this)\n{\n reset();\n}\n\nURI::URI(const std::string& uri)\n : path(*this)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const char *uri)\n : path(*this)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const Buffer &uri)\n : path(*this)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const URI &uri)\n : authority(uri.authority),\n path(*this, uri.path),\n m_scheme(uri.m_scheme),\n m_query(uri.m_query),\n m_fragment(uri.m_fragment),\n m_schemeDefined(uri.m_schemeDefined),\n m_queryDefined(uri.m_queryDefined),\n m_fragmentDefined(uri.m_fragmentDefined)\n{}\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n\nURI&\nURI::operator=(const std::string& uri)\n{\n reset();\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"uri\"));\n return *this;\n}\n\nURI&\nURI::operator=(const Buffer &uri)\n{\n reset();\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"uri\"));\n return *this;\n}\n\nvoid\nURI::reset()\n{\n schemeDefined(false);\n authority.hostDefined(false);\n path.segments.clear();\n queryDefined(false);\n fragmentDefined(false);\n}\n\nURI::Authority::Authority()\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n}\n\nURI::Authority::Authority(const char *authority)\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n *this = authority;\n}\n\nURI::Authority::Authority(const std::string& authority)\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n *this = authority;\n}\n\nURI::Authority&\nURI::Authority::operator=(const std::string& authority)\n{\n URIAuthorityParser parser(*this);\n parser.run(authority);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"authority\"));\n return *this;\n}\n\nvoid\nURI::Authority::normalize(const std::string& defaultHost, bool emptyHostValid,\n int defaultPort, bool emptyPortValid)\n{\n for(size_t i = 0; i < m_host.length(); ++i)\n m_host[i] = tolower(m_host[i]);\n if (m_port == defaultPort)\n m_port = -1;\n if (m_port == -1 && !emptyPortValid)\n m_portDefined = false;\n if (m_host == defaultHost)\n m_host.clear();\n if (m_host.empty() && !emptyHostValid && !m_userinfoDefined && !m_portDefined)\n m_hostDefined = false;\n}\n\nstd::string\nURI::Authority::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstatic int boolcmp(bool lhs, bool rhs)\n{\n if (!lhs && rhs)\n return -1;\n if (lhs && !rhs)\n return 1;\n return 0;\n}\n\nint\nURI::Authority::cmp(const Authority &rhs) const\n{\n int x = boolcmp(m_hostDefined, rhs.m_hostDefined);\n if (x != 0) return x;\n x = strcmp(m_host.c_str(), rhs.m_host.c_str());\n if (x != 0) return x;\n x = boolcmp(m_portDefined, rhs.m_portDefined);\n if (x != 0) return x;\n x = m_port - rhs.m_port;\n if (x != 0) return x;\n x = boolcmp(m_userinfoDefined, rhs.m_userinfoDefined);\n if (x != 0) return x;\n return strcmp(m_userinfo.c_str(), rhs.m_userinfo.c_str());\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Authority& authority)\n{\n MORDOR_ASSERT(authority.hostDefined());\n if (authority.userinfoDefined()) {\n os << escape(authority.userinfo(), userinfo) << \"@\";\n }\n os << escape(authority.host(), host);\n if (authority.portDefined()) {\n os << \":\";\n if (authority.port() > 0) {\n os << authority.port();\n }\n }\n return os;\n}\n\nURI::Path::Path(const URI &uri)\n : m_uri(&uri)\n{}\n\nURI::Path::Path(const URI &uri, const Path &path)\n : segments(path.segments),\n m_uri(&uri)\n{}\n\nURI::Path::Path()\n : m_uri(NULL)\n {}\n\nURI::Path::Path(const char *path)\n : m_uri(NULL)\n{\n *this = path;\n}\n\nURI::Path::Path(const std::string &path)\n : m_uri(NULL)\n{\n *this = path;\n}\n\nURI::Path::Path(const Path &path)\n : segments(path.segments),\n m_uri(NULL)\n{\n segments = path.segments;\n}\n\nURI::Path &\nURI::Path::operator=(const std::string &path)\n{\n std::vector result;\n URIPathParser parser(result);\n parser.run(path);\n if (parser.error() || !parser.final())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"path\"));\n segments.swap(result);\n return *this;\n}\n\nURI::Path &\nURI::Path::operator=(const Path &path)\n{\n segments = path.segments;\n \/\/ Do not copy m_uri\n return *this;\n}\n\nvoid\nURI::Path::makeAbsolute()\n{\n if (segments.empty()) {\n segments.push_back(std::string());\n segments.push_back(std::string());\n } else if (!segments.front().empty()) {\n segments.insert(segments.begin(), std::string());\n }\n}\n\nvoid\nURI::Path::makeRelative()\n{\n if (!segments.empty() && segments.front().empty()) {\n segments.erase(segments.begin());\n if (segments.size() == 1u && segments.front().empty())\n segments.clear();\n }\n}\n\nvoid\nURI::Path::append(const std::string &segment)\n{\n if (m_uri && segments.empty() && m_uri->authority.hostDefined()) {\n segments.push_back(std::string());\n segments.push_back(segment);\n } else if (segments.empty() || !segments[segments.size() - 1].empty() ||\n \/\/ Special case for degenerate single-empty-segment path\n (segments.size() == 1 && segments.front().empty())) {\n segments.push_back(segment);\n } else {\n segments[segments.size() - 1] = segment;\n }\n}\n\nvoid\nURI::Path::removeDotComponents()\n{\n for(size_t i = 0; i < segments.size(); ++i) {\n if (i == 0 && segments[i].empty())\n continue;\n if (segments[i] == \".\") {\n if (i + 1 == segments.size()) {\n segments[i].clear();\n continue;\n } else {\n segments.erase(segments.begin() + i);\n --i;\n continue;\n }\n }\n if (segments[i] == \"..\") {\n if (i == 0) {\n segments.erase(segments.begin());\n --i;\n continue;\n }\n if (i == 1 && segments.front().empty()) {\n segments.erase(segments.begin() + i);\n --i;\n continue;\n }\n if (i + 1 == segments.size()) {\n segments.resize(segments.size() - 1);\n segments.back().clear();\n --i;\n continue;\n }\n segments.erase(segments.begin() + i - 1, segments.begin() + i + 1);\n i -= 2;\n continue;\n }\n }\n}\n\nvoid\nURI::Path::normalize(bool emptyPathValid)\n{\n removeDotComponents();\n}\n\nvoid\nURI::Path::merge(const Path& rhs)\n{\n MORDOR_ASSERT(rhs.isRelative());\n if (!segments.empty()) {\n segments.pop_back();\n segments.insert(segments.end(), rhs.segments.begin(), rhs.segments.end());\n } else {\n segments = rhs.segments;\n }\n}\n\nURI::Path::path_serializer\nURI::Path::serialize(bool schemeless) const\n{\n path_serializer result;\n result.p = this;\n result.schemeless = schemeless;\n return result;\n}\n\nstd::string\nURI::Path::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path::path_serializer &p)\n{\n const std::vector &segments = p.p->segments;\n for (std::vector::const_iterator it = segments.begin();\n it != segments.end();\n ++it) {\n if (it != segments.begin())\n os << '\/';\n if (it == segments.begin() && p.schemeless)\n os << escape(*it, segment_nc);\n else\n os << escape(*it, pchar);\n }\n return os;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path& path)\n{\n return os << path.serialize();\n}\n\nint\nURI::Path::cmp(const Path &rhs) const\n{\n std::vector::const_iterator itl, itr;\n itl = segments.begin(); itr = rhs.segments.begin();\n while (true) {\n if (itl == segments.end() && itr != rhs.segments.end())\n return -1;\n if (itl != segments.end() && itr == rhs.segments.end())\n return 1;\n if (itl == segments.end() && itr == rhs.segments.end())\n return 0;\n int x = strcmp(itl->c_str(), itr->c_str());\n if (x != 0) return x;\n ++itl; ++itr;\n }\n}\n\nvoid\nURI::normalize()\n{\n for (size_t i = 0; i < m_scheme.size(); ++i)\n m_scheme[i] = tolower(m_scheme[i]);\n\n if (m_scheme == \"http\" || m_scheme == \"https\") {\n authority.normalize(\"\", false, m_scheme.size() == 4 ? 80 : 443, false);\n path.normalize();\n } else if (m_scheme == \"file\") {\n authority.normalize(\"localhost\", true);\n path.normalize();\n } else if (m_scheme == \"socks\") {\n authority.normalize(\"\", false, 1080, false);\n path.normalize();\n } else {\n authority.normalize();\n path.normalize();\n }\n}\n\nstd::string\nURI::query() const\n{\n MORDOR_ASSERT(m_queryDefined);\n return unescape(m_query);\n}\n\nvoid\nURI::query(const std::string &q)\n{\n m_queryDefined = true;\n m_query = escape(q, Mordor::query);\n}\n\nstd::string\nURI::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI& uri)\n{\n MORDOR_ASSERT(!uri.authority.hostDefined() || uri.path.isAbsolute() ||\n uri.path.isEmpty());\n if (uri.schemeDefined())\n os << escape(uri.scheme(), scheme) << \":\";\n\n if (uri.authority.hostDefined()) {\n os << \"\/\/\" << uri.authority;\n \/\/ authority is always part of hier_part, which only allows\n \/\/ path_abempty\n MORDOR_ASSERT(uri.path.isAbsolute() || uri.path.isEmpty());\n }\n\n \/\/ Has scheme, but no authority, must ensure that an absolute path\n \/\/ doesn't begin with an empty segment (or could be mistaken for authority)\n if (uri.schemeDefined() && !uri.authority.hostDefined() &&\n uri.path.isAbsolute() &&\n uri.path.segments.size() >= 3 && uri.path.segments[1].empty()) {\n os << \"\/\/\";\n }\n os << uri.path.serialize(!uri.schemeDefined());\n\n if (uri.queryDefined())\n os << \"?\" << uri.m_query;\n\n if (uri.fragmentDefined())\n os << \"#\" << escape(uri.fragment(), query);\n return os;\n}\n\nURI\nURI::transform(const URI& base, const URI& relative)\n{\n MORDOR_ASSERT(base.schemeDefined());\n\n URI target;\n if (relative.schemeDefined()) {\n target.scheme(relative.scheme());\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.authority.hostDefined()) {\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.path.isEmpty()) {\n target.path = base.path;\n if (relative.queryDefined()) {\n target.query(relative.query());\n } else {\n target.m_query = base.m_query;\n target.m_queryDefined = base.m_queryDefined;\n }\n } else {\n if (relative.path.isAbsolute()) {\n target.path = relative.path;\n } else {\n if (base.authority.hostDefined() && base.path.isEmpty()) {\n target.path.segments.push_back(std::string());\n target.path.segments.push_back(std::string());\n } else {\n target.path = base.path;\n }\n target.path.merge(relative.path);\n }\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n }\n target.authority = base.authority;\n }\n target.scheme(base.scheme());\n }\n target.m_fragment = relative.m_fragment;\n target.m_fragmentDefined = relative.m_fragmentDefined;\n return target;\n}\n\nint\nURI::cmp(const URI &rhs) const\n{\n int x = boolcmp(m_schemeDefined, rhs.m_schemeDefined);\n if (x != 0) return x;\n x = strcmp(m_scheme.c_str(), rhs.m_scheme.c_str());\n if (x != 0) return x;\n x = authority.cmp(rhs.authority);\n if (x != 0) return x;\n x = path.cmp(rhs.path);\n if (x != 0) return x;\n x = boolcmp(m_queryDefined, rhs.m_queryDefined);\n if (x != 0) return x;\n x = strcmp(m_query.c_str(), rhs.m_query.c_str());\n if (x != 0) return x;\n x = boolcmp(m_fragmentDefined, rhs.m_fragmentDefined);\n if (x != 0) return x;\n return strcmp(m_fragment.c_str(), rhs.m_fragment.c_str());\n}\n\n%%{\n machine querystring_parser;\n\n action mark { mark = fpc; }\n action saveKey {\n m_iterator = m_qs.insert(std::make_pair(\n unescape(std::string(mark, fpc - mark), true), std::string()));\n mark = NULL;\n }\n action saveValue {\n MORDOR_ASSERT(m_iterator != m_qs.end());\n if (fpc - mark == 0 && m_iterator->first.empty())\n m_qs.erase(m_iterator);\n else\n m_iterator->second = unescape(std::string(mark, fpc - mark), true);\n m_iterator = m_qs.end();\n mark = NULL;\n }\n action saveNoValue {\n if (m_iterator != m_qs.end() && m_iterator->first.empty()) {\n m_qs.erase(m_iterator);\n mark = NULL;\n }\n }\n\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\";\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n querychar = (pchar | \"\/\" | \"?\") -- '&' -- ';';\n key = querychar*;\n value = (querychar | '=')*;\n keyValue = key >mark %saveKey ('=' value >mark %saveValue)? %saveNoValue;\n main := keyValue? ( ('&' | ';') keyValue? )*;\n write data;\n}%%\n\nclass QueryStringParser : public RagelParser\n{\npublic:\n QueryStringParser(URI::QueryString &qs)\n : m_qs(qs),\n m_iterator(m_qs.end())\n {}\n\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\n bool complete() const { return false; }\n bool final() const\n {\n return cs >= querystring_parser_first_final;\n }\n\n bool error() const\n {\n return cs == querystring_parser_error;\n }\n\nprivate:\n URI::QueryString &m_qs;\n URI::QueryString::iterator m_iterator;\n};\n\nURI::QueryString &\nURI::QueryString::operator =(const std::string &string)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(string);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nURI::QueryString &\nURI::QueryString::operator =(Stream &stream)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(stream);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nstd::string\nURI::QueryString::toString() const\n{\n std::ostringstream os;\n for (const_iterator it = begin();\n it != end();\n ++it) {\n if (it != begin()) {\n os << '&';\n }\n os << escape(it->first, Mordor::queryString, true);\n if (!it->second.empty())\n os << '=' << escape(it->second, Mordor::queryString, true);\n }\n return os.str();\n}\n\nstd::string &\nURI::QueryString::operator[](const std::string &key)\n{\n std::pair its = equal_range(key);\n \/\/ Did not exist; create it\n if (its.first == its.second)\n return insert(std::make_pair(key, std::string()))->second;\n \/\/ Multiple instances; remove all but the first\n iterator next = its.first;\n ++next;\n erase(next, its.second);\n \/\/ Left with a single (first) instance; return it\n return its.first->second;\n}\n\nstd::string\nURI::QueryString::operator[](const std::string &key) const\n{\n std::pair its = equal_range(key);\n \/\/ Did not exist\n if (its.first == its.second)\n return std::string();\n \/\/ Return only the first instance\n return its.first->second;\n}\n\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"9aa7f1fe9b8872112a98ba3d5860a64df5d6ff53","subject":"- todo to implement LOGSTASH-728","message":"- todo to implement LOGSTASH-728\n","repos":"tinglinux\/logstash-kafka,joekiller\/logstash-kafka,Aloomaio\/logstash-kafka,joekiller\/logstash-kafka,opentable\/logstash-kafka,Aloomaio\/logstash-kafka,tinglinux\/logstash-kafka,opentable\/logstash-kafka","old_file":"lib\/logstash\/config\/grammar.rl","new_file":"lib\/logstash\/config\/grammar.rl","new_contents":"require \"logstash\/namespace\"\n\n%%{\n machine logstash_config;\n\n action mark {\n @tokenstack.push(p)\n #puts \"Mark: #{self.line(string, p)}##{self.column(string, p)}\"\n }\n\n action stack_numeric {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"numeric: #{token}\"\n #puts \"numeric?: #{string[startpos,50]}\"\n #puts [startpos, endpos].join(\",\")\n # TODO(sissel): Don't do 'to_i' here. Type coersion is the job of the\n # plugin and the validator.\n @stack << token.to_i\n }\n\n action stack_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"string: #{token}\"\n @stack << token\n }\n\n action stack_quoted_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos + 1 ... endpos - 1] # Skip quotations\n\n # Parse escapes.\n token.gsub(\/\\\\.\/) { |m| m[1,1] }\n #puts \"quotedstring: #{token}\"\n @stack << token\n }\n\n action array_init {\n @array = []\n @stack << :array_init\n }\n\n action array_push {\n while @stack.last != :array_init\n @array.unshift @stack.pop\n end\n @stack.pop # pop :array_init\n\n @stack << @array\n }\n\n action parameter_init {\n # nothing\n }\n\n action parameter {\n value = @stack.pop\n name = @stack.pop\n #puts \"parameter: #{name} => #{value}\"\n if value.is_a?(Array)\n @parameters[name] += value\n else\n @parameters[name] << value\n end\n }\n\n action plugin {\n @components ||= []\n name = @stack.pop\n #@components << { :name => name, :parameters => @parameters }\n @components << { name => @parameters }\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action component_init {\n @components = []\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action component {\n name = @stack.pop\n @config ||= Hash.new { |h,k| h[k] = [] }\n @config[name] += @components\n #puts \"Config component: #{name}\"\n }\n\n #%{ e = @tokenstack.pop; puts \"Comment: #{string[e ... p]}\" };\n comment = \"#\" (any - [\\n])* >mark ; \n ws = ([ \\t\\n] | comment)** ;\n #ws = ([ \\t\\n])** ;\n\n # TODO(sissel): Support floating point values?\n numeric = ( (\"+\" | \"-\")? [0-9] :>> [0-9]** ) >mark %stack_numeric;\n quoted_string = ( \n ( \"\\\"\" ( ( (any - [\\\\\"\\n]) | \"\\\\\" any )* ) \"\\\"\" )\n | ( \"'\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"'\" ) \n ) >mark %stack_quoted_string ;\n naked_string = ( [A-Za-z_] :>> [A-Za-z0-9_]* ) >mark %stack_string ;\n string = ( quoted_string | naked_string ) ;\n\n # TODO(sissel): allow use of this.\n regexp_literal = ( \"\/\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"\/\" ) ;\n\n array = ( \"[\" ws ( string | numeric ) ws (\",\" ws (string | numeric ) ws)* \"]\" ) >array_init %array_push;\n # TODO(sissel): Implement hash syntax { key => value, ... }\n # TODO(sissel): hashes should support arrays as values.\n\n parameter_value = ( numeric | string | array );\n parameter = ( string ws \"=>\" ws parameter_value ) %parameter ;\n parameters = ( parameter ( ws parameter )** ) >parameter_init ;\n\n # Statement:\n # component {\n # plugin_name {\n # bar => ...\n # baz => ...\n # }\n # ...\n # }\n\n plugin = (\n (\n naked_string ws \"{\" ws\n parameters\n ws \"}\"\n ) | ( \n naked_string ws \"{\" ws \"}\" \n )\n ) %plugin ; \n\n component = (\n naked_string ws \"{\"\n >component_init\n ( ws plugin )**\n ws \"}\"\n ) %component ;\n\n config = (ws component? )** ;\n\n main := config %{ puts \"END\" }\n $err { \n # Compute line and column of the cursor (p)\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n # TODO(sissel): Note what we were expecting?\n } ;\n}%%\n\nclass LogStash::Config::Grammar\n attr_accessor :eof\n attr_accessor :config\n\n def initialize\n # BEGIN RAGEL DATA\n %% write data;\n # END RAGEL DATA\n\n @tokenstack = Array.new\n @stack = Array.new\n\n @types = Hash.new { |h,k| h[k] = [] }\n @edges = []\n end\n\n def parse(string)\n # TODO(sissel): Due to a bug in my parser, we need one trailing whitespace\n # at the end of the string. I'll fix this later.\n string += \"\\n\"\n\n data = string.unpack(\"c*\")\n\n\n # BEGIN RAGEL INIT\n %% write init;\n # END RAGEL INIT\n\n begin \n # BEGIN RAGEL EXEC \n %% write exec;\n # END RAGEL EXEC\n rescue => e\n # Compute line and column of the cursor (p)\n raise e\n end\n\n if cs < self.logstash_config_first_final\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n raise \"Invalid Configuration. Check syntax of config file.\"\n end\n return cs\n end # def parse\n\n def line(str, pos)\n return str[0 .. pos].count(\"\\n\") + 1\n end\n\n def column(str, pos)\n return str[0 .. pos].split(\"\\n\").last.length\n end\nend # class LogStash::Config::Grammar\n\n#def parse(string)\n #cfgparser = LogStash::Config::Grammar.new\n #result = cfgparser.parse(string)\n #puts \"result %s\" % result\n #ap cfgparser.config\n#end\n\n#parse(File.open(ARGV[0]).read)\n","old_contents":"require \"logstash\/namespace\"\n\n%%{\n machine logstash_config;\n\n action mark {\n @tokenstack.push(p)\n #puts \"Mark: #{self.line(string, p)}##{self.column(string, p)}\"\n }\n\n action stack_numeric {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"numeric: #{token}\"\n #puts \"numeric?: #{string[startpos,50]}\"\n #puts [startpos, endpos].join(\",\")\n # TODO(sissel): Don't do 'to_i' here. Type coersion is the job of the\n # plugin and the validator.\n @stack << token.to_i\n }\n\n action stack_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos ... endpos]\n #puts \"string: #{token}\"\n @stack << token\n }\n\n action stack_quoted_string {\n startpos = @tokenstack.pop\n endpos = p\n token = string[startpos + 1 ... endpos - 1] # Skip quotations\n\n # Parse escapes.\n token.gsub(\/\\\\.\/) { |m| m[1,1] }\n #puts \"quotedstring: #{token}\"\n @stack << token\n }\n\n action array_init {\n @array = []\n @stack << :array_init\n }\n\n action array_push {\n while @stack.last != :array_init\n @array.unshift @stack.pop\n end\n @stack.pop # pop :array_init\n\n @stack << @array\n }\n\n action parameter_init {\n # nothing\n }\n\n action parameter {\n value = @stack.pop\n name = @stack.pop\n #puts \"parameter: #{name} => #{value}\"\n if value.is_a?(Array)\n @parameters[name] += value\n else\n @parameters[name] << value\n end\n }\n\n action plugin {\n @components ||= []\n name = @stack.pop\n #@components << { :name => name, :parameters => @parameters }\n @components << { name => @parameters }\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action component_init {\n @components = []\n @parameters = Hash.new { |h,k| h[k] = [] }\n }\n\n action component {\n name = @stack.pop\n @config ||= Hash.new { |h,k| h[k] = [] }\n @config[name] += @components\n #puts \"Config component: #{name}\"\n }\n\n #%{ e = @tokenstack.pop; puts \"Comment: #{string[e ... p]}\" };\n comment = \"#\" (any - [\\n])* >mark ; \n ws = ([ \\t\\n] | comment)** ;\n #ws = ([ \\t\\n])** ;\n\n # TODO(sissel): Support floating point values?\n numeric = ( (\"+\" | \"-\")? [0-9] :>> [0-9]** ) >mark %stack_numeric;\n quoted_string = ( \n ( \"\\\"\" ( ( (any - [\\\\\"\\n]) | \"\\\\\" any )* ) \"\\\"\" )\n | ( \"'\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"'\" ) \n ) >mark %stack_quoted_string ;\n naked_string = ( [A-Za-z_] :>> [A-Za-z0-9_]* ) >mark %stack_string ;\n string = ( quoted_string | naked_string ) ;\n\n # TODO(sissel): allow use of this.\n regexp_literal = ( \"\/\" ( ( (any - [\\\\'\\n]) | \"\\\\\" any )* ) \"\/\" ) ;\n\n array = ( \"[\" ws ( string | numeric ) ws (\",\" ws (string | numeric ) ws)* \"]\" ) >array_init %array_push;\n parameter_value = ( numeric | string | array );\n parameter = ( string ws \"=>\" ws parameter_value ) %parameter ;\n parameters = ( parameter ( ws parameter )** ) >parameter_init ;\n\n # Statement:\n # component {\n # plugin_name {\n # bar => ...\n # baz => ...\n # }\n # ...\n # }\n\n plugin = (\n (\n naked_string ws \"{\" ws\n parameters\n ws \"}\"\n ) | ( \n naked_string ws \"{\" ws \"}\" \n )\n ) %plugin ; \n\n component = (\n naked_string ws \"{\"\n >component_init\n ( ws plugin )**\n ws \"}\"\n ) %component ;\n\n config = (ws component? )** ;\n\n main := config %{ puts \"END\" }\n $err { \n # Compute line and column of the cursor (p)\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n # TODO(sissel): Note what we were expecting?\n } ;\n}%%\n\nclass LogStash::Config::Grammar\n attr_accessor :eof\n attr_accessor :config\n\n def initialize\n # BEGIN RAGEL DATA\n %% write data;\n # END RAGEL DATA\n\n @tokenstack = Array.new\n @stack = Array.new\n\n @types = Hash.new { |h,k| h[k] = [] }\n @edges = []\n end\n\n def parse(string)\n # TODO(sissel): Due to a bug in my parser, we need one trailing whitespace\n # at the end of the string. I'll fix this later.\n string += \"\\n\"\n\n data = string.unpack(\"c*\")\n\n\n # BEGIN RAGEL INIT\n %% write init;\n # END RAGEL INIT\n\n begin \n # BEGIN RAGEL EXEC \n %% write exec;\n # END RAGEL EXEC\n rescue => e\n # Compute line and column of the cursor (p)\n raise e\n end\n\n if cs < self.logstash_config_first_final\n $stderr.puts \"Error at line #{self.line(string, p)}, column #{self.column(string, p)}: #{string[p .. -1].inspect}\"\n raise \"Invalid Configuration. Check syntax of config file.\"\n end\n return cs\n end # def parse\n\n def line(str, pos)\n return str[0 .. pos].count(\"\\n\") + 1\n end\n\n def column(str, pos)\n return str[0 .. pos].split(\"\\n\").last.length\n end\nend # class LogStash::Config::Grammar\n\n#def parse(string)\n #cfgparser = LogStash::Config::Grammar.new\n #result = cfgparser.parse(string)\n #puts \"result %s\" % result\n #ap cfgparser.config\n#end\n\n#parse(File.open(ARGV[0]).read)\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"6d91530c8d0e35b236afb2b4a573def300cf3913","subject":"missed one","message":"missed one\n\n\ngit-svn-id: 42af35d80111c0a63d26505f5f279a5822402eca@673 19e92222-5c0b-0410-8929-a290d50e31e9\n","repos":"puma\/puma,kyledrake\/puma,tuvistavie\/puma,nathansamson\/puma,digideskio\/puma,jc00ke\/puma,matthewd\/puma,spastorino\/puma,nathansamson\/puma,rkh\/puma,matthewd\/puma,unleashed\/puma,matthewd\/puma,jbmyid\/puma,unleashed\/puma,tuvistavie\/puma,spastorino\/puma,kyledrake\/puma,wallclockbuilder\/puma,zBMNForks\/puma,prathamesh-sonpatki\/puma,looker\/puma,unleashed\/puma,looker\/puma,costi\/puma,arturocadena\/puma,BenV\/puma,respire\/puma,tuvistavie\/puma,snow\/puma,ngpestelos\/puma,costi\/puma,costi\/puma,snow\/puma,eileencodes\/puma,eileencodes\/puma,respire\/puma,zapnap\/puma,zapnap\/puma,snow\/puma,prathamesh-sonpatki\/puma,BenV\/puma,snow\/puma,rkh\/puma,zBMNForks\/puma,prathamesh-sonpatki\/puma,arturocadena\/puma,puma\/puma,puma\/puma,jbmyid\/puma,rkh\/puma,jc00ke\/puma,respire\/puma,prathamesh-sonpatki\/puma,arturocadena\/puma,ngpestelos\/puma,puma\/puma,calavera\/puma,kyledrake\/puma,wallclockbuilder\/puma,digideskio\/puma,respire\/puma,nathansamson\/puma,matthewd\/puma,jc00ke\/puma,wallclockbuilder\/puma,calavera\/puma,nathansamson\/puma,zBMNForks\/puma,digideskio\/puma,rkh\/puma,arturocadena\/puma,jc00ke\/puma,unleashed\/puma,looker\/puma,spastorino\/puma,BenV\/puma,costi\/puma,tuvistavie\/puma,ngpestelos\/puma,jbmyid\/puma,calavera\/puma,zapnap\/puma,wallclockbuilder\/puma,digideskio\/puma,looker\/puma,eileencodes\/puma,calavera\/puma,zapnap\/puma,jbmyid\/puma,BenV\/puma,zBMNForks\/puma,eileencodes\/puma,kyledrake\/puma,ngpestelos\/puma","old_file":"ext\/http11_java\/http11_parser.rl","new_file":"ext\/http11_java\/http11_parser.rl","new_contents":"package org.jruby.mongrel;\n\nimport org.jruby.util.ByteList;\n\npublic class Http11Parser {\n \n\/** Machine **\/\n\n\/** Data **\/\n%% write data;\n\n public static interface ElementCB {\n public void call(Object data, int at, int length);\n }\n\n public static interface FieldCB {\n public void call(Object data, int field, int flen, int value, int vlen);\n }\n\n public static class HttpParser {\n int cs;\n int body_start;\n int content_len;\n int nread;\n int mark;\n int field_start;\n int field_len;\n int query_start;\n\n Object data;\n ByteList buffer;\n\n public FieldCB http_field;\n public ElementCB request_method;\n public ElementCB request_uri;\n public ElementCB request_path;\n public ElementCB query_string;\n public ElementCB http_version;\n public ElementCB header_done;\n\n public void init() {\n cs = 0;\n\n %% write init;\n\n body_start = 0;\n content_len = 0;\n mark = 0;\n nread = 0;\n field_len = 0;\n field_start = 0;\n }\n }\n\n public final HttpParser parser = new HttpParser();\n\n public int execute(ByteList buffer, int off) {\n int p, pe;\n int cs = parser.cs;\n int len = buffer.realSize;\n assert off<=len : \"offset past end of buffer\";\n\n p = off;\n pe = len;\n byte[] data = buffer.bytes;\n parser.buffer = buffer;\n\n %% write exec;\n\n parser.cs = cs;\n parser.nread += (p - off);\n \n assert p <= pe : \"buffer overflow after parsing execute\";\n assert parser.nread <= len : \"nread longer than length\";\n assert parser.body_start <= len : \"body starts after buffer end\";\n assert parser.mark < len : \"mark is after buffer end\";\n assert parser.field_len <= len : \"field has length longer than whole buffer\";\n assert parser.field_start < len : \"field starts after buffer end\";\n\n if(parser.body_start>0) {\n \/* final \\r\\n combo encountered so stop right here *\/\n %%write eof;\n parser.nread++;\n }\n\n return parser.nread;\n }\n\n public int finish() {\n int cs = parser.cs;\n\n %%write eof;\n\n parser.cs = cs;\n \n if(has_error()) {\n return -1;\n } else if(is_finished()) {\n return 1;\n } else {\n return 0;\n }\n }\n\n public boolean has_error() {\n return parser.cs == http_parser_error;\n }\n\n public boolean is_finished() {\n return parser.cs == http_parser_first_final;\n }\n}\n","old_contents":"package org.jruby.mongrel;\n\nimport org.jruby.util.ByteList;\n\npublic class Http11Parser {\n\n\/** machine **\/\n%%{\n machine http_parser;\n\n action mark {parser.mark = fpc; }\n\n action start_field { parser.field_start = fpc; }\n action write_field { \n parser.field_len = fpc-parser.field_start;\n }\n\n action start_value { parser.mark = fpc; }\n action write_value { \n if(parser.http_field != null) {\n parser.http_field.call(parser.data, parser.field_start, parser.field_len, parser.mark, fpc-parser.mark);\n }\n }\n action request_method { \n if(parser.request_method != null) \n parser.request_method.call(parser.data, parser.mark, fpc-parser.mark);\n }\n action request_uri { \n if(parser.request_uri != null)\n parser.request_uri.call(parser.data, parser.mark, fpc-parser.mark);\n }\n\n action start_query {parser.query_start = fpc; }\n action query_string { \n if(parser.query_string != null)\n parser.query_string.call(parser.data, parser.query_start, fpc-parser.query_start);\n }\n\n action http_version {\t\n if(parser.http_version != null)\n parser.http_version.call(parser.data, parser.mark, fpc-parser.mark);\n }\n\n action request_path {\n if(parser.request_path != null)\n parser.request_path.call(parser.data, parser.mark, fpc-parser.mark);\n }\n\n action done { \n parser.body_start = fpc + 1; \n if(parser.header_done != null)\n parser.header_done.call(parser.data, fpc + 1, pe - fpc - 1);\n fbreak;\n }\n\n\n#### HTTP PROTOCOL GRAMMAR\n# line endings\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n\n# URI schemes and absolute paths\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n\n path = (pchar+ ( \"\/\" pchar* )*) ;\n query = ( uchar | reserved )* %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = (param ( \";\" param )*) ;\n rel_path = (path? %request_path (\";\" params)?) (\"?\" %start_query query)?;\n absolute_path = (\"\/\"+ rel_path);\n\n Request_URI = (\"*\" | absolute_uri | absolute_path) >mark %request_uri;\n Method = (upper | digit | safe){1,20} >mark %request_method;\n\n http_number = (digit+ \".\" digit+) ;\n HTTP_Version = (\"HTTP\/\" http_number) >mark %http_version ;\n Request_Line = (Method \" \" Request_URI \" \" HTTP_Version CRLF) ;\n\n field_name = (token -- \":\")+ >start_field %write_field;\n\n field_value = any* >start_value %write_value;\n\n message_header = field_name \":\" \" \"* field_value :> CRLF;\n\n Request = Request_Line (message_header)* ( CRLF @done);\n\nmain := Request;\n}%%\n\n\/** Data **\/\n%% write data;\n\n public static interface ElementCB {\n public void call(Object data, int at, int length);\n }\n\n public static interface FieldCB {\n public void call(Object data, int field, int flen, int value, int vlen);\n }\n\n public static class HttpParser {\n int cs;\n int body_start;\n int content_len;\n int nread;\n int mark;\n int field_start;\n int field_len;\n int query_start;\n\n Object data;\n ByteList buffer;\n\n public FieldCB http_field;\n public ElementCB request_method;\n public ElementCB request_uri;\n public ElementCB request_path;\n public ElementCB query_string;\n public ElementCB http_version;\n public ElementCB header_done;\n\n public void init() {\n cs = 0;\n\n %% write init;\n\n body_start = 0;\n content_len = 0;\n mark = 0;\n nread = 0;\n field_len = 0;\n field_start = 0;\n }\n }\n\n public final HttpParser parser = new HttpParser();\n\n public int execute(ByteList buffer, int off) {\n int p, pe;\n int cs = parser.cs;\n int len = buffer.realSize;\n assert off<=len : \"offset past end of buffer\";\n\n p = off;\n pe = len;\n byte[] data = buffer.bytes;\n parser.buffer = buffer;\n\n %% write exec;\n\n parser.cs = cs;\n parser.nread += (p - off);\n \n assert p <= pe : \"buffer overflow after parsing execute\";\n assert parser.nread <= len : \"nread longer than length\";\n assert parser.body_start <= len : \"body starts after buffer end\";\n assert parser.mark < len : \"mark is after buffer end\";\n assert parser.field_len <= len : \"field has length longer than whole buffer\";\n assert parser.field_start < len : \"field starts after buffer end\";\n\n if(parser.body_start>0) {\n \/* final \\r\\n combo encountered so stop right here *\/\n %%write eof;\n parser.nread++;\n }\n\n return parser.nread;\n }\n\n public int finish() {\n int cs = parser.cs;\n\n %%write eof;\n\n parser.cs = cs;\n \n if(has_error()) {\n return -1;\n } else if(is_finished()) {\n return 1;\n } else {\n return 0;\n }\n }\n\n public boolean has_error() {\n return parser.cs == http_parser_error;\n }\n\n public boolean is_finished() {\n return parser.cs == http_parser_first_final;\n }\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"c2070c4fc06df2c2b9709c86cca0acd400e80839","subject":"SSA: Add missing VSFilter 2.39 tags to the parser.","message":"SSA: Add missing VSFilter 2.39 tags to the parser.\n\nFixes some wrong font sizes in [BSS]_Darker_Than_Black_-_Gemini_of_the_Meteor_-_04_[8767FC3C].mkv.\nThese were caused by the parser skipping command blocks with unknown tags.\nMaybe it just shouldn't do that?\n\n","repos":"MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian","old_file":"Subtitles\/SubParsing.m.rl","new_file":"Subtitles\/SubParsing.m.rl","new_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = STUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = STUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" floatnum %bluredge\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fax\" floatnum\n\t\t\t\t\t\t\t|\"fay\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum %frx\n\t\t\t\t\t\t\t|\"fry\" floatnum %fry\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"i\"? \"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t\t\t|\"xbord\" floatnum\n\t\t\t\t\t\t\t|\"ybord\" floatnum\n\t\t\t\t\t\t\t|\"xshad\" floatnum\n\t\t\t\t\t\t\t|\"yshad\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","old_contents":"\/*\n * SubParsing.m.rl\n * Created by Alexander Strange on 7\/25\/07.\n *\n * This file is part of Perian.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#import \"SubParsing.h\"\n#import \"SubUtilities.h\"\n#import \"SubContext.h\"\n#import \"Codecprintf.h\"\n\n%%machine SSAfile;\n%%write data;\n\n@implementation SubRenderSpan\n+(SubRenderSpan*)startingSpanForDiv:(SubRenderDiv*)div delegate:(SubRenderer*)delegate\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = 0;\n\tspan->ex = [delegate spanExtraFromRenderDiv:div];\n\tspan->delegate = delegate;\n\treturn [span autorelease];\n}\n\n-(SubRenderSpan*)cloneWithDelegate:(SubRenderer*)delegate_\n{\n\tSubRenderSpan *span = [[SubRenderSpan alloc] init];\n\tspan->offset = offset;\n\tspan->ex = [delegate_ cloneSpanExtra:self];\n\tspan->delegate = delegate_;\n\treturn [span autorelease];\n}\n\n-(void)dealloc\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super dealloc];\n}\n\n-(void)finalize\n{\n\t[delegate releaseSpanExtra:ex];\n\t[super finalize];\n}\n\n-(NSString*)description\n{\n\treturn [NSString stringWithFormat:@\"Span at %d: %@\", offset, [delegate describeSpanEx:ex]];\n}\n@end\n\n@implementation SubRenderDiv\n-(NSString*)description\n{\n\tint i, sc = [spans count];\n\tNSMutableString *tmp = [NSMutableString stringWithFormat:@\"div \\\"%@\\\" with %d spans:\", text, sc];\n\tfor (i = 0; i < sc; i++) {[tmp appendFormat:@\" %d\",((SubRenderSpan*)[spans objectAtIndex:i])->offset];}\n\t[tmp appendFormat:@\" %d\", [text length]];\n\treturn tmp;\n}\n\n-(SubRenderDiv*)init\n{\n\tif (self = [super init]) {\n\t\ttext = nil;\n\t\tstyleLine = nil;\n\t\tmarginL = marginR = marginV = layer = 0;\n\t\tspans = nil;\n\t\t\n\t\tposX = posY = 0;\n\t\talignH = kSubAlignmentMiddle; alignV = kSubAlignmentBottom;\n\t\t\n\t\tpositioned = NO;\n\t\trender_complexity = 0;\n\t}\n\t\n\treturn self;\n}\n\n-(SubRenderDiv*)nextDivWithDelegate:(SubRenderer*)delegate\n{\n\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\n\tdiv->text = [[NSMutableString string] retain];\n div->styleLine = [styleLine retain];\n\tdiv->marginL = marginL;\n\tdiv->marginR = marginR;\n\tdiv->marginV = marginV;\n\tdiv->layer = layer;\n\t\n\tdiv->spans = [[NSMutableArray arrayWithObject:[[spans objectAtIndex:[spans count]-1] cloneWithDelegate:delegate]] retain];\n\t\n\tdiv->posX = posX;\n\tdiv->posY = posY;\n\tdiv->alignH = alignH;\n\tdiv->alignV = alignV;\n div->wrapStyle = wrapStyle;\n \n\tdiv->positioned = positioned;\n\tdiv->render_complexity = render_complexity;\n\t\n\treturn div;\n}\n\n-(void)dealloc\n{\n\t[text release];\n\t[styleLine release];\n\t[spans release];\n\t[super dealloc];\n}\n@end\n\nextern BOOL IsScriptASS(NSDictionary *headers);\n\nstatic NSArray *SplitByFormat(NSString *format, NSArray *lines)\n{\n\tNSArray *formarray = STSplitStringIgnoringWhitespace(format,@\",\");\n\tint i, numlines = [lines count], numfields = [formarray count];\n\tNSMutableArray *ar = [NSMutableArray arrayWithCapacity:numlines];\n\t\n\tfor (i = 0; i < numlines; i++) {\n\t\tNSString *s = [lines objectAtIndex:i];\n\t\tNSArray *splitline = STSplitStringWithCount(s, @\",\", numfields);\n\t\t\n\t\tif ([splitline count] != numfields) continue;\n\t\t[ar addObject:[NSDictionary dictionaryWithObjects:splitline\n\t\t\t\t\t\t\t\t\t\t\t\t forKeys:formarray]];\n\t}\n\t\n\treturn ar;\n}\n\nvoid SubParseSSAFile(NSString *ssastr, NSDictionary **headers, NSArray **styles, NSArray **subs)\n{\n\tunsigned len = [ssastr length];\n\tNSData *ssaData;\n\tconst unichar *ssa = STUnicodeForString(ssastr, &ssaData);\n\tNSMutableDictionary *hd = [NSMutableDictionary dictionary];\n\tNSMutableArray *stylearr = [NSMutableArray array], *eventarr = [NSMutableArray array], *cur_array=NULL;\n\tNSCharacterSet *wcs = [NSCharacterSet whitespaceCharacterSet];\n\tNSString *str=NULL, *styleformat=NULL, *eventformat=NULL;\n\t\n\tconst unichar *p = ssa, *pe = ssa + len, *strbegin = p;\n\tint cs=0;\n\t\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)strbegin length:p-strbegin freeWhenDone:NO] autorelease]\n\t\n\t%%{\n\t\talphtype unsigned short;\n\t\t\n\t\taction sstart {strbegin = p;}\n\t\taction setheaderval {[hd setObject:send() forKey:str];}\n\t\taction savestr {str = send();}\n\t\taction csvlineend {[cur_array addObject:[send() stringByTrimmingCharactersInSet:wcs]];}\n\t\taction setupevents {\n\t\t\tcur_array=eventarr;\n\t\t\teventformat = IsScriptASS(hd) ?\n\t\t\t\t@\"Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\":\n\t\t\t\t@\"Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\";\n\t\t}\n\t\t\t\t\n\t\tnl = (\"\\n\" | \"\\r\" | \"\\r\\n\");\n\t\tstr = any*;\n\t\tws = space | 0xa0;\n\t\tbom = 0xfeff;\n\t\t\n\t\thline = ((\";\" str) | (([^;] str) >sstart %savestr :> (\":\" ws* str >sstart %setheaderval)?))? :> nl;\n\t\t\n\t\theader = \"[Script Info]\" nl hline*;\n\t\t\t\t\n\t\tformat = \"Format:\" ws* %sstart str %savestr :> nl;\n\t\t\t\t\n\t\taction assformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\";}\n\t\taction ssaformat {styleformat = @\"Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding\";}\n\n\t\tstylename = (\"[\" [Vv] \"4 Styles]\") %ssaformat | (\"[\" [Vv] \"4+ Styles]\") %assformat;\n\t\t\n\t\tsline = ((\"Style:\" ws* %sstart str %csvlineend) | str) :> nl;\n\t\t\n\t\tstyles = stylename % {cur_array=stylearr;} nl :> (format %{styleformat=str;})? <: (sline*);\n\t\t\n\t\tevent_txt = ((\"Dialogue:\" ws* %sstart str %csvlineend %\/csvlineend) | str);\n\t\tevent = event_txt :> nl;\n\t\t\t\n\t\tlines = \"[Events]\" %setupevents nl :> (format %{eventformat=str;})? <: (event*);\n\t\t\n\t\tmain := bom? header styles lines?;\n\t}%%\n\t\t\n\t%%write init;\n\t%%write exec;\n\t%%write eof;\n\n\t[ssaData release];\n\n\t*headers = hd;\n\tif (styles) *styles = SplitByFormat(styleformat, stylearr);\n\tif (subs) *subs = SplitByFormat(eventformat, eventarr);\n}\n\n%%machine SSAtag;\n%%write data;\n\nstatic int compare_layer(const void *a, const void *b)\n{\n\tconst SubRenderDiv *divA = *(id*)a, *divB = *(id*)b;\n\n\tif (divA->layer < divB->layer) return -1;\n\telse if (divA->layer > divB->layer) return 1;\n\treturn 0;\n}\n\nNSArray *SubParsePacket(NSString *packet, SubContext *context, SubRenderer *delegate)\n{\n\tpacket = STStandardizeStringNewlines(packet);\n\tNSArray *lines = (context->scriptType == kSubTypeSRT) ? [NSArray arrayWithObject:[packet substringToIndex:[packet length]-1]] : [packet componentsSeparatedByString:@\"\\n\"];\n\tsize_t line_count = [lines count];\n\tNSMutableArray *divs = [NSMutableArray arrayWithCapacity:line_count];\n\tint i;\n\t\n\tfor (i = 0; i < line_count; i++) {\n\t\tNSString *inputText = [lines objectAtIndex:(context->collisions == kSubCollisionsReverse) ? (line_count - i - 1) : i];\n\t\tSubRenderDiv *div = [[[SubRenderDiv alloc] init] autorelease];\n\t\t\n\t\tdiv->text = [[NSMutableString string] retain];\n\t\tdiv->spans = [[NSMutableArray array] retain];\n\t\t\n\t\tif (context->scriptType == kSubTypeSRT) {\n\t\t\tdiv->styleLine = [context->defaultStyle retain];\n\t\t\tdiv->marginL = div->styleLine->marginL;\n\t\t\tdiv->marginR = div->styleLine->marginR;\n\t\t\tdiv->marginV = div->styleLine->marginV;\n\t\t\tdiv->layer = 0;\n\t\t\tdiv->wrapStyle = kSubLineWrapTopWider;\n\t\t} else {\n\t\t\tNSArray *fields = STSplitStringWithCount(inputText, @\",\", 9);\n\t\t\tif ([fields count] < 9) continue;\n\t\t\tdiv->layer = [[fields objectAtIndex:1] intValue];\n\t\t\tdiv->styleLine = [[context styleForName:[fields objectAtIndex:2]] retain];\n\t\t\tdiv->marginL = [[fields objectAtIndex:4] intValue];\n\t\t\tdiv->marginR = [[fields objectAtIndex:5] intValue];\n\t\t\tdiv->marginV = [[fields objectAtIndex:6] intValue];\n\t\t\tinputText = [fields objectAtIndex:8];\n\t\t\tif ([inputText length] == 0) continue;\n\t\t\t\n\t\t\tif (div->marginL == 0) div->marginL = div->styleLine->marginL;\n\t\t\tif (div->marginR == 0) div->marginR = div->styleLine->marginR;\n\t\t\tif (div->marginV == 0) div->marginV = div->styleLine->marginV;\n\t\t\t\n\t\t\tdiv->wrapStyle = context->wrapStyle;\n\t\t}\n\t\t\n\t\tdiv->alignH = div->styleLine->alignH;\n\t\tdiv->alignV = div->styleLine->alignV;\n\t\t\n#undef send\n#define send() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)outputbegin length:p-outputbegin freeWhenDone:NO] autorelease]\n#define psend() [[[NSString alloc] initWithCharactersNoCopy:(unichar*)parambegin length:p-parambegin freeWhenDone:NO] autorelease]\n#define tag(tagt, p) [delegate spanChangedTag:tag_##tagt span:current_span div:div param:&(p)]\n\t\t\t\t\n\t\t{\n\t\t\tsize_t linelen = [inputText length];\n\t\t\tNSData *linebufData;\n\t\t\tconst unichar *linebuf = STUnicodeForString(inputText, &linebufData);\n\t\t\tconst unichar *p = linebuf, *pe = linebuf + linelen, *outputbegin = p, *parambegin=p, *last_tag_start=p;\n\t\t\tconst unichar *pb = p;\n\t\t\tint cs = 0;\n\t\t\tSubRenderSpan *current_span = [SubRenderSpan startingSpanForDiv:div delegate:delegate];\n\t\t\tunsigned chars_deleted = 0; float floatnum = 0;\n\t\t\tNSString *strval=NULL;\n\t\t\tfloat curX, curY;\n\t\t\tint intnum = 0;\n\t\t\tBOOL reachedEnd = NO, setWrapStyle = NO, setPosition = NO, setAlignForDiv = NO, dropThisSpan = NO;\n\t\t\t\n\t\t\t%%{\n\t\t\t\taction bold {tag(b, intnum);}\n\t\t\t\taction italic {tag(i, intnum);}\n\t\t\t\taction underline {tag(u, intnum);}\n\t\t\t\taction strikeout {tag(s, intnum);}\n\t\t\t\taction outlinesize {tag(bord, floatnum);}\n\t\t\t\taction shadowdist {tag(shad, floatnum);}\n\t\t\t\taction bluredge {tag(be, intnum);}\n\t\t\t\taction fontname {tag(fn, strval);}\n\t\t\t\taction fontsize {tag(fs, floatnum);}\n\t\t\t\taction scalex {tag(fscx, floatnum);}\n\t\t\t\taction scaley {tag(fscy, floatnum);}\n\t\t\t\taction tracking {tag(fsp, floatnum);}\n\t\t\t\taction frz {tag(frz, floatnum);}\n\t\t\t\taction frx {tag(frx, floatnum);}\n\t\t\t\taction fry {tag(fry, floatnum);}\n\t\t\t\taction primaryc {tag(1c, intnum);}\n\t\t\t\taction secondaryc {tag(2c, intnum);}\n\t\t\t\taction outlinec {tag(3c, intnum);}\n\t\t\t\taction shadowc {tag(4c, intnum);}\n\t\t\t\taction alpha {tag(alpha, intnum);}\n\t\t\t\taction primarya {tag(1a, intnum);}\n\t\t\t\taction secondarya {tag(2a, intnum);}\n\t\t\t\taction outlinea {tag(3a, intnum);}\n\t\t\t\taction shadowa {tag(4a, intnum);}\n\t\t\t\taction stylerevert {tag(r, strval);}\n\t\t\t\taction drawingmode {tag(p, floatnum); dropThisSpan = floatnum > 0;}\n\n\t\t\t\taction paramset {parambegin=p;}\n\t\t\t\taction setintnum {intnum = [psend() intValue];}\n\t\t\t\taction sethexnum {intnum = strtoul([psend() UTF8String], NULL, 16);}\n\t\t\t\taction setfloatnum {floatnum = [psend() floatValue];}\n\t\t\t\taction setstringval {strval = psend();}\n\t\t\t\taction nullstring {strval = @\"\";}\n\t\t\t\taction setpos {curX=curY=0; sscanf([psend() UTF8String], \"(%f,%f\", &curX, &curY);}\n\n\t\t\t\taction ssaalign {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(SSA2ASSAlignment(intnum), &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction align {\n\t\t\t\t\tif (!setAlignForDiv) {\n\t\t\t\t\t\tsetAlignForDiv = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tParseASSAlignment(intnum, &div->alignH, &div->alignV);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction wrapstyle {\n\t\t\t\t\tif (!setWrapStyle) {\n\t\t\t\t\t\tsetWrapStyle = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->wrapStyle = intnum;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction position {\n\t\t\t\t\tif (!setPosition) {\n\t\t\t\t\t\tsetPosition = YES;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiv->posX = curX;\n\t\t\t\t\t\tdiv->posY = curY;\n\t\t\t\t\t\tdiv->positioned = YES;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction origin {\n\t\t\t\t\tdiv->shouldResetPens = YES;\n\t\t\t\t}\n\n\t\t\t\tintnum = (\"-\"? [0-9]+) >paramset %setintnum;\n\t\t\t\tflag = [01] >paramset %setintnum;\n\t\t\t\tfloatn = (\"-\"? ([0-9]+ (\".\" [0-9]*)?) | ([0-9]* \".\" [0-9]+));\n\t\t\t\tfloatnum = floatn >paramset %setfloatnum;\n\t\t\t\tstring = (([^\\\\}]+) >paramset %setstringval | \"\" %nullstring );\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) >paramset %sethexnum \"&\"?;\n\t\t\t\tparens = \"(\" [^)]* \")\";\n\t\t\t\tpos = (\"(\" floatn \",\" floatn \")\") >paramset %setpos;\n\t\t\t\tmove = (\"(\" (floatn \",\"){3,5} floatn \")\") >paramset %setpos;\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" (\n\t\t\t\t\t\t\t\"b\" intnum %bold\n\t\t\t\t\t\t\t|\"i\" flag %italic\n\t\t\t\t\t\t\t|\"u\" flag %underline\n\t\t\t\t\t\t\t|\"s\" flag %strikeout\n\t\t\t\t\t\t\t|\"bord\" floatnum %outlinesize\n\t\t\t\t\t\t\t|\"shad\" floatnum %shadowdist\n\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t|\"blur\" floatnum\n\t\t\t\t\t\t\t|\"fn\" string %fontname\n\t\t\t\t\t\t\t|\"fs\" floatnum %fontsize\n\t\t\t\t\t\t\t|\"fscx\" floatnum %scalex\n\t\t\t\t\t\t\t|\"fscy\" floatnum %scaley\n\t\t\t\t\t\t\t|\"fsp\" floatnum %tracking\n\t\t\t\t\t\t\t|(\"fr\" \"z\"? floatnum %frz)\n\t\t\t\t\t\t\t|\"frx\" floatnum %frx\n\t\t\t\t\t\t\t|\"fry\" floatnum %fry\n\t\t\t\t\t\t\t|\"fe\" intnum\n\t\t\t\t\t\t\t|(\"1\"? \"c\" color %primaryc)\n\t\t\t\t\t\t\t|\"2c\" color %secondaryc\n\t\t\t\t\t\t\t|\"3c\" color %outlinec\n\t\t\t\t\t\t\t|\"4c\" color %shadowc\n\t\t\t\t\t\t\t|\"alpha\" color %alpha\n\t\t\t\t\t\t\t|\"1a\" color %primarya\n\t\t\t\t\t\t\t|\"2a\" color %secondarya\n\t\t\t\t\t\t\t|\"3a\" color %outlinea\n\t\t\t\t\t\t\t|\"4a\" color %shadowa\n\t\t\t\t\t\t\t|\"a\" intnum %ssaalign\n\t\t\t\t\t\t\t|\"an\" intnum %align\n\t\t\t\t\t\t\t|([kK] [fo]? intnum)\n\t\t\t\t\t\t\t|\"q\" intnum %wrapstyle\n\t\t\t\t\t\t\t|\"r\" string %stylerevert\n\t\t\t\t\t\t\t|\"pos\" pos %position\n\t\t\t\t\t\t\t|\"move\" move %position\n\t\t\t\t\t\t\t|\"t\" parens\n\t\t\t\t\t\t\t|\"org\" parens %origin\n\t\t\t\t\t\t\t|(\"fad\" \"e\"? parens)\n\t\t\t\t\t\t\t|\"clip\" parens\n\t\t\t\t\t\t\t|\"p\" floatnum %drawingmode\n\t\t\t\t\t\t\t|\"pbo\" floatnum\n\t\t\t\t\t );\n\t\t\t\t\n\t\t\t\ttag = \"{\" (cmd* | any*) :> \"}\";\n\n\t\t\t\taction backslash_handler {\n\t\t\t\t\tp--;\n\t\t\t\t\t[div->text appendString:send()];\n\t\t\t\t\tunichar c = *(p+1), o=c;\n\t\t\t\t\t\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\tswitch (c) {\n\t\t\t\t\t\t\tcase 'N': case 'n':\n\t\t\t\t\t\t\t\to = '\\n';\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\to = 0xA0; \/\/non-breaking space\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t[div->text appendFormat:@\"%C\",o];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchars_deleted++;\n\t\t\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\toutputbegin = p+1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tif (dropThisSpan) chars_deleted += p - outputbegin;\n\t\t\t\t\telse if (p > outputbegin) [div->text appendString:send()];\n\t\t\t\t\tif (p == pe) reachedEnd = YES;\n\t\t\t\t\t\n\t\t\t\t\tif (p != pb) {\n\t\t\t\t\t\t[div->spans addObject:current_span];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!reachedEnd) current_span = [current_span cloneWithDelegate:delegate];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlast_tag_start = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\t\t\t\n\t\t\t\t\tp++;\n\t\t\t\t\tchars_deleted += (p - last_tag_start);\n\t\t\t\t\t\n\t\t\t\t\tcurrent_span->offset = (p - pb) - chars_deleted;\n\t\t\t\t\toutputbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tspecial = (\"\\\\\" :> any) @backslash_handler | tag >enter_tag @exit_tag;\n\t\t\t\tsub_text_char = [^\\\\{];\n\t\t\t\tsub_text = sub_text_char+;\n\t\t\t\t\n\t\t\t\tmain := ((sub_text | special)* \"\\\\\"?) %\/enter_tag;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\n\t\t\tif (!reachedEnd) Codecprintf(NULL, \"parse error: %s\\n\", [inputText UTF8String]);\n\t\t\tif (linebuf[linelen-1] == '\\\\') [div->text appendString:@\"\\\\\"];\n\t\t\t[linebufData release];\n\t\t\t[divs addObject:div];\n\t\t}\n\t\t\n\t}\n\t\n\tSTSortMutableArrayStably(divs, compare_layer);\n\treturn divs;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"dddc7a8f79c1cc239a056f9b7ad5524ec1d4a1eb","subject":"fix ifNoneMatch typo in http parser","message":"fix ifNoneMatch typo in http parser\n","repos":"mtanski\/mordor,mtanski\/mordor,ccutrer\/mordor,cgaebel\/mordor,adfin\/mordor,mozy\/mordor,adfin\/mordor,mtanski\/mordor,adfin\/mordor,ccutrer\/mordor,ccutrer\/mordor,cgaebel\/mordor,mozy\/mordor,mozy\/mordor","old_file":"mordor\/common\/http\/parser.rl","new_file":"mordor\/common\/http\/parser.rl","new_contents":"\/\/ Copyright (c) 2009 - Decho Corp.\n\n#include \"mordor\/common\/pch.h\"\n\n#include \"mordor\/common\/http\/parser.h\"\n\n#include \n#include \n#include \n\n#include \"mordor\/common\/version.h\"\n\n\/\/ From uri.rl\nstd::string unescape(const std::string& str, bool spaceAsPlus = false);\n\nstatic\nHTTP::Version\nparseVersion(const char *str)\n{\n HTTP::Version ver;\n ver.major = atoi(str + 5);\n ver.minor = atoi(strchr(str + 5, '.') + 1);\n return ver;\n}\n\nstatic\nHTTP::Method\nparseMethod(const char *str, const char *end)\n{\n for(size_t i = 0; i < 8; ++i) {\n if (strnicmp(str, HTTP::methods[i], end - str) == 0) {\n return (HTTP::Method)i;\n }\n }\n throw std::invalid_argument(\"Unrecognized method\");\n}\n\nstatic boost::posix_time::time_input_facet rfc1123Facet_in(\"%a, %d %b %Y %H:%M:%S GMT\",\n 1 \/* starting refcount, so this never gets deleted *\/);\nstatic boost::posix_time::time_input_facet rfc850Facet_in(\"%A, %d-%b-%y %H:%M:%S GMT\",\n 1 \/* starting refcount, so this never gets deleted *\/);\nstatic boost::posix_time::time_input_facet ansiFacet_in(\"%a %b %e %H:%M:%S %Y\",\n 1 \/* starting refcount, so this never gets deleted *\/);\n\nstatic\nboost::posix_time::ptime\nparseHttpDate(const char *str, size_t size)\n{\n boost::posix_time::ptime result;\n std::string val(str, size);\n \n #define ATTEMPT_WITH_FACET(facet) \\\n { \\\n std::istringstream is(val); \\\n is.imbue(std::locale(is.getloc(), facet)); \\\n is >> result; \\\n if (!result.is_not_a_date_time()) \\\n return result; \\\n }\n\n ATTEMPT_WITH_FACET(&rfc1123Facet_in);\n ATTEMPT_WITH_FACET(&rfc850Facet_in);\n ATTEMPT_WITH_FACET(&ansiFacet_in);\n NOTREACHED();\n}\n\nstatic\nstd::string\nunfold(char *p, char *pe)\n{\n char *start = p;\n char *pw = p;\n\n while (p < pe) {\n \/\/ Skip leading whitespace\n if (pw == start) {\n if (*p == ' ' || *p == '\\t' || *p == '\\r' || *p == '\\n') {\n ++p; ++pw; ++start;\n continue;\n }\n }\n \/\/ Only copy if necessary\n if (pw != p) {\n *pw = *p;\n }\n ++p; ++pw;\n }\n \/\/ Remove trailing whitespace\n do {\n --pw;\n } while ((*pw == ' ' || *pw == '\\t' || *pw == '\\r' || *pw == '\\n') && pw >= start);\n ++pw;\n return std::string(start, pw - start);\n}\n\nstd::string\nHTTP::unquote(const char *str, size_t size)\n{\n if (size == 0 || (str[0] != '\"' && str[0] != '('))\n return std::string(str, size);\n ASSERT((str[size - 1] == '\"' && str[0] == '\"') ||\n (str[size - 1] == ')' && str[0] == '('));\n std::string result(str + 1, size - 2);\n char *p = const_cast(result.c_str());\n char *pe = p + result.size();\n char *pw = p;\n\n bool escaping = false;\n while (p < pe) {\n if (escaping) {\n escaping = false;\n } else if (*p == '\\\\') {\n escaping = true;\n ++p;\n continue;\n }\n \/\/ Only copy if necessary\n if (pw != p)\n *pw = *p;\n ++p; ++pw;\n }\n result.resize(pw - result.c_str());\n return result;\n}\n\nstd::string\nHTTP::unquote(const std::string &str)\n{\n if (str.empty() || (str[0] != '\"' && str[0] != '('))\n return str;\n return unquote(str.c_str(), str.size());\n}\n\n%%{\n machine http_parser;\n \n # See RFC 2616: http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616.html\n\n action mark { mark = fpc; }\n action done { fbreak; }\n\n # basic character types\n OCTET = any;\n CHAR = ascii;\n UPALPHA = \"A\"..\"Z\";\n LOALPHA = \"a\"..\"z\";\n ALPHA = alpha;\n DIGIT = digit;\n CTL = cntrl | 127;\n CR = \"\\r\";\n LF = \"\\n\";\n SP = \" \";\n HT = \"\\t\";\n\n # almost-basic character types\n # note that we allow a single LF for a CR LF\n CRLF = CR LF;\n LWS = CRLF? ( SP | HT )+;\n TEXT = LWS | (OCTET -- CTL);\n HEX = xdigit;\n\n # some basic tokens\n separators = \"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | SP | HT;\n token = (CHAR -- (separators | CTL))+;\n quoted_pair = \"\\\\\" CHAR;\n ctext = TEXT -- (\"(\" | \")\");\n # TODO: truly nested comments\n base_comment = \"(\" ( ctext | quoted_pair )* \")\";\n comment = \"(\" ( ctext | quoted_pair | base_comment )* \")\";\n qdtext = TEXT -- \"\\\"\";\n quoted_string = \"\\\"\" ( qdtext | quoted_pair )* \"\\\"\";\n \n base64char = ALPHA | DIGIT | '+' | '\/';\n base64 = (base64char{4})+ ( (base64char{3} '=') | (base64char{2} '==') )?;\n\n action parse_HTTP_Version {\n ASSERT(m_ver);\n *m_ver = parseVersion(mark);\n mark = NULL;\n }\n\n HTTP_Version = (\"HTTP\/\" DIGIT+ \".\" DIGIT+) >mark %parse_HTTP_Version;\n\n action save_date {\n ASSERT(m_date);\n *m_date = parseHttpDate(mark, fpc - mark);\n mark = NULL; \n }\n\n wkday = \"Mon\" | \"Tue\" | \"Wed\" | \"Thu\" | \"Fri\" | \"Sat\" | \"Sun\";\n weekday = \"Monday\" | \"Tuesday\" | \"Wednesday\" | \"Thursday\" | \"Friday\" | \"Saturday\" | \"Sunday\";\n month = \"Jan\" | \"Feb\" | \"Mar\" | \"Apr\" | \"May\" | \"Jun\" | \"Jul\" | \"Aug\" | \"Sep\" | \"Oct\" | \"Nov\" | \"Dec\";\n date1 = DIGIT{2} SP month SP DIGIT{4};\n date2 = DIGIT{2} \"-\" month \"-\" DIGIT{2};\n date3 = month SP ( DIGIT{2} | (SP DIGIT));\n time = DIGIT{2} \":\" DIGIT{2} \":\" DIGIT{2};\n rfc1123_date = wkday \",\" SP date1 SP time SP \"GMT\";\n rfc850_date = weekday \",\" SP date2 SP time SP \"GMT\";\n asctime_date = wkday SP date3 SP time SP DIGIT{4};\n HTTP_date = (rfc1123_date | rfc850_date | asctime_date) >mark %save_date;\n \n delta_seconds = DIGIT+;\n\n action save_product_name {\n m_product.product = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_product_version {\n m_product.version = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_product {\n ASSERT(m_productAndCommentList);\n m_productAndCommentList->push_back(m_product);\n m_product = Product();\n }\n action save_comment {\n\t\tASSERT(m_productAndCommentList);\n m_productAndCommentList->push_back(HTTP::unquote(mark, fpc - mark));\n mark = NULL;\n }\n\n product_version = token;\n product = token >mark %save_product_name (\"\/\" product_version >mark %save_product_version)?;\n product_or_comment = (product %save_product) | (comment >mark %save_comment);\n product_and_comment_list = LWS* product_or_comment ( LWS+ product_or_comment)* LWS*;\n\n qvalue = ('0' ('.' DIGIT{0,3})?) | ('1' ('.' '0'{0,3})?);\n\n subtag = ALPHA{1,8};\n primary_tag = ALPHA{1,8};\n language_tag = primary_tag (\"-\" subtag);\n\n action start_etag {\n ASSERT(m_eTag);\n m_eTag->weak = false;\n }\n action save_weak {\n ASSERT(m_eTag);\n m_eTag->unspecified = false;\n m_eTag->weak = true;\n }\n action save_etag {\n ASSERT(m_eTag);\n m_eTag->unspecified = false;\n m_eTag->value = unquote(mark, fpc - mark);\n }\n action set_etag_list {\n m_eTag = &m_tempETag;\n }\n action save_unspecified {\n ASSERT(m_eTagSet);\n m_eTagSet->insert(ETag());\n }\n action save_etag_element {\n ASSERT(m_eTagSet);\n ASSERT(m_eTag == & m_tempETag);\n m_eTagSet->insert(m_tempETag);\n }\n \n weak = \"W\/\" %save_weak;\n opaque_tag = quoted_string >mark %save_etag;\n entity_tag = ((weak)? opaque_tag) >start_etag;\n\n etag_list = LWS* (\"*\" % save_unspecified | (LWS* entity_tag %save_etag_element ( LWS* ',' LWS* entity_tag %save_etag_element)* LWS*) LWS* ) > set_etag_list;\n\n bytes_unit = \"bytes\";\n other_range_unit = token;\n range_unit = bytes_unit | other_range_unit;\n\n action save_field_name {\n m_temp1 = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_field_value {\n std::string fieldValue = unfold((char*)mark, (char*)fpc);\n \n StringMap::iterator it = m_entity->extension.find(m_temp1);\n if (it == m_entity->extension.end()) {\n m_entity->extension[m_temp1] = fieldValue;\n } else {\n it->second.append(\", \");\n it->second.append(fieldValue);\n }\n mark = NULL;\n }\n\n field_chars = OCTET -- (CTL | CR LF SP HT);\n field_name = token >mark %save_field_name;\n field_value = TEXT* >mark %save_field_value;\n message_header = field_name \":\" field_value;\n \n action save_string {\n *m_string = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_ulong {\n *m_ulong = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n \n action save_element {\n ASSERT(m_list || m_set);\n if (m_list)\n m_list->push_back(std::string(mark, fpc - mark));\n else\n m_set->insert(std::string(mark, fpc - mark));\n mark = NULL;\n }\n element = token >mark %save_element;\n list = (LWS* element ( LWS* ',' LWS* element)* LWS*);\n \n action save_parameterized_list_element {\n ValueWithParameters vp;\n vp.value = std::string(mark, fpc - mark);\n m_parameterizedList->push_back(vp);\n m_parameters = &m_parameterizedList->back().parameters;\n mark = NULL;\n }\n \n action save_parameter_attribute {\n m_temp1 = std::string(mark, fpc - mark);\n \/\/ Don't NULL out here; could be base64 later\n }\n \n action save_parameter_value {\n (*m_parameters)[m_temp1] = unquote(mark, fpc - mark);\n mark = NULL;\n }\n\n attribute = (token - 'q'i) >mark %save_parameter_attribute; # q separates params from accept-params\n value = (token | quoted_string) >mark %save_parameter_value;\n parameter = attribute '=' value;\n parameterizedListElement = token >mark %save_parameterized_list_element (';' parameter)*;\n parameterizedList = LWS* parameterizedListElement ( LWS* ',' LWS* parameterizedListElement)* LWS*;\n \n action save_auth_scheme {\n if (m_challengeList && ((!m_challengeList->empty() && m_auth == &m_challengeList->back())\n || m_challengeList->empty())) {\n AuthParams ap;\n m_challengeList->push_back(ap);\n m_auth = &m_challengeList->back();\n }\n m_auth->scheme = std::string(mark, fpc - mark);\n m_parameters = &m_auth->parameters;\n mark = NULL;\n }\n \n action save_base64_param {\n m_auth->base64 = std::string(mark, fpc - mark);\n mark = NULL;\n }\n\n auth_param = attribute '=' value;\n auth_scheme = token;\n base64_auth_param = base64 %save_base64_param;\n challenge = auth_scheme >mark %save_auth_scheme (SP ((auth_param ( LWS* ',' LWS* auth_param )*) | base64_auth_param))? LWS*;\n credentials = auth_scheme >mark %save_auth_scheme (LWS+ ((auth_param (LWS* ',' LWS* auth_param )*) | base64_auth_param))? LWS*;\n challengeList = LWS* challenge ( LWS* ',' LWS* challenge)* LWS*;\n \n action set_connection {\n m_set = &m_general->connection;\n m_list = NULL;\n }\n \n action set_date {\n m_date = &m_general->date;\n }\n \n action set_proxy_connection {\n m_set = &m_general->proxyConnection;\n m_list = NULL;\n }\n \n action set_trailer {\n m_set = &m_general->trailer;\n m_list = NULL;\n }\n \n action set_transfer_encoding {\n m_parameterizedList = &m_general->transferEncoding;\n }\n \n action save_upgrade_product {\n m_general->upgrade.push_back(m_product);\n m_product = Product();\n }\n\n Connection = 'Connection:'i @set_connection list;\n Date = 'Date:'i @set_date LWS* HTTP_date LWS*;\n # NON-STANDARD!!!\n Proxy_Connection = 'Proxy-Connection:'i @set_proxy_connection list;\n Trailer = 'Trailer:'i @set_trailer list;\n Transfer_Encoding = 'Transfer-Encoding:'i @set_transfer_encoding parameterizedList;\n Upgrade = 'Upgrade:'i LWS* product %save_upgrade_product ( LWS* ',' LWS* product %save_upgrade_product)* LWS*;\n \n general_header = Connection | Date | Proxy_Connection | Trailer | Transfer_Encoding | Upgrade;\n general_header_names = 'Connection'i | 'Date'i | 'Proxy-Connection'i | 'Trailer'i | 'Transfer-Encoding'i | 'Upgrade'i;\n \n action set_content_encoding {\n m_list = &m_entity->contentEncoding;\n m_set = NULL;\n }\n\n action set_content_length {\n m_ulong = &m_entity->contentLength;\n }\n \n action save_cr_first_byte_pos {\n m_entity->contentRange.first = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n\n action save_cr_last_byte_pos {\n m_entity->contentRange.last = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n \n action save_blank_cr {\n m_entity->contentRange.last = 0;\n }\n\n action save_instance_length {\n m_entity->contentRange.instance = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n \n action set_content_type\n {\n m_parameters = &m_entity->contentType.parameters;\n }\n action save_type\n {\n m_entity->contentType.type = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_subtype\n {\n m_entity->contentType.subtype = std::string(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_expires\n {\n m_date = &m_entity->expires;\n }\n action set_last_modified\n {\n m_date = &m_entity->lastModified;\n }\n\n Content_Encoding = 'Content-Encoding:'i @set_content_encoding list;\n Content_Length = 'Content-Length:'i @set_content_length LWS* DIGIT+ >mark %save_ulong LWS*;\n \n byte_range_resp_spec = (DIGIT+ >mark %save_cr_first_byte_pos '-' DIGIT+ >mark %save_cr_last_byte_pos) | '*' %save_blank_cr;\n content_range_spec = bytes_unit SP byte_range_resp_spec '\/' ( DIGIT+ >mark %save_instance_length | '*');\n Content_Range = 'Content-Range:'i LWS* content_range_spec LWS*;\n \n type = token >mark %save_type;\n subtype = token >mark %save_subtype;\n media_type = type '\/' subtype (';' LWS* parameter)*;\n Content_Type = 'Content-Type:'i @set_content_type LWS* media_type LWS*;\n \n Expires = 'Expires:'i @set_expires LWS* HTTP_date LWS*;\n Last_Modified = 'Last-Modified:'i @set_last_modified LWS* HTTP_date LWS*;\n \n entity_header = Content_Encoding | Content_Length | Content_Range | Content_Type | Expires | Last_Modified; # | extension_header;\n entity_header_names = 'Content-Encoding'i | 'Content-Length'i | 'Content-Range'i | 'Content-Type'i | 'Expires'i | 'Last-Modified'i;\n\n}%%\n\n%%{\n machine http_request_parser;\n include http_parser;\n include uri_parser \"..\/uri.rl\";\n\n action parse_Method {\n m_request->requestLine.method = parseMethod(mark, fpc);\n mark = NULL;\n }\n \n action set_request_uri {\n m_uri = &m_request->requestLine.uri;\n }\n \n action set_authorization {\n m_challengeList = NULL;\n m_auth = &m_request->request.authorization;\n }\n\n action save_expectation {\n KeyValueWithParameters kvp;\n kvp.key = std::string(mark, fpc - mark);\n m_request->request.expect.push_back(kvp);\n mark = NULL;\n }\n action save_expectation_value {\n m_request->request.expect.back().value = unquote(mark, fpc - mark);\n mark = NULL;\n }\n action save_expectation_param {\n m_temp1 = std::string(mark, fpc - mark);\n m_request->request.expect.back().parameters[m_temp1] = \"\";\n mark = NULL;\n }\n action save_expectation_param_value {\n m_request->request.expect.back().parameters[m_temp1] = unquote(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_host {\n m_string = &m_request->request.host;\n }\n \n action set_if_match {\n m_eTagSet = &m_request->request.ifMatch;\n }\n \n action set_if_modified_since {\n m_date = &m_request->request.ifModifiedSince;\n }\n \n action set_if_none_match {\n m_eTagSet = &m_request->request.ifNoneMatch;\n }\n \n action set_if_range_entity_tag {\n m_request->request.ifRange = ETag();\n m_eTag = boost::get(&m_request->request.ifRange);\n }\n \n action set_if_range_http_date {\n m_request->request.ifRange = boost::posix_time::ptime();\n m_date = boost::get(&m_request->request.ifRange);\n }\n \n action set_if_unmodified_since {\n m_date = &m_request->request.ifModifiedSince;\n }\n \n action set_proxy_authorization {\n m_challengeList = NULL;\n m_auth = &m_request->request.proxyAuthorization;\n }\n\n action save_first_byte_pos {\n m_request->request.range.push_back(RangeSet::value_type(\n strtoull(mark, NULL, 10), ~0ull));\n mark = NULL;\n }\n action save_last_byte_pos {\n if (mark != NULL) {\n m_request->request.range.back().second = strtoull(mark, NULL, 10);\n }\n mark = NULL;\n }\n action save_suffix_byte_pos {\n m_request->request.range.push_back(RangeSet::value_type(\n ~0ull, strtoull(mark, NULL, 10)));\n mark = NULL;\n }\n \n action set_referer {\n m_uri = &m_request->request.referer;\n }\n\n action save_accept_list_element {\n AcceptValueWithParameters avp;\n avp.value = std::string(mark, fpc - mark);\n m_acceptList->push_back(avp);\n m_parameters = &m_acceptList->back().parameters;\n mark = NULL;\n }\n \n action save_qvalue {\n m_acceptList->back().qvalue = 0;\n size_t i = 0;\n unsigned int curPlace = 1000;\n for (; i < 5 && mark < fpc; ++i, ++mark) {\n if (i == 1)\n continue;\n unsigned int cur = *mark - '0';\n m_acceptList->back().qvalue += cur * curPlace;\n curPlace \/= 10;\n }\n mark = NULL;\n }\n \n action save_accept_attribute {\n m_temp1 = std::string(mark, fpc - mark);\n m_acceptList->back().acceptParams[m_temp1] = \"\";\n mark = NULL;\n }\n \n action save_accept_value {\n m_acceptList->back().acceptParams[m_temp1] = unquote(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_te {\n m_acceptList = &m_request->request.te;\n }\n \n action set_user_agent {\n m_productAndCommentList = &m_request->request.userAgent;\n }\n\n Authorization = 'Authorization:'i @set_authorization LWS* credentials;\n \n expect_params = ';' token >mark %save_expectation_param ( '=' (token | quoted_string) >mark %save_expectation_param_value )?;\n expectation = token >mark %save_expectation ( '=' (token | quoted_string) >mark %save_expectation_value expect_params* )?;\n Expect = 'Expect:'i LWS* expectation ( LWS* ',' LWS* expectation )* LWS*;\n\n Host = 'Host:'i @set_host LWS* (host (':' port)?) >mark %save_string LWS*;\n\n If_Match = 'If-Match:'i @set_if_match etag_list;\n If_Modified_Since = 'If-Modified-Since:'i @set_if_modified_since LWS* HTTP_date LWS*;\n If_None_Match = 'If-None-Match:'i @set_if_none_match etag_list;\n If_Range = 'If-Range:'i LWS* (entity_tag >set_if_range_entity_tag | HTTP_date >set_if_range_http_date) LWS*;\n If_Unmodified_Since = 'If-Unmodified-Since:'i @set_if_unmodified_since LWS* HTTP_date LWS*;\n\n Proxy_Authorization = 'Proxy-Authorization:'i @set_proxy_authorization credentials;\n \n byte_range_spec = DIGIT+ >mark %save_first_byte_pos '-' (DIGIT+ >mark %save_last_byte_pos)?;\n suffix_byte_range_spec = '-' DIGIT+ > mark %save_suffix_byte_pos;\n byte_range_set = LWS* (byte_range_spec | suffix_byte_range_spec) ( LWS* ',' LWS* (byte_range_spec | suffix_byte_range_spec))* LWS*;\n ranges_specifier = bytes_unit '=' byte_range_set;\n Range = 'Range:'i LWS* ranges_specifier;\n \n Referer = 'Referer:'i @set_referer LWS* (absolute_URI | relative_URI);\n\n accept_extension = ';' token >mark %save_accept_attribute ('=' (token | quoted_string) >mark %save_accept_value)?;\n accept_params = ';q='i qvalue >mark %save_qvalue (accept_extension)*;\n acceptListElement = token >mark %save_accept_list_element (';' parameter)* (accept_params)?;\n acceptList = LWS* acceptListElement ( LWS* ',' LWS* acceptListElement)* LWS*;\n TE = 'TE:'i @set_te acceptList;\n \n User_Agent = 'User-Agent:'i @set_user_agent product_and_comment_list;\n \n request_header = Authorization | Expect | Host | If_Match | If_Modified_Since | If_None_Match | If_Range | If_Unmodified_Since | Proxy_Authorization | Range | Referer | TE | User_Agent;\n request_header_names = 'Authorization'i | 'Expect'i | 'Host'i | 'If-Match'i | 'If-Modified-Since'i | 'If-None-Match'i | 'If-Range'i | 'If-Unmodified-Since'i | 'Proxy-Authorization'i | 'Range'i | 'Referer'i | 'TE'i | 'User-Agent'i;\n \n extension_header = (token - (general_header_names | request_header_names | entity_header_names)) >mark %save_field_name\n ':' field_value;\n\n Method = token >mark %parse_Method;\n # we explicitly add query to path_absolute, because the URI spec changed from RFC 2396 to RFC 3986\n # with the query not being part of hier_part\n Request_URI = ( \"*\" | absolute_URI | (path_absolute ( \"?\" query )?) | authority);\n Request_Line = Method SP Request_URI >set_request_uri SP HTTP_Version CRLF;\n Request = Request_Line ((general_header | request_header | entity_header | extension_header) CRLF)* CRLF @done;\n\n main := Request;\n write data;\n}%%\n\nvoid\nHTTP::HTTPParser::init()\n{\n m_string = NULL;\n m_set = NULL;\n m_list = NULL;\n m_parameterizedList = NULL;\n m_parameters = NULL;\n m_auth = NULL;\n m_challengeList = NULL;\n m_ulong = NULL;\n m_eTag = NULL;\n m_eTagSet = NULL;\n m_productAndCommentList = NULL;\n RagelParser::init();\n}\n\nHTTP::RequestParser::RequestParser(Request& request)\n: m_request(&request),\n m_ver(&request.requestLine.ver),\n m_path(&request.requestLine.uri.path),\n m_general(&request.general),\n m_entity(&request.entity)\n{}\n\nvoid\nHTTP::RequestParser::init()\n{\n HTTPParser::init();\n %% write init;\n}\n\nbool\nHTTP::RequestParser::final() const\n{\n return cs >= http_request_parser_first_final;\n}\n\nbool\nHTTP::RequestParser::error() const\n{\n return cs == http_request_parser_error;\n}\n\nvoid\nHTTP::RequestParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\n%%{\n machine http_response_parser;\n include http_parser;\n include uri_parser \"..\/uri.rl\";\n \n action parse_Status_Code {\n m_response->status.status = (HTTP::Status)atoi(mark);\n mark = NULL;\n }\n\n action parse_Reason_Phrase {\n m_response->status.reason = std::string(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_accept_ranges\n {\n m_set = &m_response->response.acceptRanges;\n m_list = NULL;\n }\n action set_etag\n {\n m_eTag = &m_response->response.eTag;\n }\n action set_proxy_authenticate {\n m_challengeList = &m_response->response.proxyAuthenticate;\n }\n action set_retry_after_http_date {\n m_response->response.retryAfter = boost::posix_time::ptime();\n m_date = boost::get(&m_response->response.retryAfter);\n }\n action set_retry_after_delta_seconds {\n m_response->response.retryAfter = ~0ull;\n m_ulong = boost::get(&m_response->response.retryAfter);\n }\n action set_server {\n m_productAndCommentList = &m_response->response.server;\n }\n action set_www_authenticate {\n m_challengeList = &m_response->response.wwwAuthenticate;\n }\n \n Accept_Ranges = 'Accept-Ranges:'i @set_accept_ranges list;\n ETag = 'ETag:'i @set_etag LWS* entity_tag;\n # This *should* be absolute_URI, but we're generous\n Location = 'Location:'i LWS* URI_reference LWS*;\n Proxy_Authenticate = 'Proxy-Authenticate:'i @set_proxy_authenticate challengeList;\n Retry_After = 'Retry-After:'i LWS* (HTTP_date %set_retry_after_http_date | delta_seconds >mark %set_retry_after_delta_seconds %save_ulong) LWS*;\n Server = 'Server:'i @set_server product_and_comment_list;\n WWW_Authenticate = 'WWW-Authenticate:'i @set_www_authenticate challengeList;\n \n response_header = Accept_Ranges | ETag | Location | Proxy_Authenticate | Retry_After | Server | WWW_Authenticate;\n response_header_names = 'Accept-Ranges'i | 'ETag'i | 'Location'i | 'Proxy-Authenticate'i | 'Retry-After'i | 'Server'i | 'WWW-Authenticate'i;\n \n extension_header = (token - (general_header_names | response_header_names | entity_header_names)) >mark %save_field_name\n ':' field_value;\n\n Status_Code = DIGIT{3} > mark %parse_Status_Code;\n Reason_Phrase = (TEXT -- (CR | LF))* >mark %parse_Reason_Phrase;\n Status_Line = HTTP_Version SP Status_Code SP Reason_Phrase CRLF;\n Response = Status_Line ((general_header | response_header | entity_header | extension_header) CRLF)* CRLF @done;\n\n main := Response;\n\n write data;\n}%%\n\nHTTP::ResponseParser::ResponseParser(Response& response)\n: m_response(&response),\n m_ver(&response.status.ver),\n m_uri(&response.response.location),\n m_path(&response.response.location.path),\n m_general(&response.general),\n m_entity(&response.entity)\n{}\n\nvoid\nHTTP::ResponseParser::init()\n{\n HTTPParser::init();\n %% write init;\n}\n\nbool\nHTTP::ResponseParser::final() const\n{\n return cs >= http_response_parser_first_final;\n}\n\nbool\nHTTP::ResponseParser::error() const\n{\n return cs == http_response_parser_error;\n}\n\nvoid\nHTTP::ResponseParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\n%%{\n machine http_trailer_parser;\n include http_parser;\n\n extension_header = (token - (entity_header_names)) >mark %save_field_name ':' field_value;\n\n trailer = ((entity_header | extension_header) CRLF)*;\n\n main := trailer CRLF @done;\n\n write data;\n}%%\n\nHTTP::TrailerParser::TrailerParser(EntityHeaders& entity)\n: m_entity(&entity)\n{}\n\nvoid\nHTTP::TrailerParser::init()\n{\n HTTPParser::init();\n %% write init;\n}\n\nbool\nHTTP::TrailerParser::final() const\n{\n return cs >= http_trailer_parser_first_final;\n}\n\nbool\nHTTP::TrailerParser::error() const\n{\n return cs == http_trailer_parser_error;\n}\n\nvoid\nHTTP::TrailerParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\n\n%%{\n machine http_list_parser;\n include http_parser;\n\n main := list;\n\n write data;\n}%%\n\nHTTP::ListParser::ListParser(StringSet& stringSet)\n: m_set(&stringSet),\n m_list(NULL)\n{}\n\nvoid\nHTTP::ListParser::init()\n{\n RagelParser::init();\n %% write init;\n}\n\nbool\nHTTP::ListParser::final() const\n{\n return cs >= http_list_parser_first_final;\n}\n\nbool\nHTTP::ListParser::error() const\n{\n return cs == http_list_parser_error;\n}\n\nvoid\nHTTP::ListParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n","old_contents":"\/\/ Copyright (c) 2009 - Decho Corp.\n\n#include \"mordor\/common\/pch.h\"\n\n#include \"mordor\/common\/http\/parser.h\"\n\n#include \n#include \n#include \n\n#include \"mordor\/common\/version.h\"\n\n\/\/ From uri.rl\nstd::string unescape(const std::string& str, bool spaceAsPlus = false);\n\nstatic\nHTTP::Version\nparseVersion(const char *str)\n{\n HTTP::Version ver;\n ver.major = atoi(str + 5);\n ver.minor = atoi(strchr(str + 5, '.') + 1);\n return ver;\n}\n\nstatic\nHTTP::Method\nparseMethod(const char *str, const char *end)\n{\n for(size_t i = 0; i < 8; ++i) {\n if (strnicmp(str, HTTP::methods[i], end - str) == 0) {\n return (HTTP::Method)i;\n }\n }\n throw std::invalid_argument(\"Unrecognized method\");\n}\n\nstatic boost::posix_time::time_input_facet rfc1123Facet_in(\"%a, %d %b %Y %H:%M:%S GMT\",\n 1 \/* starting refcount, so this never gets deleted *\/);\nstatic boost::posix_time::time_input_facet rfc850Facet_in(\"%A, %d-%b-%y %H:%M:%S GMT\",\n 1 \/* starting refcount, so this never gets deleted *\/);\nstatic boost::posix_time::time_input_facet ansiFacet_in(\"%a %b %e %H:%M:%S %Y\",\n 1 \/* starting refcount, so this never gets deleted *\/);\n\nstatic\nboost::posix_time::ptime\nparseHttpDate(const char *str, size_t size)\n{\n boost::posix_time::ptime result;\n std::string val(str, size);\n \n #define ATTEMPT_WITH_FACET(facet) \\\n { \\\n std::istringstream is(val); \\\n is.imbue(std::locale(is.getloc(), facet)); \\\n is >> result; \\\n if (!result.is_not_a_date_time()) \\\n return result; \\\n }\n\n ATTEMPT_WITH_FACET(&rfc1123Facet_in);\n ATTEMPT_WITH_FACET(&rfc850Facet_in);\n ATTEMPT_WITH_FACET(&ansiFacet_in);\n NOTREACHED();\n}\n\nstatic\nstd::string\nunfold(char *p, char *pe)\n{\n char *start = p;\n char *pw = p;\n\n while (p < pe) {\n \/\/ Skip leading whitespace\n if (pw == start) {\n if (*p == ' ' || *p == '\\t' || *p == '\\r' || *p == '\\n') {\n ++p; ++pw; ++start;\n continue;\n }\n }\n \/\/ Only copy if necessary\n if (pw != p) {\n *pw = *p;\n }\n ++p; ++pw;\n }\n \/\/ Remove trailing whitespace\n do {\n --pw;\n } while ((*pw == ' ' || *pw == '\\t' || *pw == '\\r' || *pw == '\\n') && pw >= start);\n ++pw;\n return std::string(start, pw - start);\n}\n\nstd::string\nHTTP::unquote(const char *str, size_t size)\n{\n if (size == 0 || (str[0] != '\"' && str[0] != '('))\n return std::string(str, size);\n ASSERT((str[size - 1] == '\"' && str[0] == '\"') ||\n (str[size - 1] == ')' && str[0] == '('));\n std::string result(str + 1, size - 2);\n char *p = const_cast(result.c_str());\n char *pe = p + result.size();\n char *pw = p;\n\n bool escaping = false;\n while (p < pe) {\n if (escaping) {\n escaping = false;\n } else if (*p == '\\\\') {\n escaping = true;\n ++p;\n continue;\n }\n \/\/ Only copy if necessary\n if (pw != p)\n *pw = *p;\n ++p; ++pw;\n }\n result.resize(pw - result.c_str());\n return result;\n}\n\nstd::string\nHTTP::unquote(const std::string &str)\n{\n if (str.empty() || (str[0] != '\"' && str[0] != '('))\n return str;\n return unquote(str.c_str(), str.size());\n}\n\n%%{\n machine http_parser;\n \n # See RFC 2616: http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616.html\n\n action mark { mark = fpc; }\n action done { fbreak; }\n\n # basic character types\n OCTET = any;\n CHAR = ascii;\n UPALPHA = \"A\"..\"Z\";\n LOALPHA = \"a\"..\"z\";\n ALPHA = alpha;\n DIGIT = digit;\n CTL = cntrl | 127;\n CR = \"\\r\";\n LF = \"\\n\";\n SP = \" \";\n HT = \"\\t\";\n\n # almost-basic character types\n # note that we allow a single LF for a CR LF\n CRLF = CR LF;\n LWS = CRLF? ( SP | HT )+;\n TEXT = LWS | (OCTET -- CTL);\n HEX = xdigit;\n\n # some basic tokens\n separators = \"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | SP | HT;\n token = (CHAR -- (separators | CTL))+;\n quoted_pair = \"\\\\\" CHAR;\n ctext = TEXT -- (\"(\" | \")\");\n # TODO: truly nested comments\n base_comment = \"(\" ( ctext | quoted_pair )* \")\";\n comment = \"(\" ( ctext | quoted_pair | base_comment )* \")\";\n qdtext = TEXT -- \"\\\"\";\n quoted_string = \"\\\"\" ( qdtext | quoted_pair )* \"\\\"\";\n \n base64char = ALPHA | DIGIT | '+' | '\/';\n base64 = (base64char{4})+ ( (base64char{3} '=') | (base64char{2} '==') )?;\n\n action parse_HTTP_Version {\n ASSERT(m_ver);\n *m_ver = parseVersion(mark);\n mark = NULL;\n }\n\n HTTP_Version = (\"HTTP\/\" DIGIT+ \".\" DIGIT+) >mark %parse_HTTP_Version;\n\n action save_date {\n ASSERT(m_date);\n *m_date = parseHttpDate(mark, fpc - mark);\n mark = NULL; \n }\n\n wkday = \"Mon\" | \"Tue\" | \"Wed\" | \"Thu\" | \"Fri\" | \"Sat\" | \"Sun\";\n weekday = \"Monday\" | \"Tuesday\" | \"Wednesday\" | \"Thursday\" | \"Friday\" | \"Saturday\" | \"Sunday\";\n month = \"Jan\" | \"Feb\" | \"Mar\" | \"Apr\" | \"May\" | \"Jun\" | \"Jul\" | \"Aug\" | \"Sep\" | \"Oct\" | \"Nov\" | \"Dec\";\n date1 = DIGIT{2} SP month SP DIGIT{4};\n date2 = DIGIT{2} \"-\" month \"-\" DIGIT{2};\n date3 = month SP ( DIGIT{2} | (SP DIGIT));\n time = DIGIT{2} \":\" DIGIT{2} \":\" DIGIT{2};\n rfc1123_date = wkday \",\" SP date1 SP time SP \"GMT\";\n rfc850_date = weekday \",\" SP date2 SP time SP \"GMT\";\n asctime_date = wkday SP date3 SP time SP DIGIT{4};\n HTTP_date = (rfc1123_date | rfc850_date | asctime_date) >mark %save_date;\n \n delta_seconds = DIGIT+;\n\n action save_product_name {\n m_product.product = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_product_version {\n m_product.version = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_product {\n ASSERT(m_productAndCommentList);\n m_productAndCommentList->push_back(m_product);\n m_product = Product();\n }\n action save_comment {\n\t\tASSERT(m_productAndCommentList);\n m_productAndCommentList->push_back(HTTP::unquote(mark, fpc - mark));\n mark = NULL;\n }\n\n product_version = token;\n product = token >mark %save_product_name (\"\/\" product_version >mark %save_product_version)?;\n product_or_comment = (product %save_product) | (comment >mark %save_comment);\n product_and_comment_list = LWS* product_or_comment ( LWS+ product_or_comment)* LWS*;\n\n qvalue = ('0' ('.' DIGIT{0,3})?) | ('1' ('.' '0'{0,3})?);\n\n subtag = ALPHA{1,8};\n primary_tag = ALPHA{1,8};\n language_tag = primary_tag (\"-\" subtag);\n\n action start_etag {\n ASSERT(m_eTag);\n m_eTag->weak = false;\n }\n action save_weak {\n ASSERT(m_eTag);\n m_eTag->unspecified = false;\n m_eTag->weak = true;\n }\n action save_etag {\n ASSERT(m_eTag);\n m_eTag->unspecified = false;\n m_eTag->value = unquote(mark, fpc - mark);\n }\n action set_etag_list {\n m_eTag = &m_tempETag;\n }\n action save_unspecified {\n ASSERT(m_eTagSet);\n m_eTagSet->insert(ETag());\n }\n action save_etag_element {\n ASSERT(m_eTagSet);\n ASSERT(m_eTag == & m_tempETag);\n m_eTagSet->insert(m_tempETag);\n }\n \n weak = \"W\/\" %save_weak;\n opaque_tag = quoted_string >mark %save_etag;\n entity_tag = ((weak)? opaque_tag) >start_etag;\n\n etag_list = LWS* (\"*\" % save_unspecified | (LWS* entity_tag %save_etag_element ( LWS* ',' LWS* entity_tag %save_etag_element)* LWS*) LWS* ) > set_etag_list;\n\n bytes_unit = \"bytes\";\n other_range_unit = token;\n range_unit = bytes_unit | other_range_unit;\n\n action save_field_name {\n m_temp1 = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_field_value {\n std::string fieldValue = unfold((char*)mark, (char*)fpc);\n \n StringMap::iterator it = m_entity->extension.find(m_temp1);\n if (it == m_entity->extension.end()) {\n m_entity->extension[m_temp1] = fieldValue;\n } else {\n it->second.append(\", \");\n it->second.append(fieldValue);\n }\n mark = NULL;\n }\n\n field_chars = OCTET -- (CTL | CR LF SP HT);\n field_name = token >mark %save_field_name;\n field_value = TEXT* >mark %save_field_value;\n message_header = field_name \":\" field_value;\n \n action save_string {\n *m_string = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_ulong {\n *m_ulong = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n \n action save_element {\n ASSERT(m_list || m_set);\n if (m_list)\n m_list->push_back(std::string(mark, fpc - mark));\n else\n m_set->insert(std::string(mark, fpc - mark));\n mark = NULL;\n }\n element = token >mark %save_element;\n list = (LWS* element ( LWS* ',' LWS* element)* LWS*);\n \n action save_parameterized_list_element {\n ValueWithParameters vp;\n vp.value = std::string(mark, fpc - mark);\n m_parameterizedList->push_back(vp);\n m_parameters = &m_parameterizedList->back().parameters;\n mark = NULL;\n }\n \n action save_parameter_attribute {\n m_temp1 = std::string(mark, fpc - mark);\n \/\/ Don't NULL out here; could be base64 later\n }\n \n action save_parameter_value {\n (*m_parameters)[m_temp1] = unquote(mark, fpc - mark);\n mark = NULL;\n }\n\n attribute = (token - 'q'i) >mark %save_parameter_attribute; # q separates params from accept-params\n value = (token | quoted_string) >mark %save_parameter_value;\n parameter = attribute '=' value;\n parameterizedListElement = token >mark %save_parameterized_list_element (';' parameter)*;\n parameterizedList = LWS* parameterizedListElement ( LWS* ',' LWS* parameterizedListElement)* LWS*;\n \n action save_auth_scheme {\n if (m_challengeList && ((!m_challengeList->empty() && m_auth == &m_challengeList->back())\n || m_challengeList->empty())) {\n AuthParams ap;\n m_challengeList->push_back(ap);\n m_auth = &m_challengeList->back();\n }\n m_auth->scheme = std::string(mark, fpc - mark);\n m_parameters = &m_auth->parameters;\n mark = NULL;\n }\n \n action save_base64_param {\n m_auth->base64 = std::string(mark, fpc - mark);\n mark = NULL;\n }\n\n auth_param = attribute '=' value;\n auth_scheme = token;\n base64_auth_param = base64 %save_base64_param;\n challenge = auth_scheme >mark %save_auth_scheme (SP ((auth_param ( LWS* ',' LWS* auth_param )*) | base64_auth_param))? LWS*;\n credentials = auth_scheme >mark %save_auth_scheme (LWS+ ((auth_param (LWS* ',' LWS* auth_param )*) | base64_auth_param))? LWS*;\n challengeList = LWS* challenge ( LWS* ',' LWS* challenge)* LWS*;\n \n action set_connection {\n m_set = &m_general->connection;\n m_list = NULL;\n }\n \n action set_date {\n m_date = &m_general->date;\n }\n \n action set_proxy_connection {\n m_set = &m_general->proxyConnection;\n m_list = NULL;\n }\n \n action set_trailer {\n m_set = &m_general->trailer;\n m_list = NULL;\n }\n \n action set_transfer_encoding {\n m_parameterizedList = &m_general->transferEncoding;\n }\n \n action save_upgrade_product {\n m_general->upgrade.push_back(m_product);\n m_product = Product();\n }\n\n Connection = 'Connection:'i @set_connection list;\n Date = 'Date:'i @set_date LWS* HTTP_date LWS*;\n # NON-STANDARD!!!\n Proxy_Connection = 'Proxy-Connection:'i @set_proxy_connection list;\n Trailer = 'Trailer:'i @set_trailer list;\n Transfer_Encoding = 'Transfer-Encoding:'i @set_transfer_encoding parameterizedList;\n Upgrade = 'Upgrade:'i LWS* product %save_upgrade_product ( LWS* ',' LWS* product %save_upgrade_product)* LWS*;\n \n general_header = Connection | Date | Proxy_Connection | Trailer | Transfer_Encoding | Upgrade;\n general_header_names = 'Connection'i | 'Date'i | 'Proxy-Connection'i | 'Trailer'i | 'Transfer-Encoding'i | 'Upgrade'i;\n \n action set_content_encoding {\n m_list = &m_entity->contentEncoding;\n m_set = NULL;\n }\n\n action set_content_length {\n m_ulong = &m_entity->contentLength;\n }\n \n action save_cr_first_byte_pos {\n m_entity->contentRange.first = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n\n action save_cr_last_byte_pos {\n m_entity->contentRange.last = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n \n action save_blank_cr {\n m_entity->contentRange.last = 0;\n }\n\n action save_instance_length {\n m_entity->contentRange.instance = strtoull(mark, NULL, 10);\n mark = NULL;\n }\n \n action set_content_type\n {\n m_parameters = &m_entity->contentType.parameters;\n }\n action save_type\n {\n m_entity->contentType.type = std::string(mark, fpc - mark);\n mark = NULL;\n }\n action save_subtype\n {\n m_entity->contentType.subtype = std::string(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_expires\n {\n m_date = &m_entity->expires;\n }\n action set_last_modified\n {\n m_date = &m_entity->lastModified;\n }\n\n Content_Encoding = 'Content-Encoding:'i @set_content_encoding list;\n Content_Length = 'Content-Length:'i @set_content_length LWS* DIGIT+ >mark %save_ulong LWS*;\n \n byte_range_resp_spec = (DIGIT+ >mark %save_cr_first_byte_pos '-' DIGIT+ >mark %save_cr_last_byte_pos) | '*' %save_blank_cr;\n content_range_spec = bytes_unit SP byte_range_resp_spec '\/' ( DIGIT+ >mark %save_instance_length | '*');\n Content_Range = 'Content-Range:'i LWS* content_range_spec LWS*;\n \n type = token >mark %save_type;\n subtype = token >mark %save_subtype;\n media_type = type '\/' subtype (';' LWS* parameter)*;\n Content_Type = 'Content-Type:'i @set_content_type LWS* media_type LWS*;\n \n Expires = 'Expires:'i @set_expires LWS* HTTP_date LWS*;\n Last_Modified = 'Last-Modified:'i @set_last_modified LWS* HTTP_date LWS*;\n \n entity_header = Content_Encoding | Content_Length | Content_Range | Content_Type | Expires | Last_Modified; # | extension_header;\n entity_header_names = 'Content-Encoding'i | 'Content-Length'i | 'Content-Range'i | 'Content-Type'i | 'Expires'i | 'Last-Modified'i;\n\n}%%\n\n%%{\n machine http_request_parser;\n include http_parser;\n include uri_parser \"..\/uri.rl\";\n\n action parse_Method {\n m_request->requestLine.method = parseMethod(mark, fpc);\n mark = NULL;\n }\n \n action set_request_uri {\n m_uri = &m_request->requestLine.uri;\n }\n \n action set_authorization {\n m_challengeList = NULL;\n m_auth = &m_request->request.authorization;\n }\n\n action save_expectation {\n KeyValueWithParameters kvp;\n kvp.key = std::string(mark, fpc - mark);\n m_request->request.expect.push_back(kvp);\n mark = NULL;\n }\n action save_expectation_value {\n m_request->request.expect.back().value = unquote(mark, fpc - mark);\n mark = NULL;\n }\n action save_expectation_param {\n m_temp1 = std::string(mark, fpc - mark);\n m_request->request.expect.back().parameters[m_temp1] = \"\";\n mark = NULL;\n }\n action save_expectation_param_value {\n m_request->request.expect.back().parameters[m_temp1] = unquote(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_host {\n m_string = &m_request->request.host;\n }\n \n action set_if_match {\n m_eTagSet = &m_request->request.ifMatch;\n }\n \n action set_if_modified_since {\n m_date = &m_request->request.ifModifiedSince;\n }\n \n action set_if_none_match {\n m_eTagSet = &m_request->request.ifMatch;\n }\n \n action set_if_range_entity_tag {\n m_request->request.ifRange = ETag();\n m_eTag = boost::get(&m_request->request.ifRange);\n }\n \n action set_if_range_http_date {\n m_request->request.ifRange = boost::posix_time::ptime();\n m_date = boost::get(&m_request->request.ifRange);\n }\n \n action set_if_unmodified_since {\n m_date = &m_request->request.ifModifiedSince;\n }\n \n action set_proxy_authorization {\n m_challengeList = NULL;\n m_auth = &m_request->request.proxyAuthorization;\n }\n\n action save_first_byte_pos {\n m_request->request.range.push_back(RangeSet::value_type(\n strtoull(mark, NULL, 10), ~0ull));\n mark = NULL;\n }\n action save_last_byte_pos {\n if (mark != NULL) {\n m_request->request.range.back().second = strtoull(mark, NULL, 10);\n }\n mark = NULL;\n }\n action save_suffix_byte_pos {\n m_request->request.range.push_back(RangeSet::value_type(\n ~0ull, strtoull(mark, NULL, 10)));\n mark = NULL;\n }\n \n action set_referer {\n m_uri = &m_request->request.referer;\n }\n\n action save_accept_list_element {\n AcceptValueWithParameters avp;\n avp.value = std::string(mark, fpc - mark);\n m_acceptList->push_back(avp);\n m_parameters = &m_acceptList->back().parameters;\n mark = NULL;\n }\n \n action save_qvalue {\n m_acceptList->back().qvalue = 0;\n size_t i = 0;\n unsigned int curPlace = 1000;\n for (; i < 5 && mark < fpc; ++i, ++mark) {\n if (i == 1)\n continue;\n unsigned int cur = *mark - '0';\n m_acceptList->back().qvalue += cur * curPlace;\n curPlace \/= 10;\n }\n mark = NULL;\n }\n \n action save_accept_attribute {\n m_temp1 = std::string(mark, fpc - mark);\n m_acceptList->back().acceptParams[m_temp1] = \"\";\n mark = NULL;\n }\n \n action save_accept_value {\n m_acceptList->back().acceptParams[m_temp1] = unquote(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_te {\n m_acceptList = &m_request->request.te;\n }\n \n action set_user_agent {\n m_productAndCommentList = &m_request->request.userAgent;\n }\n\n Authorization = 'Authorization:'i @set_authorization LWS* credentials;\n \n expect_params = ';' token >mark %save_expectation_param ( '=' (token | quoted_string) >mark %save_expectation_param_value )?;\n expectation = token >mark %save_expectation ( '=' (token | quoted_string) >mark %save_expectation_value expect_params* )?;\n Expect = 'Expect:'i LWS* expectation ( LWS* ',' LWS* expectation )* LWS*;\n\n Host = 'Host:'i @set_host LWS* (host (':' port)?) >mark %save_string LWS*;\n\n If_Match = 'If-Match:'i @set_if_match etag_list;\n If_Modified_Since = 'If-Modified-Since:'i @set_if_modified_since LWS* HTTP_date LWS*;\n If_None_Match = 'If-None-Match:'i @set_if_none_match etag_list;\n If_Range = 'If-Range:'i LWS* (entity_tag >set_if_range_entity_tag | HTTP_date >set_if_range_http_date) LWS*;\n If_Unmodified_Since = 'If-Unmodified-Since:'i @set_if_unmodified_since LWS* HTTP_date LWS*;\n\n Proxy_Authorization = 'Proxy-Authorization:'i @set_proxy_authorization credentials;\n \n byte_range_spec = DIGIT+ >mark %save_first_byte_pos '-' (DIGIT+ >mark %save_last_byte_pos)?;\n suffix_byte_range_spec = '-' DIGIT+ > mark %save_suffix_byte_pos;\n byte_range_set = LWS* (byte_range_spec | suffix_byte_range_spec) ( LWS* ',' LWS* (byte_range_spec | suffix_byte_range_spec))* LWS*;\n ranges_specifier = bytes_unit '=' byte_range_set;\n Range = 'Range:'i LWS* ranges_specifier;\n \n Referer = 'Referer:'i @set_referer LWS* (absolute_URI | relative_URI);\n\n accept_extension = ';' token >mark %save_accept_attribute ('=' (token | quoted_string) >mark %save_accept_value)?;\n accept_params = ';q='i qvalue >mark %save_qvalue (accept_extension)*;\n acceptListElement = token >mark %save_accept_list_element (';' parameter)* (accept_params)?;\n acceptList = LWS* acceptListElement ( LWS* ',' LWS* acceptListElement)* LWS*;\n TE = 'TE:'i @set_te acceptList;\n \n User_Agent = 'User-Agent:'i @set_user_agent product_and_comment_list;\n \n request_header = Authorization | Expect | Host | If_Match | If_Modified_Since | If_None_Match | If_Range | If_Unmodified_Since | Proxy_Authorization | Range | Referer | TE | User_Agent;\n request_header_names = 'Authorization'i | 'Expect'i | 'Host'i | 'If-Match'i | 'If-Modified-Since'i | 'If-None-Match'i | 'If-Range'i | 'If-Unmodified-Since'i | 'Proxy-Authorization'i | 'Range'i | 'Referer'i | 'TE'i | 'User-Agent'i;\n \n extension_header = (token - (general_header_names | request_header_names | entity_header_names)) >mark %save_field_name\n ':' field_value;\n\n Method = token >mark %parse_Method;\n # we explicitly add query to path_absolute, because the URI spec changed from RFC 2396 to RFC 3986\n # with the query not being part of hier_part\n Request_URI = ( \"*\" | absolute_URI | (path_absolute ( \"?\" query )?) | authority);\n Request_Line = Method SP Request_URI >set_request_uri SP HTTP_Version CRLF;\n Request = Request_Line ((general_header | request_header | entity_header | extension_header) CRLF)* CRLF @done;\n\n main := Request;\n write data;\n}%%\n\nvoid\nHTTP::HTTPParser::init()\n{\n m_string = NULL;\n m_set = NULL;\n m_list = NULL;\n m_parameterizedList = NULL;\n m_parameters = NULL;\n m_auth = NULL;\n m_challengeList = NULL;\n m_ulong = NULL;\n m_eTag = NULL;\n m_eTagSet = NULL;\n m_productAndCommentList = NULL;\n RagelParser::init();\n}\n\nHTTP::RequestParser::RequestParser(Request& request)\n: m_request(&request),\n m_ver(&request.requestLine.ver),\n m_path(&request.requestLine.uri.path),\n m_general(&request.general),\n m_entity(&request.entity)\n{}\n\nvoid\nHTTP::RequestParser::init()\n{\n HTTPParser::init();\n %% write init;\n}\n\nbool\nHTTP::RequestParser::final() const\n{\n return cs >= http_request_parser_first_final;\n}\n\nbool\nHTTP::RequestParser::error() const\n{\n return cs == http_request_parser_error;\n}\n\nvoid\nHTTP::RequestParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\n%%{\n machine http_response_parser;\n include http_parser;\n include uri_parser \"..\/uri.rl\";\n \n action parse_Status_Code {\n m_response->status.status = (HTTP::Status)atoi(mark);\n mark = NULL;\n }\n\n action parse_Reason_Phrase {\n m_response->status.reason = std::string(mark, fpc - mark);\n mark = NULL;\n }\n \n action set_accept_ranges\n {\n m_set = &m_response->response.acceptRanges;\n m_list = NULL;\n }\n action set_etag\n {\n m_eTag = &m_response->response.eTag;\n }\n action set_proxy_authenticate {\n m_challengeList = &m_response->response.proxyAuthenticate;\n }\n action set_retry_after_http_date {\n m_response->response.retryAfter = boost::posix_time::ptime();\n m_date = boost::get(&m_response->response.retryAfter);\n }\n action set_retry_after_delta_seconds {\n m_response->response.retryAfter = ~0ull;\n m_ulong = boost::get(&m_response->response.retryAfter);\n }\n action set_server {\n m_productAndCommentList = &m_response->response.server;\n }\n action set_www_authenticate {\n m_challengeList = &m_response->response.wwwAuthenticate;\n }\n \n Accept_Ranges = 'Accept-Ranges:'i @set_accept_ranges list;\n ETag = 'ETag:'i @set_etag LWS* entity_tag;\n # This *should* be absolute_URI, but we're generous\n Location = 'Location:'i LWS* URI_reference LWS*;\n Proxy_Authenticate = 'Proxy-Authenticate:'i @set_proxy_authenticate challengeList;\n Retry_After = 'Retry-After:'i LWS* (HTTP_date %set_retry_after_http_date | delta_seconds >mark %set_retry_after_delta_seconds %save_ulong) LWS*;\n Server = 'Server:'i @set_server product_and_comment_list;\n WWW_Authenticate = 'WWW-Authenticate:'i @set_www_authenticate challengeList;\n \n response_header = Accept_Ranges | ETag | Location | Proxy_Authenticate | Retry_After | Server | WWW_Authenticate;\n response_header_names = 'Accept-Ranges'i | 'ETag'i | 'Location'i | 'Proxy-Authenticate'i | 'Retry-After'i | 'Server'i | 'WWW-Authenticate'i;\n \n extension_header = (token - (general_header_names | response_header_names | entity_header_names)) >mark %save_field_name\n ':' field_value;\n\n Status_Code = DIGIT{3} > mark %parse_Status_Code;\n Reason_Phrase = (TEXT -- (CR | LF))* >mark %parse_Reason_Phrase;\n Status_Line = HTTP_Version SP Status_Code SP Reason_Phrase CRLF;\n Response = Status_Line ((general_header | response_header | entity_header | extension_header) CRLF)* CRLF @done;\n\n main := Response;\n\n write data;\n}%%\n\nHTTP::ResponseParser::ResponseParser(Response& response)\n: m_response(&response),\n m_ver(&response.status.ver),\n m_uri(&response.response.location),\n m_path(&response.response.location.path),\n m_general(&response.general),\n m_entity(&response.entity)\n{}\n\nvoid\nHTTP::ResponseParser::init()\n{\n HTTPParser::init();\n %% write init;\n}\n\nbool\nHTTP::ResponseParser::final() const\n{\n return cs >= http_response_parser_first_final;\n}\n\nbool\nHTTP::ResponseParser::error() const\n{\n return cs == http_response_parser_error;\n}\n\nvoid\nHTTP::ResponseParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\n%%{\n machine http_trailer_parser;\n include http_parser;\n\n extension_header = (token - (entity_header_names)) >mark %save_field_name ':' field_value;\n\n trailer = ((entity_header | extension_header) CRLF)*;\n\n main := trailer CRLF @done;\n\n write data;\n}%%\n\nHTTP::TrailerParser::TrailerParser(EntityHeaders& entity)\n: m_entity(&entity)\n{}\n\nvoid\nHTTP::TrailerParser::init()\n{\n HTTPParser::init();\n %% write init;\n}\n\nbool\nHTTP::TrailerParser::final() const\n{\n return cs >= http_trailer_parser_first_final;\n}\n\nbool\nHTTP::TrailerParser::error() const\n{\n return cs == http_trailer_parser_error;\n}\n\nvoid\nHTTP::TrailerParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n\n\n%%{\n machine http_list_parser;\n include http_parser;\n\n main := list;\n\n write data;\n}%%\n\nHTTP::ListParser::ListParser(StringSet& stringSet)\n: m_set(&stringSet),\n m_list(NULL)\n{}\n\nvoid\nHTTP::ListParser::init()\n{\n RagelParser::init();\n %% write init;\n}\n\nbool\nHTTP::ListParser::final() const\n{\n return cs >= http_list_parser_first_final;\n}\n\nbool\nHTTP::ListParser::error() const\n{\n return cs == http_list_parser_error;\n}\n\nvoid\nHTTP::ListParser::exec()\n{\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"3f00b3c6c22a4e1c321f9676624e63c156107f4f","subject":"Add parsing of binary body to JavaParser","message":"Add parsing of binary body to JavaParser","repos":"elabs\/stompede,elabs\/stomp_parser,elabs\/stomp_parser,elabs\/stompede","old_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.RubyNumeric;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n \/*mark_message_size = 0;*\/\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n IRubyObject content_length = mark_message.callMethod(context, \"content_length\");\n\n if ( ! content_length.isNil()) {\n mark_content_length = RubyNumeric.num2int(content_length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n mark_message.callMethod(context, \"write_body\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action consume_null {\n ((mark_content_length != -1) && ((p - mark) < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || ((p - mark) < mark_content_length))\n }\n\n action check_message_size {\n \/*mark_message_size += 1;*\/\n \/*if (mark_message_size > max_message_size) {*\/\n \/* rb_raise(eMessageSizeExceeded, \"\");*\/\n \/*}*\/\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n \/\/ RaiseException error = context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(\"build_parse_error\");\n \/\/ throw error;\n }\n\n return context.nil;\n }\n}\n","old_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n \/*mark_message_size = 0;*\/\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n \/*VALUE length = rb_funcall(mark_message, g_content_length, 0);*\/\n \/*if ( ! NIL_P(length)) {*\/\n \/* mark_content_length = NUM2LONG(length);*\/\n \/*} else {*\/\n \/* mark_content_length = -1;*\/\n \/*}*\/\n }\n\n action write_body {\n mark_message.callMethod(context, \"write_body\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action consume_null {\n false\n \/*((mark_content_length != -1) && (MARK_LEN < mark_content_length))*\/\n }\n\n action consume_octet {\n true\n \/*((mark_content_length == -1) || (MARK_LEN < mark_content_length))*\/\n }\n\n action check_message_size {\n \/*mark_message_size += 1;*\/\n \/*if (mark_message_size > max_message_size) {*\/\n \/* rb_raise(eMessageSizeExceeded, \"\");*\/\n \/*}*\/\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n \/\/ RaiseException error = context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(\"build_parse_error\");\n \/\/ throw error;\n }\n\n return context.nil;\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"7d40ed3e801d64637670cdcb51f94a7ad8ec81a7","subject":"Handle multiple invocations in JavaParser with error","message":"Handle multiple invocations in JavaParser with error","repos":"elabs\/stomp_parser,elabs\/stompede,elabs\/stompede,elabs\/stomp_parser","old_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_file":"ext\/java\/stompede\/stomp\/JavaParser.java.rl","new_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.RubyNumeric;\nimport org.jruby.RubyException;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n mark_message_size = 0;\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n IRubyObject content_length = mark_message.callMethod(context, \"content_length\");\n\n if ( ! content_length.isNil()) {\n mark_content_length = RubyNumeric.num2int(content_length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n mark_message.callMethod(context, \"write_body\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action consume_null {\n ((mark_content_length != -1) && ((p - mark) < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || ((p - mark) < mark_content_length))\n }\n\n action check_message_size {\n mark_message_size += 1;\n if (mark_message_size > maxMessageSize) {\n RubyModule messageSizeExceeded = context.runtime.getClassFromPath(\"Stompede::Stomp::MessageSizeExceeded\");\n RubyException error = (RubyException) messageSizeExceeded.callMethod(\"new\");\n throw new RaiseException(error);\n }\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RubyException parseError;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n parseError = null;\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n if (parseError == null) {\n int p;\n byte data[] = null;\n byte bytes[] = ((RubyString) chunk).getBytes();\n\n if (state.chunk != null) {\n p = state.chunk.length;\n data = new byte[state.chunk.length + bytes.length];\n System.arraycopy(state.chunk, 0, data, 0, state.chunk.length);\n System.arraycopy(bytes, 0, data, state.chunk.length, bytes.length);\n } else {\n p = 0;\n data = bytes;\n }\n\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n if (mark != -1) {\n state.chunk = data;\n } else {\n state.chunk = null;\n }\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n IRubyObject args[] = { RubyString.newString(context.runtime, data), RubyFixnum.newFixnum(context.runtime, (long) p) };\n parseError = (RubyException) context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(context, \"build_parse_error\", args);\n }\n }\n\n if (parseError != null) {\n throw new RaiseException(parseError);\n }\n\n return context.nil;\n }\n}\n","old_contents":"package stompede.stomp;\n\nimport org.jruby.Ruby;\nimport org.jruby.RubyModule;\nimport org.jruby.RubyClass;\nimport org.jruby.RubyObject;\nimport org.jruby.RubyFixnum;\nimport org.jruby.RubyString;\nimport org.jruby.RubyNumeric;\nimport org.jruby.RubyException;\nimport org.jruby.exceptions.RaiseException;\n\nimport org.jruby.runtime.ThreadContext;\nimport org.jruby.runtime.builtin.IRubyObject;\nimport org.jruby.runtime.Block;\n\nimport org.jruby.anno.JRubyClass;\nimport org.jruby.anno.JRubyMethod;\n\n%%{\n machine message;\n\n action mark {\n mark = p;\n }\n\n action mark_message {\n mark_message = context.runtime.getClassFromPath(\"Stompede::Stomp::Message\").callMethod(\"new\", context.nil, context.nil);\n mark_message_size = 0;\n }\n\n action write_command {\n mark_message.callMethod(context, \"write_command\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action mark_key {\n mark_key = RubyString.newString(context.runtime, data, mark, p - mark);\n mark = -1;\n }\n\n action write_header {\n IRubyObject args[] = { mark_key, RubyString.newString(context.runtime, data, mark, p - mark) };\n mark_message.callMethod(context, \"write_header\", args);\n mark_key = null;\n mark = -1;\n }\n\n action finish_headers {\n IRubyObject content_length = mark_message.callMethod(context, \"content_length\");\n\n if ( ! content_length.isNil()) {\n mark_content_length = RubyNumeric.num2int(content_length);\n } else {\n mark_content_length = -1;\n }\n }\n\n action write_body {\n mark_message.callMethod(context, \"write_body\", RubyString.newString(context.runtime, data, mark, p - mark));\n mark = -1;\n }\n\n action consume_null {\n ((mark_content_length != -1) && ((p - mark) < mark_content_length))\n }\n\n action consume_octet {\n ((mark_content_length == -1) || ((p - mark) < mark_content_length))\n }\n\n action check_message_size {\n mark_message_size += 1;\n if (mark_message_size > maxMessageSize) {\n RubyModule messageSizeExceeded = context.runtime.getClassFromPath(\"Stompede::Stomp::MessageSizeExceeded\");\n RubyException error = (RubyException) messageSizeExceeded.callMethod(\"new\");\n throw new RaiseException(error);\n }\n }\n\n action finish_message {\n block.yield(context, mark_message);\n mark_message = null;\n }\n\n include message_common \"parser_common.rl\";\n}%%\n\n@JRubyClass(name=\"JavaParser\", parent=\"Object\")\npublic class JavaParser extends RubyObject {\n %% write data noprefix;\n\n private class State {\n public int cs = JavaParser.start;\n public byte[] chunk;\n public int mark = -1;\n public RubyString mark_key;\n public IRubyObject mark_message;\n public int mark_message_size = -1;\n public int mark_content_length = -1;\n }\n\n private RaiseException exception;\n private long maxMessageSize;\n private State state;\n\n public JavaParser(Ruby runtime, RubyClass klass) {\n super(runtime, klass);\n state = new State();\n }\n\n @JRubyMethod\n public IRubyObject initialize(ThreadContext context) {\n RubyModule mStomp = context.runtime.getClassFromPath(\"Stompede::Stomp\");\n return initialize(context, mStomp.callMethod(\"max_message_size\"));\n }\n\n @JRubyMethod(argTypes = {RubyFixnum.class})\n public IRubyObject initialize(ThreadContext context, IRubyObject maxMessageSize) {\n this.maxMessageSize = ((RubyFixnum) maxMessageSize).getLongValue();\n return context.nil;\n }\n\n @JRubyMethod(argTypes = {RubyString.class})\n public IRubyObject parse(ThreadContext context, IRubyObject chunk, Block block) {\n byte data[] = ((RubyString) chunk).getBytes();\n\n int p = 0;\n int pe = data.length;\n\n int cs = state.cs;\n int mark = state.mark;\n RubyString mark_key = state.mark_key;\n IRubyObject mark_message = state.mark_message;\n int mark_message_size = state.mark_message_size;\n int mark_content_length = state.mark_content_length;\n\n %% write exec;\n\n state.cs = cs;\n state.mark = mark;\n state.mark_key = mark_key;\n state.mark_message = mark_message;\n state.mark_message_size = mark_message_size;\n state.mark_content_length = mark_content_length;\n\n if (cs == error) {\n IRubyObject args[] = { RubyString.newString(context.runtime, data), RubyFixnum.newFixnum(context.runtime, (long) p) };\n RubyException error = (RubyException) context.runtime.getClassFromPath(\"Stompede::Stomp\").callMethod(context, \"build_parse_error\", args);\n throw new RaiseException(error);\n }\n\n return context.nil;\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"a5f09254a398bebc11de7e496acf10af099fa163","subject":"Don't try to prune SSA style spans if there's only one of them. (fixes crash on 0-byte subtitle lines)","message":"Don't try to prune SSA style spans if there's only one of them. (fixes crash on 0-byte subtitle lines)\n\ngit-svn-id: d8f21eb7283bfb39ebab2f8f9b4a259b233f9348@345 621663c8-3916-0410-8f58-edc14a8543d5\n","repos":"mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian","old_file":"SSATagParsing.m.rl","new_file":"SSATagParsing.m.rl","new_contents":"\/*\n * SSARenderCodec.m\n * Copyright (c) 2007 Perian Project\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nstatic void SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\nstatic void PruneEmptyStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\tsize_t style_count_new = 0;\n\tint i;\n\t\n\tif (re->style_count <= 1) return;\n\t\n\tfor (i = 0; i < re->style_count; i++) {\n\t\tif (re->styles[i]->range.length == 0) {\n\t\t\t[re->styles[i] release];\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n\nstatic void PruneIdenticalStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\t\n\tif (re->multipleruns || re->style_count <= 1) return;\n\n\tsize_t style_count_new = 1, remaining = re->style_count-1;\n\tint i=1;\n\t\n\t\n\tstyles_new[0] = re->styles[0];\n\t\n\twhile (remaining) {\n\t\tATSUStyleComparison asc;\n\t\tATSUCompareStyles(styles_new[style_count_new-1]->astyle,re->styles[i]->astyle,&asc);\n\t\t\n\t\tif (asc == kATSUStyleEquals) {\n\t\t\tstyles_new[style_count_new-1]->range.length += re->styles[i]->range.length;\n\t\t\t[re->styles[i] release];\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t\t\n\t\ti++;\n\t\tremaining--;\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n\nstatic void UpdateAlignment(int inum, int cur_posx, int *valign, int *halign, ATSUTextLayout cur_layout)\n{\n\tint cur_halign, cur_valign;\n\t\n\tswitch (inum) \n\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\n\tswitch (inum)\n\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\n\t*halign = cur_halign;\n\t*valign = cur_valign;\n\tFract alignment;\n\t\n\tif (cur_posx != -1) {\n\t\tswitch(cur_halign) {\n\t\t\tcase S_LeftAlign:\n\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\tbreak;\n\t\t\tcase S_CenterAlign: default:\n\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\tbreak;\n\t\t\tcase S_RightAlign: \n\t\t\t\talignment = FloatToFract(1.);\n\t\t}\n\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t} \n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i, j, pcount; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t\tpcount = 1;\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\t\n\tfor (i = 0; i < pcount; i++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:i] componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipleruns=NO;\n\t\tre->is_shape=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\t[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin = p, *strbegin = p, *skipbegin = p, *intbegin = p, *pb = p, *posbegin=p, *strparambegin=p;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow, cur_scalex = re->style->scalex, cur_scaley = re->style->scaley;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx=-1, cur_posy=-1;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\tCGAffineTransform matrix;\n\t\t\t\n\t\t\tunsigned long inum=0;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag=0, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineRotationTag, sizeof(Fixed), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tnum *= (72.\/96.); \/\/ scale from Windows 96dpi\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction ftrack {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUTrackingTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscalex {\n\t\t\t\t\tcur_scalex = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscaley {\n\t\t\t\t\tcur_scaley = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction strp_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(inum, cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\n\t\t\t\taction ssa_alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(SSA2ASSAlignment(inum), cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t\t\n\t\t\t\t\tFract alignment = FloatToFract(0);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondarycolor {\n\t\t\t\t\tcur_color.secondary = ParseColorTag(inum,cur_color.secondary.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primaryalpha {\n\t\t\t\t\tcur_color.primary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondaryalpha {\n\t\t\t\t\tcur_color.secondary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinealpha {\n\t\t\t\t\tcur_color.outline.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowalpha {\n\t\t\t\t\tcur_color.shadow.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\t[output appendString:@\"\\n\"];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\t[re increasestyles];\n\t\t\t\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n\t\t\t\t\tre->styles[re->style_count-1]->outline = cur_outline;\n\t\t\t\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\n\t\t\t\t\tre->styles[re->style_count-1]->astyle = cur_style;\n\t\t\t\t\tre->styles[re->style_count-1]->range = cur_range;\n\t\t\t\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\n\t\t\t\t\tre->styles[re->style_count-1]->color = cur_color;\n\t\t\t\t\tATSUCreateAndCopyStyle(cur_style,&cur_style);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[SSARenderEntity alloc] init];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipleruns = NO;\n\t\t\t\t\t\tnre->is_shape = re->is_shape;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction styleset {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t\tssastyleline *the_style = re->style;\n\t\t\t\t\tNSString *searchsn = [NSString stringWithCharacters:strparambegin length:p-strparambegin];\n\t\t\t\t\t\n\t\t\t\t\tif ([searchsn length] > 0) {\n\t\t\t\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\t\t\t\tif ([searchsn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\t\t\t\tthe_style = &ssa->styles[j]; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tATSUCopyAttributes(the_style->atsustyle,cur_style);\n\t\t\t\t\tcur_color = the_style->color;\n\t\t\t\t\tcur_outline = the_style->outline;\n\t\t\t\t\tcur_shadow = the_style->shadow;\n\t\t\t\t\tcur_posx = cur_posy = -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction skip_t_tag {\n\t\t\t\t\twhile (p != pe && *p != ')' && *p != '}') p++;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction draw_mode {\n\t\t\t\t\tre->is_shape = inum != 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (flag == '0' || flag == '1') flag = fl - '0';})? > {flag = 1;};\n\t\t\t\tnum_ = \"-\"? digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = \"-\"? (digit+) > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|\"fsp\" num %ftrack\n\t\t\t\t\t\t\t\t|\"fscx\" num %fscalex\n\t\t\t\t\t\t\t\t|\"fscy\" num %fscaley\n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > strp_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"a\" intnum %ssa_alignment\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"1c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"2c\" color %secondarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t|\"1a\" color %primaryalpha\n\t\t\t\t\t\t\t\t|\"2a\" color %secondaryalpha\n\t\t\t\t\t\t\t\t|\"3a\" color %outlinealpha\n\t\t\t\t\t\t\t\t|\"4a\" color %shadowalpha\n\t\t\t\t\t\t\t\t|(\"r\" [^\\\\}]* > strp_begin %styleset)\n\t\t\t\t\t\t\t\t|(\"fe\"|\"k\"|\"kf\"|\"K\"|\"ko\"|\"q\"|\"fr\"|\"fad\"|\"move\"|\"clip\"|\"o\") [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"p\" num %draw_mode\n\t\t\t\t\t\t\t\t#|\"t\" [^)}]* # enabling this crashes ragel\n\t\t\t\t\t\t\t\t|\"t(\" % skip_t_tag\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" cmd_specific ;\n\t\t\t\t\n\t\t\t\ttag = \"{\" ((cmd*) | ([^\\\\}]*)) \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nn];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | \n\t\t\t\t\t\t (tag > enter_tag % exit_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text :> special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (pb[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\n\t\t\tPruneEmptyStyleSpans(re);\n\t\t\tPruneIdenticalStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\t\n\treturn rentities;\n}","old_contents":"\/*\n * SSARenderCodec.m\n * Copyright (c) 2007 Perian Project\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nstatic void SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\nstatic void PruneEmptyStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\tsize_t style_count_new = 0;\n\tint i;\n\t\n\tfor (i = 0; i < re->style_count; i++) {\n\t\tif (re->styles[i]->range.length == 0) {\n\t\t\t[re->styles[i] release];\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n\nstatic void PruneIdenticalStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\tsize_t style_count_new = 1, remaining = re->style_count-1;\n\tint i=1;\n\t\n\tif (re->multipleruns) return;\n\t\n\tstyles_new[0] = re->styles[0];\n\t\n\twhile (remaining) {\n\t\tATSUStyleComparison asc;\n\t\tATSUCompareStyles(styles_new[style_count_new-1]->astyle,re->styles[i]->astyle,&asc);\n\t\t\n\t\tif (asc == kATSUStyleEquals) {\n\t\t\tstyles_new[style_count_new-1]->range.length += re->styles[i]->range.length;\n\t\t\t[re->styles[i] release];\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t\t\n\t\ti++;\n\t\tremaining--;\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n\nstatic void UpdateAlignment(int inum, int cur_posx, int *valign, int *halign, ATSUTextLayout cur_layout)\n{\n\tint cur_halign, cur_valign;\n\t\n\tswitch (inum) \n\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\n\tswitch (inum)\n\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\n\t*halign = cur_halign;\n\t*valign = cur_valign;\n\tFract alignment;\n\t\n\tif (cur_posx != -1) {\n\t\tswitch(cur_halign) {\n\t\t\tcase S_LeftAlign:\n\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\tbreak;\n\t\t\tcase S_CenterAlign: default:\n\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\tbreak;\n\t\t\tcase S_RightAlign: \n\t\t\t\talignment = FloatToFract(1.);\n\t\t}\n\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t} \n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i, j, pcount; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t\tpcount = 1;\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\t\n\tfor (i = 0; i < pcount; i++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:i] componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipleruns=NO;\n\t\tre->is_shape=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\t[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin = p, *strbegin = p, *skipbegin = p, *intbegin = p, *pb = p, *posbegin=p, *strparambegin=p;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow, cur_scalex = re->style->scalex, cur_scaley = re->style->scaley;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx=-1, cur_posy=-1;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\tCGAffineTransform matrix;\n\t\t\t\n\t\t\tunsigned long inum=0;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag=0, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineRotationTag, sizeof(Fixed), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tnum *= (72.\/96.); \/\/ scale from Windows 96dpi\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction ftrack {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUTrackingTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscalex {\n\t\t\t\t\tcur_scalex = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscaley {\n\t\t\t\t\tcur_scaley = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction strp_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(inum, cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\n\t\t\t\taction ssa_alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(SSA2ASSAlignment(inum), cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t\t\n\t\t\t\t\tFract alignment = FloatToFract(0);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondarycolor {\n\t\t\t\t\tcur_color.secondary = ParseColorTag(inum,cur_color.secondary.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primaryalpha {\n\t\t\t\t\tcur_color.primary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondaryalpha {\n\t\t\t\t\tcur_color.secondary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinealpha {\n\t\t\t\t\tcur_color.outline.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowalpha {\n\t\t\t\t\tcur_color.shadow.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\t[output appendString:@\"\\n\"];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\t[re increasestyles];\n\t\t\t\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n\t\t\t\t\tre->styles[re->style_count-1]->outline = cur_outline;\n\t\t\t\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\n\t\t\t\t\tre->styles[re->style_count-1]->astyle = cur_style;\n\t\t\t\t\tre->styles[re->style_count-1]->range = cur_range;\n\t\t\t\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\n\t\t\t\t\tre->styles[re->style_count-1]->color = cur_color;\n\t\t\t\t\tATSUCreateAndCopyStyle(cur_style,&cur_style);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[SSARenderEntity alloc] init];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipleruns = NO;\n\t\t\t\t\t\tnre->is_shape = re->is_shape;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction styleset {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t\tssastyleline *the_style = re->style;\n\t\t\t\t\tNSString *searchsn = [NSString stringWithCharacters:strparambegin length:p-strparambegin];\n\t\t\t\t\t\n\t\t\t\t\tif ([searchsn length] > 0) {\n\t\t\t\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\t\t\t\tif ([searchsn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\t\t\t\tthe_style = &ssa->styles[j]; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tATSUCopyAttributes(the_style->atsustyle,cur_style);\n\t\t\t\t\tcur_color = the_style->color;\n\t\t\t\t\tcur_outline = the_style->outline;\n\t\t\t\t\tcur_shadow = the_style->shadow;\n\t\t\t\t\tcur_posx = cur_posy = -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction skip_t_tag {\n\t\t\t\t\twhile (p != pe && *p != ')' && *p != '}') p++;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction draw_mode {\n\t\t\t\t\tre->is_shape = inum != 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (flag == '0' || flag == '1') flag = fl - '0';})? > {flag = 1;};\n\t\t\t\tnum_ = \"-\"? digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = \"-\"? (digit+) > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|\"fsp\" num %ftrack\n\t\t\t\t\t\t\t\t|\"fscx\" num %fscalex\n\t\t\t\t\t\t\t\t|\"fscy\" num %fscaley\n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > strp_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"a\" intnum %ssa_alignment\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"1c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"2c\" color %secondarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t|\"1a\" color %primaryalpha\n\t\t\t\t\t\t\t\t|\"2a\" color %secondaryalpha\n\t\t\t\t\t\t\t\t|\"3a\" color %outlinealpha\n\t\t\t\t\t\t\t\t|\"4a\" color %shadowalpha\n\t\t\t\t\t\t\t\t|(\"r\" [^\\\\}]* > strp_begin %styleset)\n\t\t\t\t\t\t\t\t|(\"fe\"|\"k\"|\"kf\"|\"K\"|\"ko\"|\"q\"|\"fr\"|\"fad\"|\"move\"|\"clip\"|\"o\") [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"p\" num %draw_mode\n\t\t\t\t\t\t\t\t#|\"t\" [^)}]* # enabling this crashes ragel\n\t\t\t\t\t\t\t\t|\"t(\" % skip_t_tag\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" cmd_specific ;\n\t\t\t\t\n\t\t\t\ttag = \"{\" ((cmd*) | ([^\\\\}]*)) \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nn];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | \n\t\t\t\t\t\t (tag > enter_tag % exit_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text :> special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (pb[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\n\t\t\tPruneEmptyStyleSpans(re);\n\t\t\tPruneIdenticalStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\t\n\treturn rentities;\n}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"00fc3db92da234e2b5f9855966f99c63cf86d932","subject":"add PF_UNSPEC, PF_INET, and PF_INET6 to assembler symbolic constants table","message":"add PF_UNSPEC, PF_INET, and PF_INET6 to assembler symbolic constants table\n","repos":"wahern\/dns,wahern\/dns","old_file":"src\/spf.rl","new_file":"src\/spf.rl","new_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009, 2010 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n#include \t\/* FILE *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (spf_unlikely(SPF_DEBUG > 0)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#if __GNUC__ >= 3\n#define spf_likely(e)\t__builtin_expect((e), 1)\n#define spf_unlikely(e)\t__builtin_expect((e), 0)\n#else\n#define spf_likely(e)\t(e)\n#define spf_unlikely(e)\t(e)\n#endif\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * V E R S I O N R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst char *spf_vendor(void) {\n\treturn SPF_VENDOR;\n} \/* spf_vendor() *\/\n\n\nint spf_v_rel(void) {\n\treturn SPF_V_REL;\n} \/* spf_v_rel() *\/\n\n\nint spf_v_abi(void) {\n\treturn SPF_V_ABI;\n} \/* spf_v_abi() *\/\n\n\nint spf_v_api(void) {\n\treturn SPF_V_API;\n} \/* spf_v_api() *\/\n\n\n\/*\n * E R R O R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase SPF_EQUERYLIMIT:\n\t\treturn \"SPF query limit reached\";\n\tcase SPF_ENOPOLICY:\n\t\treturn \"No SPF policy found\";\n\tcase SPF_EBADPOLICY:\n\t\treturn \"Invalid SPF policy\";\n\tdefault:\n\t\treturn dns_strerror(error);\n\t} \/* switch() *\/\n} \/* spf_strerror() *\/\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > i; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\nint spf_iresult(const char *result) {\n\tif (!strcasecmp(result, \"None\")) {\n\t\treturn SPF_NONE;\n\t} else if (!strcasecmp(result, \"Neutral\")) {\n\t\treturn SPF_NEUTRAL;\n\t} else if (!strcasecmp(result, \"Pass\")) {\n\t\treturn SPF_PASS;\n\t} else if (!strcasecmp(result, \"Fail\")) {\n\t\treturn SPF_FAIL;\n\t} else if (!strcasecmp(result, \"SoftFail\")) {\n\t\treturn SPF_SOFTFAIL;\n\t} else if (!strcasecmp(result, \"TempError\")) {\n\t\treturn SPF_TEMPERROR;\n\t} else if (!strcasecmp(result, \"PermError\")) {\n\t\treturn SPF_PERMERROR;\n\t} else {\n\t\treturn 0;\n\t}\n} \/* spf_iresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops { goto oops; }\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tmacros = 0;\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tmacros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_expand {\n\t\tmacros |= 1 << 30;\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\taction domain_putc {\n\t\tif (fc == '.' && lc == '.')\n\t\t\tgoto oops;\n\t\tsbuf_putc(&domain, fc);\n\t\tlc = fc;\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\t# `c', `r', and `t' not allowed in policy terms.\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | (\"%%\" | \"%_\" | \"%-\") @term_expand;\n\tmacro_string = (macro_expand | macro_literal)+;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) $domain_putc;\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) $domain_putc;\n\tip6_network = (xdigit | \":\" | \".\")+ $domain_putc;\n\n\tip4_cidr_length = \"\/\" >{ prefix4 = 32; } digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; if ((prefix4 += fc - '0') > 32) goto oops; };\n\tip6_cidr_length = \"\/\" >{ prefix6 = 128; } digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; if ((prefix6 += fc - '0') > 128) goto oops; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tBARE4 = ip4_network >ip4_begin ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | BARE4 | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tspf_macros_t macros = 0;\n\tint lc = '.';\n\tconst unsigned char *part;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error = 0;\n\n\treturn term->type;\noops:\n\t*error = SPF_EBADPOLICY;\n\n\tparser->error.lc = *parser->p;\n\n\tif (parser->p - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\tpart = parser->p - (sizeof parser->error.near \/ 2);\n\telse\n\t\tpart = parser->rdata;\n\n\tparser->error.lp = parser->p - part;\n\tparser->error.rp = parser->p - parser->rdata;\n\n\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\tif (SPF_DEBUG) {\n\t\tif (isgraph(parser->error.lc))\n\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\telse\n\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t}\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *helo, const char *sender) {\n\tstruct spf_sbuf mbox;\n\tstruct in_addr ip4;\n\tchar *local, *host;\n\n\tif (af == AF_INET6) {\n\t\tif (IN6_IS_ADDR_V4MAPPED(((struct in6_addr *)ip))) {\n\t\t\tip4.s_addr = (((struct in6_addr *)ip)->s6_addr[12] << 24U)\n\t\t\t | (((struct in6_addr *)ip)->s6_addr[13] << 16U)\n\t\t\t | (((struct in6_addr *)ip)->s6_addr[14] << 8U)\n\t\t\t | (((struct in6_addr *)ip)->s6_addr[15] << 0U);\n\t\t\tip4.s_addr = htonl(ip4.s_addr);\n\t\t\tip = &ip4;\n\t\t\tgoto ip4;\n\t\t}\n\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\nip4:\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tif (!helo || !*helo)\n\t\thelo = \"localhost\";\n\n\tif (sender && *sender) {\n\t\tsbuf_init(&mbox);\n\t\tsbuf_puts(&mbox, sender);\n\n\t\tif ((host = strchr(mbox.str, '@'))) {\n\t\t\t*host++ = '\\0';\n\n\t\t\tlocal = (mbox.str[0])? mbox.str : \"postmaster\";\n\t\t\thost = (*host)? host : (char *)helo;\n\t\t} else {\n\t\t\tlocal = mbox.str;\n\t\t\thost = (char *)helo;\n\t\t}\n\t} else {\n\t\tlocal = \"postmaster\";\n\t\thost = (char *)helo;\n\t}\n\n\tif (strchr(host, '['))\n\t\thost = (char *)helo;\n\n\tspf_strlcpy(env->d, host, sizeof env->d);\n\tspf_strlcpy(env->h, helo, sizeof env->h);\n\n\tspf_strlcpy(env->l, local, sizeof env->l);\n\tspf_strlcpy(env->o, host, sizeof env->o);\n\n\tsbuf_init(&mbox);\n\tsbuf_puts(&mbox, env->l);\n\tsbuf_putc(&mbox, '@');\n\tsbuf_puts(&mbox, env->o);\n\tspf_strlcpy(env->s, mbox.str, sizeof env->s);\n\n\tspf_strlcpy(env->p, \"unknown\", sizeof env->p);\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\nvoid spf_printenv(const struct spf_env *env, FILE *fp) {\n\tfprintf(fp, \"%%{s} : %s\\n\", env->s);\n\tfprintf(fp, \"%%{l} : %s\\n\", env->l);\n\tfprintf(fp, \"%%{o} : %s\\n\", env->o);\n\tfprintf(fp, \"%%{d} : %s\\n\", env->d);\n\tfprintf(fp, \"%%{i} : %s\\n\", env->i);\n\tfprintf(fp, \"%%{p} : %s\\n\", env->p);\n\tfprintf(fp, \"%%{v} : %s\\n\", env->v);\n\tfprintf(fp, \"%%{h} : %s\\n\", env->h);\n\tfprintf(fp, \"%%{c} : %s\\n\", env->c);\n\tfprintf(fp, \"%%{r} : %s\\n\", env->r);\n\tfprintf(fp, \"%%{t} : %s\\n\", env->t);\n} \/* spf_printenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tcase '_':\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = ' ';\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '%';\n\t\t\t++sp; ++dp;\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '2';\n\t\t\t++dp;\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '0';\n\t\t\t++dp;\n\n\t\t\tbreak;\n\t\tcase '%':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_ERROR,\t\/* 2\/0 Throw a PERMERROR or TEMPERROR S(-2) code, S(-1) exp *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_options opts;\n\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n\n\tstruct spf_info info;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (spf_unlikely(!(cond))) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic inline void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic inline int vm_indexof(struct spf_vm *vm, int p) {\n\tif (spf_likely(p < 0))\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic inline enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic inline intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic inline intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic inline intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic inline intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic inline int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n#define ERROR(sub) sub_emit((sub), OP_ERROR)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\tSPF_SAY(\"querying %s IN %s\", (char *)qname, dns_strtype(qtype));\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\tif (txt->len < sizeof \"v=spf1\" - 1)\n\t\treturn 0;\n\tif (strncasecmp((char *)txt->data, \"v=spf1\", 6))\n\t\treturn 0;\n\treturn txt->len == sizeof \"v=spf1\" - 1 || txt->data[6] == ' ';\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\tif (grep->type == -DNS_T_SPF && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/*\n\t\t\t * FIXME: This is a hack to pass the OpenSPF test\n\t\t\t * suite. Perhaps it would be better to pass a\n\t\t\t * length parameter to the caller.\n\t\t\t *\/\n\t\t\tif (memchr(any.txt.data, '\\0', any.txt.len)) {\n\t\t\t\tstruct spf_sbuf exp;\n\t\t\t\tsbuf_init(&exp);\n\t\t\t\tvm_assert(vm, dns_d_expand(exp.str, sizeof exp.str, 12, pkt, &error), EFAULT);\n\t\t\t\texp.end = strlen(exp.str);\n\t\t\t\tsbuf_puts(&exp, \" has embedded NUL\");\n\t\t\t\tspf_strlcpy(vm->spf->info.error.exp, exp.str, sizeof vm->spf->info.error.exp);\n\t\t\t\tvm_throw(vm, SPF_EBADPOLICY);\n\t\t\t}\n\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstruct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -4, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -3))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -3, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -3, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -2, T_INT);\n\thints.ai_family = vm_peek(vm, -1, T_INT);\n\n\tSPF_SAY(\"querying %s IN %s\", host, dns_strtype(qtype));\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 4);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/* Query #1\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tDUP(&sub);\n\tI8(&sub, vm->spf->opts.lookup[0]);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] domain\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, vm->spf->opts.lookup[0]);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for TXT v=spf1 or SPF *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tsub_jump(&sub, (vm->spf->opts.lookup[1])? 2 : 7);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ6(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\tif (!vm->spf->opts.lookup[1])\n\t\tgoto L6; \/* Skip Query #2 bytecode generation *\/\n\n\t\/* Query #2\n\t *\n\t * [-6] reset address\n\t * [-5] return address\n\t * [-4] domain\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL2(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tDUP(&sub);\n\tI8(&sub, vm->spf->opts.lookup[1]);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] domain\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, vm->spf->opts.lookup[1]);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for TXT v=spf1 or SPF *\/\n\tGREP(&sub);\n\tL3(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ6(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ3(&sub); \/* otherwise, continue looping *\/\n\n\t\/* Transfer\n\t * \n\t * [-6] reset address\n\t * [-5] return address\n\t * [-4] domain\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\nL6:\tL6(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/* Return None\n\t *\n\t * [-6] reset address\n\t * [-5] return address\n\t * [-4] domain\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L2 is for matches\n\t * L4 is the explanation (i.e. exp= or default).\n\t * L6 is to return\n\t * L7 is for failed includes\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, SPF_NONE);\n\t\t\tEQ(&sub);\n\t\t\tJ7(&sub); \/* no policy found *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tIN6(&sub, (intptr_t)&term.ip6.addr.s6_addr);\n\t\t\tI8(&sub, term.ip6.prefix);\n\t\t\tsub_emit(&sub, OP_IP6);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\tif (exp.type) {\n\t\t\t\tvm_assert(vm, spf_expand(vm->spf->info.error.exp, sizeof vm->spf->info.error.exp, &(spf_macros_t){ 0 }, \"multiple exp terms in %{d} policy\", &vm->spf->env, &error), error);\n\t\t\t\tvm_throw(vm, SPF_EBADPOLICY);\n\t\t\t}\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tif (redir.type) {\n\t\t\t\tvm_assert(vm, spf_expand(vm->spf->info.error.exp, sizeof vm->spf->info.error.exp, &(spf_macros_t){ 0 }, \"multiple redirect terms in %{d} policy\", &vm->spf->env, &error), error);\n\t\t\t\tvm_throw(vm, SPF_EBADPOLICY);\n\t\t\t}\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ2(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tstruct spf_sbuf exp;\n\t\tchar *p;\n\n\t\tvm->end = end;\n\t\tend = 0;\n\n\t\t\/*\n\t\t * Pretty print the parsing error.\n\t\t *\/\n\t\tsbuf_init(&exp);\n\t\tsbuf_puts(&exp, vm->spf->env.d);\n\t\tsbuf_puts(&exp, \" policy syntax error: `\");\n\n\t\tfor (p = parser.error.near; p < spf_endof(parser.error.near) && *p; p++) {\n\t\t\tif (p == &parser.error.near[parser.error.lp]) {\n\t\t\t\tsbuf_putc(&exp, '[');\n\t\t\t\tsbuf_putc(&exp, *p);\n\t\t\t\tsbuf_putc(&exp, ']');\n\t\t\t} else\n\t\t\t\tsbuf_putc(&exp, *p);\n\t\t}\n\n\t\tsbuf_putc(&exp, '\\'');\n\n\t\tspf_strlcpy(vm->spf->info.error.exp, exp.str, sizeof vm->spf->info.error.exp);\n\n\t\tvm_throw(vm, error);\n\t}\n\n\tif (redir.type) {\n\t\tI8(&sub, 'd');\n\t\tGETENV(&sub);\n\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tDUP(&sub);\n\t\tI8(&sub, 'd');\n\t\tSETENV(&sub);\n\n\t\tsub_emit(&sub, OP_CHECK);\n\n\t\tDUP(&sub);\n\t\tI8(&sub, SPF_NONE);\n\t\tEQ(&sub);\n\t\tJ7(&sub); \/* no policy found *\/\n\n\t\tI8(&sub, 3);\n\t\tNEG(&sub);\n\t\tMOVE(&sub);\n\t\tI8(&sub, 'd');\n\t\tSETENV(&sub);\n\n\t\tTRUE(&sub);\n\t\tJ6(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ4(&sub);\n\n\tL2(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL4(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ6(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&exp.domain[0]);\n\t\tif (exp.macros) {\n\t\t\tif (spf_isset(exp.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL6(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tL7(&sub);\n\tSTR(&sub, (intptr_t)\"no policy found for \");\n\tI8(&sub, 'd');\n\tGETENV(&sub);\n\tCAT(&sub);\n\tI32(&sub, abs(SPF_ENOPOLICY));\n\tNEG(&sub);\n\tSWAP(&sub);\n\tERROR(&sub);\n\tTRAP(&sub);\n\n\tsub_link(&sub);\n\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_ip6(struct spf_vm *vm) {\n\tstruct in6_addr *a, b;\n\tunsigned prefix;\n\tint match;\n\n\ta = (struct in6_addr *)vm_peek(vm, -2, T_REF|T_MEM);\n\tprefix = vm_peek(vm, -1, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"ip6\")) {\n\t\tspf_pto6(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_6cmp(a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip6() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (!strcmp(vm->spf->env.v, \"ip6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tI8(&sub, (!strcmp(vm->spf->env.v, \"ip6\"))? PF_INET6 : PF_INET);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, (!strcmp(vm->spf->env.v, \"ip6\"))? DNS_T_AAAA : DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (!strcmp(vm->spf->env.v, \"ip6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tI8(&sub, (!strcmp(vm->spf->env.v, \"ip6\"))? PF_INET6 : PF_INET);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic void op_error(struct spf_vm *vm) {\n\tint error = vm_peek(vm, -2, T_INT);\n\tchar *exp = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tspf_strlcpy(vm->spf->info.error.exp, (exp)? exp : \"\", sizeof vm->spf->info.error.exp);\n\n\tvm->pc++;\n\n\tvm_throw(vm, error);\n} \/* op_error() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_IP6] = { \"ip6\", &op_ip6, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puta, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_ERROR] = { \"error\", &op_error, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\nstatic const char *vm_strcode(int code) {\n\treturn vm_op[code].name;\n} \/* vm_strcode() *\/\n\nstatic int vm_icode(const char *name) {\n\tint code;\n\n\tfor (code = 0; code < (int)spf_lengthof(vm_op); code++) {\n\t\tif (vm_op[code].name && !strcasecmp(name, vm_op[code].name))\n\t\t\treturn code;\n\t}\n\n\treturn -1;\n} \/* vm_icode() *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (spf_unlikely(SPF_DEBUG >= 2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SPF_SAFELIMITS { .query = 10 }\n\nconst struct spf_limits spf_safelimits = SPF_SAFELIMITS;\n\nconst struct spf_options spf_defaults = {\n\t.limits = SPF_SAFELIMITS,\n\t.lookup = { SPF_RR_SPF, SPF_RR_TXT },\n}; \/* spf_defaults *\/\n\nstruct spf_resolver *spf_open(const struct spf_env *env, struct dns_resolver *res, const struct spf_options *opts, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (res)\n\t\tdns_res_acquire(res);\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->opts = (opts)? *opts : spf_defaults;\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (res) {\n\t\tspf->res = res; res = NULL;\n\t} else if (!(spf->res = dns_res_stub(NULL, &error)))\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tdns_res_close(res);\n\tspf_close(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm))) {\n\t\tswitch (error) {\n\t\tcase SPF_EQUERYLIMIT:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_ENOPOLICY:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_EBADPOLICY:\n\t\t\tspf->info.error.code = error;\n\t\t\tspf->result = SPF_PERMERROR;\n\n\t\t\treturn 0;\n\t\tdefault:\n\t\t\treturn error;\n\t\t}\n\t}\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nconst struct spf_info *spf_info(struct spf_resolver *spf) {\n\treturn &spf->info;\n} \/* spf_info() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nvoid spf_clear(struct spf_resolver *spf) {\n\treturn dns_res_clear(spf->res);\n} \/* spf_clear() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n#include \"cache.h\"\n\n\nstruct {\n\tconst char *resconf;\n\tconst char *cache;\n\tstruct dns_resolver *res;\n} MAIN;\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic struct dns_cache *mkcache(void) {\n#if SPF_CACHE\n\tstatic struct cache *cache;\n\tint error;\n\n\tif (cache)\n\t\treturn cache_resi(cache);\n\n\tif (!MAIN.cache)\n\t\treturn NULL;\n\n\tassert(cache = cache_open(&error));\n\n\tif ((error = cache_loadpath(cache, MAIN.cache, NULL, 0)))\n\t\tpanic(\"%s: %s\", MAIN.cache, strerror(error));\n\n\treturn cache_resi(cache);\n#else\n\treturn NULL;\n#endif\n} \/* mkcache() *\/\n\n\nstatic struct dns_resolv_conf *mkresconf(void) {\n\tstatic struct dns_resolv_conf *resconf;\n\tunsigned i;\n\tint error;\n\n\tif (resconf)\n\t\treturn resconf;\n\n\tif (MAIN.resconf) {\n\t\tassert(resconf = dns_resconf_open(&error));\n\n\t\tif ((error = dns_resconf_loadpath(resconf, MAIN.resconf)))\n\t\t\tpanic(\"%s: %s\", MAIN.resconf, strerror(error));\n\t} else {\n\t\tassert(resconf = dns_resconf_local(&error));\n\n\t\tresconf->lookup[2] = resconf->lookup[1];\n\t\tresconf->lookup[1] = resconf->lookup[0];\n\t\tresconf->lookup[0] = 'c';\n\t}\n\n\treturn resconf;\n} \/* mkresconf() *\/\n\n\nstatic struct dns_resolver *mkres(void) {\n\tint error;\n\n\tif (MAIN.res)\n\t\treturn MAIN.res;\n\n\tassert(MAIN.res = dns_res_open(mkresconf(), dns_hosts_mortal(dns_hosts_local(&error)), dns_hints_mortal(dns_hints_local(mkresconf(), &error)), mkcache(), dns_opts(), &error));\n\n\treturn MAIN.res;\n} \/* mkres() *\/\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6), VM_C(PF_UNSPEC),\n\t\tVM_C(PF_INET), VM_C(PF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, mkres(), NULL, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tif (*line) {\n\t\t\t\tif (-1 != (code = vm_icode(line))) {\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t\t} else\n\t\t\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t\t}\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, mkres(), NULL, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tspf_printenv(env, stdout);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -c PATH path to resolv.conf\\n\" \\\n\t\" -z PATH path to zone cache file\\n\" \\\n\t\" -W print version\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\n\nstatic void version(FILE *fp) {\n\tfprintf(fp, \"spf (spf.c) %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"vendor %s\\n\", spf_vendor());\n\tfprintf(fp, \"release %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"abi %.8X\\n\", spf_v_abi());\n\tfprintf(fp, \"api %.8X\\n\", spf_v_api());\n\tfprintf(fp, \"dns %.8X\\n\", dns_v_rel());\n} \/* version() *\/\n\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:c:z:vWh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tMAIN.resconf = optarg;\n\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\tMAIN.cache = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'W':\n\t\t\tversion(stdout);\n\n\t\t\treturn 0;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","old_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009, 2010 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n#include \t\/* FILE *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (spf_unlikely(SPF_DEBUG > 0)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#if __GNUC__ >= 3\n#define spf_likely(e)\t__builtin_expect((e), 1)\n#define spf_unlikely(e)\t__builtin_expect((e), 0)\n#else\n#define spf_likely(e)\t(e)\n#define spf_unlikely(e)\t(e)\n#endif\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * V E R S I O N R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst char *spf_vendor(void) {\n\treturn SPF_VENDOR;\n} \/* spf_vendor() *\/\n\n\nint spf_v_rel(void) {\n\treturn SPF_V_REL;\n} \/* spf_v_rel() *\/\n\n\nint spf_v_abi(void) {\n\treturn SPF_V_ABI;\n} \/* spf_v_abi() *\/\n\n\nint spf_v_api(void) {\n\treturn SPF_V_API;\n} \/* spf_v_api() *\/\n\n\n\/*\n * E R R O R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase SPF_EQUERYLIMIT:\n\t\treturn \"SPF query limit reached\";\n\tcase SPF_ENOPOLICY:\n\t\treturn \"No SPF policy found\";\n\tcase SPF_EBADPOLICY:\n\t\treturn \"Invalid SPF policy\";\n\tdefault:\n\t\treturn dns_strerror(error);\n\t} \/* switch() *\/\n} \/* spf_strerror() *\/\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > i; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\nint spf_iresult(const char *result) {\n\tif (!strcasecmp(result, \"None\")) {\n\t\treturn SPF_NONE;\n\t} else if (!strcasecmp(result, \"Neutral\")) {\n\t\treturn SPF_NEUTRAL;\n\t} else if (!strcasecmp(result, \"Pass\")) {\n\t\treturn SPF_PASS;\n\t} else if (!strcasecmp(result, \"Fail\")) {\n\t\treturn SPF_FAIL;\n\t} else if (!strcasecmp(result, \"SoftFail\")) {\n\t\treturn SPF_SOFTFAIL;\n\t} else if (!strcasecmp(result, \"TempError\")) {\n\t\treturn SPF_TEMPERROR;\n\t} else if (!strcasecmp(result, \"PermError\")) {\n\t\treturn SPF_PERMERROR;\n\t} else {\n\t\treturn 0;\n\t}\n} \/* spf_iresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops { goto oops; }\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tmacros = 0;\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tmacros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_expand {\n\t\tmacros |= 1 << 30;\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\taction domain_putc {\n\t\tif (fc == '.' && lc == '.')\n\t\t\tgoto oops;\n\t\tsbuf_putc(&domain, fc);\n\t\tlc = fc;\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\t# `c', `r', and `t' not allowed in policy terms.\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | (\"%%\" | \"%_\" | \"%-\") @term_expand;\n\tmacro_string = (macro_expand | macro_literal)+;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) $domain_putc;\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) $domain_putc;\n\tip6_network = (xdigit | \":\" | \".\")+ $domain_putc;\n\n\tip4_cidr_length = \"\/\" >{ prefix4 = 32; } digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; if ((prefix4 += fc - '0') > 32) goto oops; };\n\tip6_cidr_length = \"\/\" >{ prefix6 = 128; } digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; if ((prefix6 += fc - '0') > 128) goto oops; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tBARE4 = ip4_network >ip4_begin ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | BARE4 | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tspf_macros_t macros = 0;\n\tint lc = '.';\n\tconst unsigned char *part;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error = 0;\n\n\treturn term->type;\noops:\n\t*error = SPF_EBADPOLICY;\n\n\tparser->error.lc = *parser->p;\n\n\tif (parser->p - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\tpart = parser->p - (sizeof parser->error.near \/ 2);\n\telse\n\t\tpart = parser->rdata;\n\n\tparser->error.lp = parser->p - part;\n\tparser->error.rp = parser->p - parser->rdata;\n\n\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\tif (SPF_DEBUG) {\n\t\tif (isgraph(parser->error.lc))\n\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\telse\n\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t}\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *helo, const char *sender) {\n\tstruct spf_sbuf mbox;\n\tstruct in_addr ip4;\n\tchar *local, *host;\n\n\tif (af == AF_INET6) {\n\t\tif (IN6_IS_ADDR_V4MAPPED(((struct in6_addr *)ip))) {\n\t\t\tip4.s_addr = (((struct in6_addr *)ip)->s6_addr[12] << 24U)\n\t\t\t | (((struct in6_addr *)ip)->s6_addr[13] << 16U)\n\t\t\t | (((struct in6_addr *)ip)->s6_addr[14] << 8U)\n\t\t\t | (((struct in6_addr *)ip)->s6_addr[15] << 0U);\n\t\t\tip4.s_addr = htonl(ip4.s_addr);\n\t\t\tip = &ip4;\n\t\t\tgoto ip4;\n\t\t}\n\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\nip4:\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tif (!helo || !*helo)\n\t\thelo = \"localhost\";\n\n\tif (sender && *sender) {\n\t\tsbuf_init(&mbox);\n\t\tsbuf_puts(&mbox, sender);\n\n\t\tif ((host = strchr(mbox.str, '@'))) {\n\t\t\t*host++ = '\\0';\n\n\t\t\tlocal = (mbox.str[0])? mbox.str : \"postmaster\";\n\t\t\thost = (*host)? host : (char *)helo;\n\t\t} else {\n\t\t\tlocal = mbox.str;\n\t\t\thost = (char *)helo;\n\t\t}\n\t} else {\n\t\tlocal = \"postmaster\";\n\t\thost = (char *)helo;\n\t}\n\n\tif (strchr(host, '['))\n\t\thost = (char *)helo;\n\n\tspf_strlcpy(env->d, host, sizeof env->d);\n\tspf_strlcpy(env->h, helo, sizeof env->h);\n\n\tspf_strlcpy(env->l, local, sizeof env->l);\n\tspf_strlcpy(env->o, host, sizeof env->o);\n\n\tsbuf_init(&mbox);\n\tsbuf_puts(&mbox, env->l);\n\tsbuf_putc(&mbox, '@');\n\tsbuf_puts(&mbox, env->o);\n\tspf_strlcpy(env->s, mbox.str, sizeof env->s);\n\n\tspf_strlcpy(env->p, \"unknown\", sizeof env->p);\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\nvoid spf_printenv(const struct spf_env *env, FILE *fp) {\n\tfprintf(fp, \"%%{s} : %s\\n\", env->s);\n\tfprintf(fp, \"%%{l} : %s\\n\", env->l);\n\tfprintf(fp, \"%%{o} : %s\\n\", env->o);\n\tfprintf(fp, \"%%{d} : %s\\n\", env->d);\n\tfprintf(fp, \"%%{i} : %s\\n\", env->i);\n\tfprintf(fp, \"%%{p} : %s\\n\", env->p);\n\tfprintf(fp, \"%%{v} : %s\\n\", env->v);\n\tfprintf(fp, \"%%{h} : %s\\n\", env->h);\n\tfprintf(fp, \"%%{c} : %s\\n\", env->c);\n\tfprintf(fp, \"%%{r} : %s\\n\", env->r);\n\tfprintf(fp, \"%%{t} : %s\\n\", env->t);\n} \/* spf_printenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tcase '_':\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = ' ';\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '%';\n\t\t\t++sp; ++dp;\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '2';\n\t\t\t++dp;\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '0';\n\t\t\t++dp;\n\n\t\t\tbreak;\n\t\tcase '%':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_ERROR,\t\/* 2\/0 Throw a PERMERROR or TEMPERROR S(-2) code, S(-1) exp *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_options opts;\n\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n\n\tstruct spf_info info;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (spf_unlikely(!(cond))) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic inline void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic inline int vm_indexof(struct spf_vm *vm, int p) {\n\tif (spf_likely(p < 0))\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic inline enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic inline intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic inline intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic inline intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic inline intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic inline int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n#define ERROR(sub) sub_emit((sub), OP_ERROR)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\tSPF_SAY(\"querying %s IN %s\", (char *)qname, dns_strtype(qtype));\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\tif (txt->len < sizeof \"v=spf1\" - 1)\n\t\treturn 0;\n\tif (strncasecmp((char *)txt->data, \"v=spf1\", 6))\n\t\treturn 0;\n\treturn txt->len == sizeof \"v=spf1\" - 1 || txt->data[6] == ' ';\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\tif (grep->type == -DNS_T_SPF && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/*\n\t\t\t * FIXME: This is a hack to pass the OpenSPF test\n\t\t\t * suite. Perhaps it would be better to pass a\n\t\t\t * length parameter to the caller.\n\t\t\t *\/\n\t\t\tif (memchr(any.txt.data, '\\0', any.txt.len)) {\n\t\t\t\tstruct spf_sbuf exp;\n\t\t\t\tsbuf_init(&exp);\n\t\t\t\tvm_assert(vm, dns_d_expand(exp.str, sizeof exp.str, 12, pkt, &error), EFAULT);\n\t\t\t\texp.end = strlen(exp.str);\n\t\t\t\tsbuf_puts(&exp, \" has embedded NUL\");\n\t\t\t\tspf_strlcpy(vm->spf->info.error.exp, exp.str, sizeof vm->spf->info.error.exp);\n\t\t\t\tvm_throw(vm, SPF_EBADPOLICY);\n\t\t\t}\n\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstruct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -4, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -3))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -3, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -3, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -2, T_INT);\n\thints.ai_family = vm_peek(vm, -1, T_INT);\n\n\tSPF_SAY(\"querying %s IN %s\", host, dns_strtype(qtype));\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 4);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/* Query #1\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tDUP(&sub);\n\tI8(&sub, vm->spf->opts.lookup[0]);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] domain\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, vm->spf->opts.lookup[0]);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for TXT v=spf1 or SPF *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tsub_jump(&sub, (vm->spf->opts.lookup[1])? 2 : 7);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ6(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\tif (!vm->spf->opts.lookup[1])\n\t\tgoto L6; \/* Skip Query #2 bytecode generation *\/\n\n\t\/* Query #2\n\t *\n\t * [-6] reset address\n\t * [-5] return address\n\t * [-4] domain\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL2(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tDUP(&sub);\n\tI8(&sub, vm->spf->opts.lookup[1]);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] domain\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, vm->spf->opts.lookup[1]);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for TXT v=spf1 or SPF *\/\n\tGREP(&sub);\n\tL3(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ6(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ3(&sub); \/* otherwise, continue looping *\/\n\n\t\/* Transfer\n\t * \n\t * [-6] reset address\n\t * [-5] return address\n\t * [-4] domain\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\nL6:\tL6(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/* Return None\n\t *\n\t * [-6] reset address\n\t * [-5] return address\n\t * [-4] domain\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L2 is for matches\n\t * L4 is the explanation (i.e. exp= or default).\n\t * L6 is to return\n\t * L7 is for failed includes\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, SPF_NONE);\n\t\t\tEQ(&sub);\n\t\t\tJ7(&sub); \/* no policy found *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tIN6(&sub, (intptr_t)&term.ip6.addr.s6_addr);\n\t\t\tI8(&sub, term.ip6.prefix);\n\t\t\tsub_emit(&sub, OP_IP6);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\tif (exp.type) {\n\t\t\t\tvm_assert(vm, spf_expand(vm->spf->info.error.exp, sizeof vm->spf->info.error.exp, &(spf_macros_t){ 0 }, \"multiple exp terms in %{d} policy\", &vm->spf->env, &error), error);\n\t\t\t\tvm_throw(vm, SPF_EBADPOLICY);\n\t\t\t}\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tif (redir.type) {\n\t\t\t\tvm_assert(vm, spf_expand(vm->spf->info.error.exp, sizeof vm->spf->info.error.exp, &(spf_macros_t){ 0 }, \"multiple redirect terms in %{d} policy\", &vm->spf->env, &error), error);\n\t\t\t\tvm_throw(vm, SPF_EBADPOLICY);\n\t\t\t}\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ2(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tstruct spf_sbuf exp;\n\t\tchar *p;\n\n\t\tvm->end = end;\n\t\tend = 0;\n\n\t\t\/*\n\t\t * Pretty print the parsing error.\n\t\t *\/\n\t\tsbuf_init(&exp);\n\t\tsbuf_puts(&exp, vm->spf->env.d);\n\t\tsbuf_puts(&exp, \" policy syntax error: `\");\n\n\t\tfor (p = parser.error.near; p < spf_endof(parser.error.near) && *p; p++) {\n\t\t\tif (p == &parser.error.near[parser.error.lp]) {\n\t\t\t\tsbuf_putc(&exp, '[');\n\t\t\t\tsbuf_putc(&exp, *p);\n\t\t\t\tsbuf_putc(&exp, ']');\n\t\t\t} else\n\t\t\t\tsbuf_putc(&exp, *p);\n\t\t}\n\n\t\tsbuf_putc(&exp, '\\'');\n\n\t\tspf_strlcpy(vm->spf->info.error.exp, exp.str, sizeof vm->spf->info.error.exp);\n\n\t\tvm_throw(vm, error);\n\t}\n\n\tif (redir.type) {\n\t\tI8(&sub, 'd');\n\t\tGETENV(&sub);\n\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tDUP(&sub);\n\t\tI8(&sub, 'd');\n\t\tSETENV(&sub);\n\n\t\tsub_emit(&sub, OP_CHECK);\n\n\t\tDUP(&sub);\n\t\tI8(&sub, SPF_NONE);\n\t\tEQ(&sub);\n\t\tJ7(&sub); \/* no policy found *\/\n\n\t\tI8(&sub, 3);\n\t\tNEG(&sub);\n\t\tMOVE(&sub);\n\t\tI8(&sub, 'd');\n\t\tSETENV(&sub);\n\n\t\tTRUE(&sub);\n\t\tJ6(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ4(&sub);\n\n\tL2(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL4(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ6(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&exp.domain[0]);\n\t\tif (exp.macros) {\n\t\t\tif (spf_isset(exp.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL6(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tL7(&sub);\n\tSTR(&sub, (intptr_t)\"no policy found for \");\n\tI8(&sub, 'd');\n\tGETENV(&sub);\n\tCAT(&sub);\n\tI32(&sub, abs(SPF_ENOPOLICY));\n\tNEG(&sub);\n\tSWAP(&sub);\n\tERROR(&sub);\n\tTRAP(&sub);\n\n\tsub_link(&sub);\n\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_ip6(struct spf_vm *vm) {\n\tstruct in6_addr *a, b;\n\tunsigned prefix;\n\tint match;\n\n\ta = (struct in6_addr *)vm_peek(vm, -2, T_REF|T_MEM);\n\tprefix = vm_peek(vm, -1, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"ip6\")) {\n\t\tspf_pto6(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_6cmp(a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip6() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (!strcmp(vm->spf->env.v, \"ip6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tI8(&sub, (!strcmp(vm->spf->env.v, \"ip6\"))? PF_INET6 : PF_INET);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, (!strcmp(vm->spf->env.v, \"ip6\"))? DNS_T_AAAA : DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (!strcmp(vm->spf->env.v, \"ip6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tI8(&sub, (!strcmp(vm->spf->env.v, \"ip6\"))? PF_INET6 : PF_INET);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic void op_error(struct spf_vm *vm) {\n\tint error = vm_peek(vm, -2, T_INT);\n\tchar *exp = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tspf_strlcpy(vm->spf->info.error.exp, (exp)? exp : \"\", sizeof vm->spf->info.error.exp);\n\n\tvm->pc++;\n\n\tvm_throw(vm, error);\n} \/* op_error() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_IP6] = { \"ip6\", &op_ip6, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puta, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_ERROR] = { \"error\", &op_error, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\nstatic const char *vm_strcode(int code) {\n\treturn vm_op[code].name;\n} \/* vm_strcode() *\/\n\nstatic int vm_icode(const char *name) {\n\tint code;\n\n\tfor (code = 0; code < (int)spf_lengthof(vm_op); code++) {\n\t\tif (vm_op[code].name && !strcasecmp(name, vm_op[code].name))\n\t\t\treturn code;\n\t}\n\n\treturn -1;\n} \/* vm_icode() *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (spf_unlikely(SPF_DEBUG >= 2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SPF_SAFELIMITS { .query = 10 }\n\nconst struct spf_limits spf_safelimits = SPF_SAFELIMITS;\n\nconst struct spf_options spf_defaults = {\n\t.limits = SPF_SAFELIMITS,\n\t.lookup = { SPF_RR_SPF, SPF_RR_TXT },\n}; \/* spf_defaults *\/\n\nstruct spf_resolver *spf_open(const struct spf_env *env, struct dns_resolver *res, const struct spf_options *opts, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (res)\n\t\tdns_res_acquire(res);\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->opts = (opts)? *opts : spf_defaults;\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (res) {\n\t\tspf->res = res; res = NULL;\n\t} else if (!(spf->res = dns_res_stub(NULL, &error)))\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tdns_res_close(res);\n\tspf_close(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm))) {\n\t\tswitch (error) {\n\t\tcase SPF_EQUERYLIMIT:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_ENOPOLICY:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_EBADPOLICY:\n\t\t\tspf->info.error.code = error;\n\t\t\tspf->result = SPF_PERMERROR;\n\n\t\t\treturn 0;\n\t\tdefault:\n\t\t\treturn error;\n\t\t}\n\t}\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nconst struct spf_info *spf_info(struct spf_resolver *spf) {\n\treturn &spf->info;\n} \/* spf_info() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nvoid spf_clear(struct spf_resolver *spf) {\n\treturn dns_res_clear(spf->res);\n} \/* spf_clear() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n#include \"cache.h\"\n\n\nstruct {\n\tconst char *resconf;\n\tconst char *cache;\n\tstruct dns_resolver *res;\n} MAIN;\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic struct dns_cache *mkcache(void) {\n#if SPF_CACHE\n\tstatic struct cache *cache;\n\tint error;\n\n\tif (cache)\n\t\treturn cache_resi(cache);\n\n\tif (!MAIN.cache)\n\t\treturn NULL;\n\n\tassert(cache = cache_open(&error));\n\n\tif ((error = cache_loadpath(cache, MAIN.cache, NULL, 0)))\n\t\tpanic(\"%s: %s\", MAIN.cache, strerror(error));\n\n\treturn cache_resi(cache);\n#else\n\treturn NULL;\n#endif\n} \/* mkcache() *\/\n\n\nstatic struct dns_resolv_conf *mkresconf(void) {\n\tstatic struct dns_resolv_conf *resconf;\n\tunsigned i;\n\tint error;\n\n\tif (resconf)\n\t\treturn resconf;\n\n\tif (MAIN.resconf) {\n\t\tassert(resconf = dns_resconf_open(&error));\n\n\t\tif ((error = dns_resconf_loadpath(resconf, MAIN.resconf)))\n\t\t\tpanic(\"%s: %s\", MAIN.resconf, strerror(error));\n\t} else {\n\t\tassert(resconf = dns_resconf_local(&error));\n\n\t\tresconf->lookup[2] = resconf->lookup[1];\n\t\tresconf->lookup[1] = resconf->lookup[0];\n\t\tresconf->lookup[0] = 'c';\n\t}\n\n\treturn resconf;\n} \/* mkresconf() *\/\n\n\nstatic struct dns_resolver *mkres(void) {\n\tint error;\n\n\tif (MAIN.res)\n\t\treturn MAIN.res;\n\n\tassert(MAIN.res = dns_res_open(mkresconf(), dns_hosts_mortal(dns_hosts_local(&error)), dns_hints_mortal(dns_hints_local(mkresconf(), &error)), mkcache(), dns_opts(), &error));\n\n\treturn MAIN.res;\n} \/* mkres() *\/\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, mkres(), NULL, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tif (*line) {\n\t\t\t\tif (-1 != (code = vm_icode(line))) {\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t\t} else\n\t\t\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t\t}\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, mkres(), NULL, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tspf_printenv(env, stdout);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -c PATH path to resolv.conf\\n\" \\\n\t\" -z PATH path to zone cache file\\n\" \\\n\t\" -W print version\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\n\nstatic void version(FILE *fp) {\n\tfprintf(fp, \"spf (spf.c) %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"vendor %s\\n\", spf_vendor());\n\tfprintf(fp, \"release %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"abi %.8X\\n\", spf_v_abi());\n\tfprintf(fp, \"api %.8X\\n\", spf_v_api());\n\tfprintf(fp, \"dns %.8X\\n\", dns_v_rel());\n} \/* version() *\/\n\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:c:z:vWh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tMAIN.resconf = optarg;\n\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\tMAIN.cache = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'W':\n\t\t\tversion(stdout);\n\n\t\t\treturn 0;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"d61902cad46f6e21df402972da0f3625e0b30f04","subject":"ifchd: Better handle incomplete command buffers.","message":"ifchd: Better handle incomplete command buffers.\n\nBefore the handling would constantly acculmulate a prefix of previous\nincomplete commands. Now it still has a latent defect where the entire\nbuffer will be discarded given a spurious command, but ndhc shouldn't\ngenerate such commands so it shouldn't matter.\n","repos":"niklata\/ndhc","old_file":"src\/ifchd-parse.rl","new_file":"src\/ifchd-parse.rl","new_contents":"\/* ifchd-parse.rl - interface change daemon parser\n *\n * Copyright 2004-2018 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n\n#include \"ifchd-parse.h\"\n#include \"ifchd.h\"\n#include \"ifset.h\"\n#include \"ndhc.h\"\n\n%%{\n machine ipv4set_parser;\n\n action XSt { arg_start = p; }\n action IpEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_addr) {\n have_ip = true;\n memcpy(ip4_addr, arg_start, (size_t)arg_len);\n }\n ip4_addr[arg_len] = 0;\n }\n action SnEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_subnet) {\n have_subnet = true;\n memcpy(ip4_subnet, arg_start, (size_t)arg_len);\n }\n ip4_subnet[arg_len] = 0;\n }\n action BcEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_bcast) {\n have_ip = true;\n memcpy(ip4_bcast, arg_start, (size_t)arg_len);\n }\n ip4_bcast[arg_len] = 0;\n }\n\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip4_nobc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn);\n ip4_bc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn) ','\n (v4addr > XSt % BcEn);\n main := (ip4_bc|ip4_nobc);\n}%%\n\n%% write data;\n\nstatic int perform_ip4set(const char buf[static 1], size_t len)\n{\n char ip4_addr[INET_ADDRSTRLEN];\n char ip4_subnet[INET_ADDRSTRLEN];\n char ip4_bcast[INET_ADDRSTRLEN];\n const char *p = buf;\n const char *pe = p + len;\n const char *eof = pe;\n const char *arg_start = p;\n int cs = 0;\n bool have_ip = false;\n bool have_subnet = false;\n bool have_bcast = false;\n\n %% write init;\n %% write exec;\n\n if (cs < ipv4set_parser_first_final) {\n log_line(\"%s: received invalid arguments\", __func__);\n return -1;\n }\n\n \/\/ These should never trigger because of the above check, but be safe...\n if (!have_ip) {\n log_line(\"%s: No IPv4 address specified.\", __func__);\n return -1;\n }\n if (!have_subnet) {\n log_line(\"%s: No IPv4 subnet specified.\", __func__);\n return -1;\n }\n\n return perform_ip_subnet_bcast(ip4_addr, ip4_subnet,\n have_bcast ? ip4_bcast : (char *)0);\n}\n\n%%{\n machine ifchd_parser;\n\n action Reset { cl.state = STATE_NOTHING; }\n action ArgSt { arg_start = p; }\n action ArgEn {\n ptrdiff_t al = p - arg_start;\n if (al < 0 || (size_t)al > sizeof tb - 1) {\n log_line(\"command argument would overflow\");\n return -99;\n }\n arg_len = (size_t)al;\n memcpy(tb, arg_start, arg_len);\n tb[arg_len] = 0;\n }\n\n action Dispatch {\n int pr = 0;\n cmd_start = p + 1;\n switch (cl.state) {\n case STATE_IP4SET: pr = perform_ip4set(tb, arg_len); break;\n case STATE_TIMEZONE: pr = perform_timezone( tb, arg_len); break;\n case STATE_ROUTER: pr = perform_router(tb, arg_len); break;\n case STATE_DNS: pr = perform_dns(tb, arg_len); break;\n case STATE_LPRSVR: pr = perform_lprsvr(tb, arg_len); break;\n case STATE_HOSTNAME: pr = perform_hostname(tb, arg_len); break;\n case STATE_DOMAIN: pr = perform_domain(tb, arg_len); break;\n case STATE_IPTTL: pr = perform_ipttl(tb, arg_len); break;\n case STATE_MTU: pr = perform_mtu(tb, arg_len); break;\n case STATE_NTPSVR: pr = perform_ntpsrv(tb, arg_len); break;\n case STATE_WINS: pr = perform_wins(tb, arg_len); break;\n case STATE_CARRIER: pr = perform_carrier(); break;\n default:\n arg_len = 0;\n log_line(\"error: invalid state in dispatch_work\");\n return -99;\n }\n arg_len = 0;\n if (pr == -99)\n return -99;\n cmdf |= pr;\n }\n\n terminator = ';' > Dispatch;\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip_arg = (v4addr > ArgSt % ArgEn) terminator;\n ip4set_arg = (((v4addr ','){1,2} v4addr) > ArgSt % ArgEn) terminator;\n iplist_arg = (((v4addr ',')* v4addr) > ArgSt % ArgEn) terminator;\n str_arg = ([^;\\0]+ > ArgSt % ArgEn) terminator;\n s32_arg = (extend{4} > ArgSt % ArgEn) terminator;\n u16_arg = (extend{2} > ArgSt % ArgEn) terminator;\n u8_arg = (extend{1} > ArgSt % ArgEn) terminator;\n\n cmd_ip = ('routr:' % { cl.state = STATE_ROUTER; }) ip_arg;\n cmd_ip4set = ('ip4:' % { cl.state = STATE_IP4SET; }) ip4set_arg;\n cmd_iplist = ('dns:' % { cl.state = STATE_DNS; }\n |'lpr:' % { cl.state = STATE_LPRSVR; }\n |'ntp:' % { cl.state = STATE_NTPSVR; }\n |'wins:' % { cl.state = STATE_WINS; }\n ) iplist_arg;\n cmd_str = ('host:' % { cl.state = STATE_HOSTNAME; }\n |'dom:' % { cl.state = STATE_DOMAIN; }\n ) str_arg;\n cmd_s32 = ('tzone:' % { cl.state = STATE_TIMEZONE; }) s32_arg;\n cmd_u16 = ('mtu:' % { cl.state = STATE_MTU; }) u16_arg;\n cmd_u8 = ('ipttl:' % { cl.state = STATE_IPTTL; }) u8_arg;\n cmd_none = ('carrier:' % { cl.state = STATE_CARRIER; }) terminator;\n\n command = (cmd_ip|cmd_ip4set|cmd_iplist|cmd_str|cmd_s32|cmd_u16|cmd_u8|cmd_none);\n main := (command > Reset)+;\n}%%\n\n%% write data;\n\n\/*\n * Returns -99 on fatal error; that leads to peer connection being closed.\n * Returns -1 if one of the commands failed.\n * Returns 0 on success.\n *\/\nint execute_buffer(const char newbuf[static 1])\n{\n char buf[MAX_BUF * 2];\n char tb[MAX_BUF];\n int cmdf = 0;\n\n ssize_t buflen = snprintf(buf, sizeof buf, \"%s%s\", cl.ibuf, newbuf);\n memset(cl.ibuf, 0, sizeof cl.ibuf);\n if (buflen < 0) {\n log_line(\"%s: (%s) snprintf1 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)buflen >= sizeof buf) {\n log_line(\"%s: (%s) input is too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n\n const char *p = buf;\n const char *pe = p + strlen(buf);\n const char *arg_start = p;\n const char *cmd_start = p;\n size_t arg_len = 0;\n int cs = 0;\n\n %% write init;\n %% write exec;\n\n if (cs == ifchd_parser_error) {\n log_line(\"%s: (%s) ifch received invalid commands\",\n client_config.interface, __func__);\n return -99;\n }\n\n if (cmd_start != pe) {\n ssize_t ilen = snprintf(cl.ibuf, sizeof cl.ibuf, \"%s\", cmd_start);\n if (ilen < 0) {\n log_line(\"%s: (%s) snprintf2 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)ilen >= sizeof buf) {\n log_line(\"%s: (%s) unconsumed input too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n }\n\n return !cmdf ? 0 : -1;\n}\n\n","old_contents":"\/* ifchd-parse.rl - interface change daemon parser\n *\n * Copyright 2004-2018 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n\n#include \"ifchd-parse.h\"\n#include \"ifchd.h\"\n#include \"ifset.h\"\n#include \"ndhc.h\"\n\n%%{\n machine ipv4set_parser;\n\n action XSt { arg_start = p; }\n action IpEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_addr) {\n have_ip = true;\n memcpy(ip4_addr, arg_start, (size_t)arg_len);\n }\n ip4_addr[arg_len] = 0;\n }\n action SnEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_subnet) {\n have_subnet = true;\n memcpy(ip4_subnet, arg_start, (size_t)arg_len);\n }\n ip4_subnet[arg_len] = 0;\n }\n action BcEn {\n ptrdiff_t arg_len = p - arg_start;\n if (arg_len > 0 && (size_t)arg_len < sizeof ip4_bcast) {\n have_ip = true;\n memcpy(ip4_bcast, arg_start, (size_t)arg_len);\n }\n ip4_bcast[arg_len] = 0;\n }\n\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip4_nobc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn);\n ip4_bc = (v4addr > XSt % IpEn) ',' (v4addr > XSt % SnEn) ','\n (v4addr > XSt % BcEn);\n main := (ip4_bc|ip4_nobc);\n}%%\n\n%% write data;\n\nstatic int perform_ip4set(const char buf[static 1], size_t len)\n{\n char ip4_addr[INET_ADDRSTRLEN];\n char ip4_subnet[INET_ADDRSTRLEN];\n char ip4_bcast[INET_ADDRSTRLEN];\n const char *p = buf;\n const char *pe = p + len;\n const char *eof = pe;\n const char *arg_start = p;\n int cs = 0;\n bool have_ip = false;\n bool have_subnet = false;\n bool have_bcast = false;\n\n %% write init;\n %% write exec;\n\n if (cs < ipv4set_parser_first_final) {\n log_line(\"%s: received invalid arguments\", __func__);\n return -1;\n }\n\n \/\/ These should never trigger because of the above check, but be safe...\n if (!have_ip) {\n log_line(\"%s: No IPv4 address specified.\", __func__);\n return -1;\n }\n if (!have_subnet) {\n log_line(\"%s: No IPv4 subnet specified.\", __func__);\n return -1;\n }\n\n return perform_ip_subnet_bcast(ip4_addr, ip4_subnet,\n have_bcast ? ip4_bcast : (char *)0);\n}\n\n%%{\n machine ifchd_parser;\n\n action Reset { cl.state = STATE_NOTHING; }\n action ArgSt { arg_start = p; }\n action ArgEn {\n ptrdiff_t al = p - arg_start;\n if (al < 0 || (size_t)al > sizeof tb - 1) {\n log_line(\"command argument would overflow\");\n return -99;\n }\n arg_len = (size_t)al;\n memcpy(tb, arg_start, arg_len);\n tb[arg_len] = 0;\n }\n\n action Dispatch {\n int pr = 0;\n switch (cl.state) {\n case STATE_IP4SET: pr = perform_ip4set(tb, arg_len); break;\n case STATE_TIMEZONE: pr = perform_timezone( tb, arg_len); break;\n case STATE_ROUTER: pr = perform_router(tb, arg_len); break;\n case STATE_DNS: pr = perform_dns(tb, arg_len); break;\n case STATE_LPRSVR: pr = perform_lprsvr(tb, arg_len); break;\n case STATE_HOSTNAME: pr = perform_hostname(tb, arg_len); break;\n case STATE_DOMAIN: pr = perform_domain(tb, arg_len); break;\n case STATE_IPTTL: pr = perform_ipttl(tb, arg_len); break;\n case STATE_MTU: pr = perform_mtu(tb, arg_len); break;\n case STATE_NTPSVR: pr = perform_ntpsrv(tb, arg_len); break;\n case STATE_WINS: pr = perform_wins(tb, arg_len); break;\n case STATE_CARRIER: pr = perform_carrier(); break;\n default:\n arg_len = 0;\n log_line(\"error: invalid state in dispatch_work\");\n return -99;\n }\n arg_len = 0;\n if (pr == -99)\n return -99;\n cmdf |= pr;\n }\n\n terminator = ';' > Dispatch;\n v4addr = digit{1,3} '.' digit{1,3} '.' digit{1,3} '.' digit{1,3};\n ip_arg = (v4addr > ArgSt % ArgEn) terminator;\n ip4set_arg = (((v4addr ','){1,2} v4addr) > ArgSt % ArgEn) terminator;\n iplist_arg = (((v4addr ',')* v4addr) > ArgSt % ArgEn) terminator;\n str_arg = ([^;\\0]+ > ArgSt % ArgEn) terminator;\n s32_arg = (extend{4} > ArgSt % ArgEn) terminator;\n u16_arg = (extend{2} > ArgSt % ArgEn) terminator;\n u8_arg = (extend{1} > ArgSt % ArgEn) terminator;\n\n cmd_ip = ('routr:' % { cl.state = STATE_ROUTER; }) ip_arg;\n cmd_ip4set = ('ip4:' % { cl.state = STATE_IP4SET; }) ip4set_arg;\n cmd_iplist = ('dns:' % { cl.state = STATE_DNS; }\n |'lpr:' % { cl.state = STATE_LPRSVR; }\n |'ntp:' % { cl.state = STATE_NTPSVR; }\n |'wins:' % { cl.state = STATE_WINS; }\n ) iplist_arg;\n cmd_str = ('host:' % { cl.state = STATE_HOSTNAME; }\n |'dom:' % { cl.state = STATE_DOMAIN; }\n ) str_arg;\n cmd_s32 = ('tzone:' % { cl.state = STATE_TIMEZONE; }) s32_arg;\n cmd_u16 = ('mtu:' % { cl.state = STATE_MTU; }) u16_arg;\n cmd_u8 = ('ipttl:' % { cl.state = STATE_IPTTL; }) u8_arg;\n cmd_none = ('carrier:' % { cl.state = STATE_CARRIER; }) terminator;\n\n command = (cmd_ip|cmd_ip4set|cmd_iplist|cmd_str|cmd_s32|cmd_u16|cmd_u8|cmd_none);\n main := (command > Reset)+;\n}%%\n\n%% write data;\n\n\/*\n * Returns -99 on fatal error; that leads to peer connection being closed.\n * Returns -1 if one of the commands failed.\n * Returns 0 on success.\n *\/\nint execute_buffer(const char newbuf[static 1])\n{\n char buf[MAX_BUF * 2];\n char tb[MAX_BUF];\n int cmdf = 0;\n\n ssize_t buflen = snprintf(buf, sizeof buf, \"%s%s\", cl.ibuf, newbuf);\n if (buflen < 0) {\n log_line(\"%s: (%s) snprintf1 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)buflen >= sizeof buf) {\n log_line(\"%s: (%s) input is too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n\n const char *p = buf;\n const char *pe = p + strlen(buf);\n const char *arg_start = p;\n size_t arg_len = 0;\n int cs = 0;\n\n %% write init;\n %% write exec;\n\n if (p != pe) {\n ssize_t ilen = snprintf(cl.ibuf, sizeof cl.ibuf, \"%s\", p);\n if (ilen < 0) {\n log_line(\"%s: (%s) snprintf2 failed; your system is broken?\",\n client_config.interface, __func__);\n return -99;\n }\n if ((size_t)ilen >= sizeof buf) {\n log_line(\"%s: (%s) unconsumed input too long for buffer\",\n client_config.interface, __func__);\n return -99;\n }\n }\n\n if (cs < ifchd_parser_first_final) {\n log_line(\"%s: ifch received invalid commands\",\n client_config.interface);\n return -99;\n }\n return !cmdf ? 0 : -1;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"04c24aca999f90831e40666ca26bdd5232116320","subject":"[mtocpp_post] added quiet flag","message":"[mtocpp_post] added quiet flag\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/postprocess.rl","new_file":"src\/postprocess.rl","new_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\/\/ New for directory recursion\n#ifdef WIN32\n\t#include \n#else\n\t#include \n#endif\n\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n if (!quiet)\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p);\n if (!quiet)\n cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # bugfix: allow '>' in the end of typenames for Daniel's generic types\n ('<' . [^&]* . '>') => { fout.write(ts, te-ts); };\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US) => { fout.write(ts, te-ts); };\n\n '_m_tsbus_cotm_' => { fout << \">\"; fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n ('::mtoc_subst_') => { fout << '.'; fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:.,;_\\t])+ => { fout.write(ts, te-ts); };\n\n (')=0') => { fout << \")\"; };\n\n # word separators\n ([\\n <>()[\\]{}\\t:.;,_\\&]) => {fout << *ts;};\n\n # a single dot stays a dot\n ('.') => {fout << '.';};\n *|;\n}%%\n\nclass PostProcess {\n\nprivate:\n string docdir_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n bool quiet_;\n\npublic:\n \/**\n * @class PostProcess\n *\n * @change{1,2,dw,2011-11-04} Changed the postprocessor interface from taking a single file argument to\n * assuming the passed string to be a folder whos contents are to be postprocessed.\n *\/\n \/\/ constructor\n PostProcess(const string &docdir, const bool quiet_flag) :\n docdir_(docdir),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false),\n quiet_(quiet_flag)\n { }\n\n int execute()\n {\n DIR *dp;\n if ((dp = opendir(docdir_.c_str())) == NULL) {\n cerr << \"Error opening directory \" << docdir_ << endl;\n return -1;\n }\n\n struct dirent* dirp;\n string file;\n while ((dirp = readdir(dp)) != NULL) {\n file = string(dirp->d_name);\n \/\/ Process only html files\n if (file.substr(file.find_last_of(\".\") + 1) == \"html\" && file.find(\"8rl\") == string::npos) {\n postprocess(docdir_ + string(\"\/\") + file);\n }\n }\n closedir(dp);\n return 0;\n }\n\n \/\/ run postprocessor\n int postprocess(string file)\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try {\n is.open(file.c_str());\n } catch (std::ifstream::failure e) {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char* buf = new char[(int)(1.1*length)];\n char* p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n \n ofstream fout;\n try {\n fout.open(file.c_str(), ios_base::trunc);\n } catch (std::ofstream::failure e) {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << file << \": PARSE ERROR \" << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n};\n\nvoid usage()\n{\n cout << \"mtocpp_post Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: mtocpp_post [-q] filename\" << endl;\n cout << \"\\nOptions:\\n -q\\t\\tsuppresses debug output.\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n bool quiet = false;\n string docdir;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n if (argc == 3 && std::string(\"-q\") == std::string(argv[1]))\n {\n quiet = true;\n docdir = argv[2];\n }\n else if(argc == 2)\n docdir = argv[1];\n else\n {\n cerr << \"wrong arguments!\" << endl;\n usage();\n exit(-2);\n }\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n usage();\n exit(-2);\n }\n\n if (!quiet)\n cout << \"Running mtoc++ postprocessor on directory \" << docdir << endl;\n\n PostProcess scanner(docdir, quiet);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","old_contents":"#include \"config.h\"\n\n#include \n#include \n#include \n#include \n\/\/ New for directory recursion\n#ifdef WIN32\n\t#include \n#else\n\t#include \n#endif\n\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::ios_base;\nusing std::endl;\n\n%%{\n machine PostProcess;\n write data;\n\n # end of file character\n EOF = 0;\n\n # all but end of file character\n default = ^0;\n\n # end of line\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # matlab identifier\n IDENT = [A-Z\\\\a-z\\-_][A-Z\\\\a-z0-9\\-_]*;\n\n # matlab ifdentifier without underscore characters\n IDENT_WO_US = [A-Z\\\\a-z\\-][A-Z\\\\a-z0-9\\-]*;\n\n ANY_TAG = '<' . [^>]* . '>';\n\n action echo {\n fout << fpc;\n cout << fpc;\n }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok { fout.write(tmp_p, p - tmp_p); cout.write(tmp_p, p-tmp_p); }\n\n rettype:= |*\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>\\&:,\\t])+ => { fout.write(ts, te-ts); };\n\n # word separators\n ([\\n <>\\&:\\t]) => {fout << *ts;};\n\n # bugfix: allow '>' in the end of typenames for Daniel's generic types\n ('<' . [^&]* . '>') => { fout.write(ts, te-ts); };\n\n # comma or > end the type\n (',') => { fhold; fret; };\n ('>') => { p -=4; fret; };\n *|;\n\n # reconstruct return values\n retval:= |*\n ('<' . ('::')?) => { fcall rettype; };\n\n # matlab identifier (1 return value)\n# ('<' . (default - [,&])*) => { cerr.write(ts+4, te - ts-4); cerr << std::endl; fout.write(ts+4, te - ts-4); };\n\n (',' . (default - '\\&')*) => { fout << \" \"; fout.write(ts+1, te-ts-1); fout << \"<\/span>\"; };\n\n # end of return value\n ('>') => {\n if(only_retval) { fout << \" =\"; }\n fret;\n };\n\n # white spaces\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n\n # typebreak\n ('
') => {};\n\n # other tags\n #(ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n retvals := |*\n\n ('<') => {};\n\n ('mlhsInnerSubst') => { fcall retval; };\n\n ('>') => { fout << \"] =\"; fgoto main; };\n\n # white spaces and commata\n ([ \\t\\n]*) => { fout.write(ts, te - ts); };\n ('
' . [ \\t\\n]* . ',') => { fout << \",
\\n\"; };\n (',') => { fout << \", \"; };\n\n # other tags\n (ANY_TAG) => { fout.write(ts, te-ts); };\n\n *|;\n\n # function name\n mtocsubst:= |*\n '_';\n\n (IDENT_WO_US) => { fout.write(ts, te-ts); };\n\n '_m_tsbus_cotm_' => { fout << \">\"; fgoto main; };\n *|;\n\n main:= |*\n # list of return values\n ('mlhsSubst') => { fout << \"function [\"; only_retval = false; fgoto retvals; };\n\n # one return value\n ('mlhsInnerSubst') => { fout << \"function \"; only_retval = true; fcall retval; fout << \" =\"; };\n\n # no return values\n ('noret::substitute') => {fout << \"function \";};\n\n # function name\n ('mtoc_subst_') => { fgoto mtocsubst; };\n ('::mtoc_subst_') => { fout << '.'; fgoto mtocsubst; };\n\n # matlab is typeless, so discard the type\n ('matlabtypesubstitute') => {fout << \" \";};\n\n # remove leading \"::\" (global namespace identifier)\n ([(,>] . '::') => { fout.write(ts, 1); fout << \" \"; };\n ('<' . '::') => { fout.write(ts, 4); fout << \" \";};\n\n # replace all \"::\" by \".\"\n ('::' . [A-Z\\\\a-z\\-_]) => { fout << '.' << *(te-1); };\n\n # a word\n (any - [\\n <>()[\\]{}\\&:.,;_\\t])+ => { fout.write(ts, te-ts); };\n\n (')=0') => { fout << \")\"; };\n\n # word separators\n ([\\n <>()[\\]{}\\t:.;,_\\&]) => {fout << *ts;};\n\n # a single dot stays a dot\n ('.') => {fout << '.';};\n *|;\n}%%\n\nclass PostProcess {\n\nprivate:\n string docdir_;\n int line , col;\n char *ts , *te;\n int act , have;\n int cs;\n int top;\n int stack[5];\n bool only_retval;\n\npublic:\n \/**\n * @class PostProcess\n *\n * @change{1,2,dw,2011-11-04} Changed the postprocessor interface from taking a single file argument to\n * assuming the passed string to be a folder whos contents are to be postprocessed.\n *\/\n \/\/ constructor\n PostProcess(const string &docdir) :\n docdir_(docdir),\n line(1),\n ts(0), te(0), have(0),\n top(0), only_retval(false)\n { }\n\n int execute()\n {\n DIR *dp;\n if ((dp = opendir(docdir_.c_str())) == NULL) {\n cerr << \"Error opening directory \" << docdir_ << endl;\n return -1;\n }\n\n struct dirent* dirp;\n string file;\n while ((dirp = readdir(dp)) != NULL) {\n file = string(dirp->d_name);\n \/\/ Process only html files\n if (file.substr(file.find_last_of(\".\") + 1) == \"html\" && file.find(\"8rl\") == string::npos) {\n postprocess(docdir_ + string(\"\/\") + file);\n }\n }\n closedir(dp);\n return 0;\n }\n\n \/\/ run postprocessor\n int postprocess(string file)\n {\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n ifstream is;\n try {\n is.open(file.c_str());\n } catch (std::ifstream::failure e) {\n cerr << \"Exception opening\/reading file\";\n exit(-1);\n }\n\n is.seekg(0, ios_base::end);\n int length = is.tellg();\n is.seekg(0, ios_base::beg);\n\n char* buf = new char[(int)(1.1*length)];\n char* p = buf;\n\/\/ char * tmp_p = p;\n\n is.read(buf, length);\n is.close();\n \n ofstream fout;\n try {\n fout.open(file.c_str(), ios_base::trunc);\n } catch (std::ofstream::failure e) {\n cerr << \"Exception opening\/writing file\";\n exit(-1);\n }\n\n int len = is.gcount();\n char *pe = p + len;\n char *eof = pe;\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == PostProcess_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << file << \": PARSE ERROR \" << endl;\n cerr.write(p, 100);\n exit(-1);\n }\n\n fout.close();\n delete buf;\n\n return 0;\n }\n};\n\nvoid usage()\n{\n cout << \"postprocess Version \" << MTOCPP_VERSION_MAJOR << \".\"\n << MTOCPP_VERSION_MINOR << endl;\n cout << \"Usage: .\/postprocess filename\" << endl;\n}\n\nint main(int argc, char ** argv)\n{\n string docdir;\n if(argc >= 2)\n {\n if (std::string(\"--help\") == std::string(argv[1]))\n {\n usage();\n return 0;\n }\n docdir = argv[1];\n }\n else\n {\n cerr << \"wrong number of arguments!\" << endl;\n exit(-2);\n }\n\n cout << \"Running mtoc++ postprocessor on directory \" << docdir << endl;\n \n PostProcess scanner(docdir);\n scanner.execute();\n return 0;\n}\n\n\/* vim: set et sw=2 ft=ragel: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"406504ed2fe1cb5b624e2d4f693521561249c3b6","subject":"Works","message":"Works\n","repos":"CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf,gusevfe\/bioruby-vcf,CuppenResearch\/bioruby-vcf,pjotrp\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = [a-zA-Z][a-zA-Z_]+; \n string = [\"][^\"]*[\"];\n boolean = '.';\n id_kw = 'ID'|'Number';\n\n action call_key { fcall key ; }\n action call_value {}\n\n n := ( identifier );\n\n key := |*\n 'ID' => {\n emit(:identifier, data, token_array, ts, te) \n };\n *|;\n\n # parser\n main := ( ('<'|',') @call_key '=' @call_value )+ ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data.pack(\"c*\")[ts...te] }\nend\n\ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n \n %% write init;\n %% write exec;\n\n p token_array\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n# run_lexer(\"value = -2.00\")\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s.sub(\/^##(FORMAT|INFO)=\/,'')) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\n # key := (\n \n # integer => { \n # emit(:integer_literal, data, token_array, ts, te) \n # };\n \n # float => { \n # emit(:float_literal, data, token_array, ts, te) \n # };\n \n # assignment => { \n # emit(:assignment_operator, data, token_array, ts, te) \n # };\n \n # boolean => { \n # emit(:boolean, data, token_array, ts, te) \n # };\n \n # identifier => { \n # emit(:identifier, data, token_array, ts, te) \n # };\n\n # string => { \n # emit(:string, data, token_array, ts, te) \n # };\n \n # space|',';\n \n # );\n\n","old_contents":"# Parser for VCF-header info and format fields\n\n=begin\n%%{\n\n machine simple_lexer;\n \n integer = ('+'|'-')?[0-9]+;\n float = ('+'|'-')?[0-9]+'.'[0-9]+;\n assignment = '=';\n identifier = [a-zA-Z][a-zA-Z_]+; \n string = [\"][^\"]*[\"];\n boolean = '.';\n id_kw = 'ID'|'Number';\n\n action call_pairs { fcall pairs ; }\n\n pairs := |*\n 'ID=' identifier => {\n emit(:identifier, data, token_array, ts, te) \n };\n *|;\n\n # parser\n main := '<' @call_pairs ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef emit(token_name, data, target_array, ts, te)\n target_array << {:name => token_name.to_sym, :value => data.pack(\"c*\")[ts...te] }\nend\n\ndef run_lexer(data)\n p data\n data = data.unpack(\"c*\") if(data.is_a?(String))\n eof = data.length\n token_array = []\n stack = []\n \n %% write init;\n %% write exec;\n\n p token_array\n token_array.each do | h |\n p h\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\nend\n\n# run_lexer(\"value = -2.00\")\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s| run_lexer(s.sub(\/^##(FORMAT|INFO)=\/,'')) }\n\ncmd=ARGV.shift\nrun_lexer(cmd)\n\n # key := (\n \n # integer => { \n # emit(:integer_literal, data, token_array, ts, te) \n # };\n \n # float => { \n # emit(:float_literal, data, token_array, ts, te) \n # };\n \n # assignment => { \n # emit(:assignment_operator, data, token_array, ts, te) \n # };\n \n # boolean => { \n # emit(:boolean, data, token_array, ts, te) \n # };\n \n # identifier => { \n # emit(:identifier, data, token_array, ts, te) \n # };\n\n # string => { \n # emit(:string, data, token_array, ts, te) \n # };\n \n # space|',';\n \n # );\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"cac0b47597dc66a45afae67f9995cea2a9d7751c","subject":"Really change license header","message":"Really change license header\n\n90de8af corrected the license header in the generated C file rather than\nthe Ragel source (I need to add an \"rl\" filetype to Ack so that I won't\noverlook this kind of thing in the future).\n\nSigned-off-by: Wincent Colaiuta \n","repos":"geni\/wikitext,wincent\/wikitext,geni\/wikitext,barnaclebarnes\/wikitext,barnaclebarnes\/wikitext,barnaclebarnes\/wikitext,geni\/wikitext,wincent\/wikitext","old_file":"ext\/wikitext_ragel.rl","new_file":"ext\/wikitext_ragel.rl","new_contents":"\/\/ Copyright 2008-2009 Wincent Colaiuta. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/----------------------------------------------------------------------\/\/\n\/\/ NOTE: wikitext_ragel.c is generated from wikitext_ragel.rl, so \/\/\n\/\/ if you make changes to the former they will be overwritten. \/\/\n\/\/ You should perform all your edits in wikitext_ragel.rl. \/\/\n\/\/----------------------------------------------------------------------\/\/\n\n#include \"wikitext_ragel.h\"\n#include \"wikitext.h\"\n#include \n\n#define EMIT(t) do { out->type = t; out->stop = p + 1; out->column_stop += (out->stop - out->start); } while (0)\n#define MARK() do { mark = p; } while (0)\n#define REWIND() do { p = mark; } while (0)\n#define AT_END() (p + 1 == pe)\n#define DISTANCE() (p + 1 - ts)\n#define NEXT_CHAR() (*(p + 1))\n\n%%{\n machine wikitext;\n\n action mark\n {\n MARK();\n }\n\n action non_printable_ascii\n {\n out->code_point = *p & 0x7f;\n }\n\n action two_byte_utf8_sequence\n {\n out->code_point = ((uint32_t)(*(p - 1)) & 0x1f) << 6 |\n (*p & 0x3f);\n }\n\n action three_byte_utf8_sequence\n {\n out->code_point = ((uint32_t)(*(p - 2)) & 0x0f) << 12 |\n ((uint32_t)(*(p - 1)) & 0x3f) << 6 |\n (*p & 0x3f);\n }\n\n action four_byte_utf8_sequence\n {\n out->code_point = ((uint32_t)(*(p - 3)) & 0x07) << 18 |\n ((uint32_t)(*(p - 2)) & 0x3f) << 12 |\n ((uint32_t)(*(p - 1)) & 0x3f) << 6 |\n (*p & 0x3f);\n }\n\n # simple approximation for matching email addresses; not quite RFC 2822!\n user = (alnum | [_\\.] | '-')+ ;\n tld = alpha{2,5} ;\n domain = (alnum+ '.')+ tld ;\n mail = user '@' domain ;\n\n uri_chars = (alnum | [@$&'(\\*\\+=%_~\/#] | '-')+ ;\n special_uri_chars = ([:!\\(\\),;\\.\\?])+ ;\n uri = ('mailto:'i mail) |\n (('http'i [sS]? ':\/\/' | 'ftp:\/\/'i | 'svn:\/\/'i) uri_chars (special_uri_chars uri_chars)*) ;\n path = '\/' ([a-zA-Z0-9_\\-.]+ '\/'?)* ;\n\n main := |*\n\n ''i\n {\n EMIT(NO_WIKI_START);\n fbreak;\n };\n\n '<\/nowiki>'i\n {\n EMIT(NO_WIKI_END);\n fbreak;\n };\n\n '

'i\n        {\n            EMIT(PRE_START);\n            fbreak;\n        };\n\n        '<\/pre>'i\n        {\n            EMIT(PRE_END);\n            fbreak;\n        };\n\n        '
'i\n {\n EMIT(BLOCKQUOTE_START);\n fbreak;\n };\n\n '<\/blockquote>'i\n {\n EMIT(BLOCKQUOTE_END);\n fbreak;\n };\n\n \"'\"{1,5}\n {\n if (DISTANCE() == 5)\n EMIT(STRONG_EM);\n else if (DISTANCE() == 4)\n {\n p--;\n EMIT(STRONG_EM);\n }\n else if (DISTANCE() == 3)\n EMIT(STRONG);\n else if (DISTANCE() == 2)\n EMIT(EM);\n else\n EMIT(PRINTABLE);\n fbreak;\n };\n\n ''i\n {\n EMIT(STRONG_START);\n fbreak;\n };\n\n '<\/strong>'i\n {\n EMIT(STRONG_END);\n fbreak;\n };\n\n ''i\n {\n EMIT(EM_START);\n fbreak;\n };\n\n '<\/em>'i\n {\n EMIT(EM_END);\n fbreak;\n };\n\n '`'\n {\n EMIT(TT);\n fbreak;\n };\n\n ''i\n {\n EMIT(TT_START);\n fbreak;\n };\n\n '<\/tt>'i\n {\n EMIT(TT_END);\n fbreak;\n };\n\n # shorthand for
and <\/blockquote>\n '>' @mark ' '?\n {\n if (out->column_start == 1 || last_token_type == BLOCKQUOTE)\n EMIT(BLOCKQUOTE);\n else\n {\n REWIND();\n EMIT(GREATER);\n }\n fbreak;\n };\n\n # shorthand for
 and <\/pre>\n        ' ' @mark ' '*\n        {\n            if (out->column_start == 1 || last_token_type == BLOCKQUOTE)\n            {\n                REWIND();\n                EMIT(PRE);\n            }\n            else\n                EMIT(SPACE);\n            fbreak;\n        };\n\n        '#'\n        {\n            if (out->column_start == 1              ||\n                last_token_type == OL               ||\n                last_token_type == UL               ||\n                last_token_type == BLOCKQUOTE       ||\n                last_token_type == BLOCKQUOTE_START)\n                EMIT(OL);\n            else\n                EMIT(PRINTABLE);\n            fbreak;\n        };\n\n        '*'\n        {\n            if (out->column_start == 1              ||\n                last_token_type == OL               ||\n                last_token_type == UL               ||\n                last_token_type == BLOCKQUOTE       ||\n                last_token_type == BLOCKQUOTE_START)\n                EMIT(UL);\n            else\n                EMIT(PRINTABLE);\n            fbreak;\n        };\n\n        '='+ @mark ' '*\n        {\n            if (out->column_start == 1 || last_token_type == BLOCKQUOTE || last_token_type == BLOCKQUOTE_START)\n            {\n                REWIND();\n                if (DISTANCE() == 1)\n                    EMIT(H1_START);\n                else if (DISTANCE() == 2)\n                    EMIT(H2_START);\n                else if (DISTANCE() == 3)\n                    EMIT(H3_START);\n                else if (DISTANCE() == 4)\n                    EMIT(H4_START);\n                else if (DISTANCE() == 5)\n                    EMIT(H5_START);\n                else if (DISTANCE() == 6)\n                    EMIT(H6_START);\n                else if (DISTANCE() > 6)\n                {\n                    p = ts + 6;\n                    EMIT(H6_START);\n                }\n            }\n            else if (AT_END() || NEXT_CHAR() == '\\n' || NEXT_CHAR() == '\\r')\n            {\n                REWIND();\n                if (DISTANCE() == 1)\n                    EMIT(H1_END);\n                else if (DISTANCE() == 2)\n                    EMIT(H2_END);\n                else if (DISTANCE() == 3)\n                    EMIT(H3_END);\n                else if (DISTANCE() == 4)\n                    EMIT(H4_END);\n                else if (DISTANCE() == 5)\n                    EMIT(H5_END);\n                else if (DISTANCE() == 6)\n                    EMIT(H6_END);\n                else if (DISTANCE() > 6)\n                {\n                    p -= 6; \/\/ will scan the H6 on the next scan\n                    EMIT(PRINTABLE);\n                }\n            }\n            else\n            {\n                \/\/ note that a H*_END token will never match before a BLOCKQUOTE_END\n                REWIND();\n                EMIT(PRINTABLE);\n            }\n            fbreak;\n        };\n\n        uri\n        {\n            EMIT(URI);\n            fbreak;\n        };\n\n        mail\n        {\n            EMIT(MAIL);\n            fbreak;\n        };\n\n        path\n        {\n            EMIT(PATH);\n            fbreak;\n        };\n\n        '[['\n        {\n            EMIT(LINK_START);\n            fbreak;\n        };\n\n        ']]'\n        {\n            EMIT(LINK_END);\n            fbreak;\n        };\n\n        '|'\n        {\n            EMIT(SEPARATOR);\n            fbreak;\n        };\n\n        '['\n        {\n            EMIT(EXT_LINK_START);\n            fbreak;\n        };\n\n        ']'\n        {\n            EMIT(EXT_LINK_END);\n            fbreak;\n        };\n\n        '"'\n        {\n            EMIT(QUOT_ENTITY);\n            fbreak;\n        };\n\n        '&'\n        {\n            EMIT(AMP_ENTITY);\n            fbreak;\n        };\n\n        '&' alpha+ digit* ';'\n        {\n            EMIT(NAMED_ENTITY);\n            fbreak;\n        };\n\n        '&#' [xX] xdigit+ ';'\n        {\n            EMIT(HEX_ENTITY);\n            fbreak;\n        };\n\n        '&#' digit+ ';'\n        {\n            EMIT(DECIMAL_ENTITY);\n            fbreak;\n        };\n\n        '\"'\n        {\n            EMIT(QUOT);\n            fbreak;\n        };\n\n        '&'\n        {\n            EMIT(AMP);\n            fbreak;\n        };\n\n        '<'\n        {\n            EMIT(LESS);\n            fbreak;\n        };\n\n        '>'\n        {\n            EMIT(GREATER);\n            fbreak;\n        };\n\n        '{{'\n        {\n            EMIT(IMG_START);\n            fbreak;\n        };\n\n        '}}'\n        {\n            EMIT(IMG_END);\n            fbreak;\n        };\n\n        '{'\n        {\n            EMIT(LEFT_CURLY);\n            fbreak;\n        };\n\n        '}'\n        {\n            EMIT(RIGHT_CURLY);\n            fbreak;\n        };\n\n        (\"\\r\"? \"\\n\") | \"\\r\"\n        {\n            EMIT(CRLF);\n            out->column_stop = 1;\n            out->line_stop++;\n            fbreak;\n        };\n\n        # must tokenize these separately from the other PRINTABLE characters otherwise a string like:\n        #   See http:\/\/example.com\/.\n        # will get greedily tokenized as PRINABLE, SPACE, PRINTABLE rather than PRINTABLE, SPACE, URI, SPECIAL_URI_CHARS\n        # this also applies to MAIL tokenization and input strings like:\n        #   Email me (user@example.com) for more info.\n        special_uri_chars\n        {\n            EMIT(SPECIAL_URI_CHARS);\n            fbreak;\n        };\n\n        alnum+\n        {\n            EMIT(ALNUM);\n            fbreak;\n        };\n\n        # all the printable ASCII characters (0x20 to 0x7e) excluding those explicitly covered elsewhere:\n        # we skip space (0x20), exclamation mark (0x21), quote (0x22), hash (0x23), ampersand (0x26), apostrophe (0x27),\n        # left parenthesis (0x28), right parenthesis (0x29), numbers (0x30..0x39), asterisk (0x2a), comma (0x2c), period (0x2e),\n        # colon (0x3a), semi-colon (0x3b), less than (0x3c), equals (0x3d), greater than (0x3e), question mark (0x3f), uppercase\n        # letters (0x41..0x5a), left bracket (0x5b), right bracket (0x5d), backtick (0x60), lowercase letters (0x61..0x7a), left\n        # curly brace (0x7b), vertical bar (0x7c) and right curly brace (0x7d).\n        (0x24..0x25 | 0x2b | 0x2d | 0x2f | 0x40 | 0x5c | 0x5e..0x5f | 0x7e)+\n        {\n            EMIT(PRINTABLE);\n            fbreak;\n        };\n\n        # here is where we handle the UTF-8 and everything else\n        #\n        #     one_byte_sequence   = byte begins with zero;\n        #     two_byte_sequence   = first byte begins with 110 (0xc0..0xdf), next with 10 (0x80..9xbf);\n        #     three_byte_sequence = first byte begins with 1110 (0xe0..0xef), next two with 10 (0x80..9xbf);\n        #     four_byte_sequence  = first byte begins with 11110 (0xf0..0xf7), next three with 10 (0x80..9xbf);\n        #\n        #     within the ranges specified, we also exclude these illegal sequences:\n        #       1100000x (c0 c1)    overlong encoding, lead byte of 2 byte seq but code point <= 127\n        #       11110101 (f5)       restricted by RFC 3629 lead byte of 4-byte sequence for codepoint above 10ffff\n        #       1111011x (f6, f7)   restricted by RFC 3629 lead byte of 4-byte sequence for codepoint above 10ffff\n        (0x01..0x1f | 0x7f)                             @non_printable_ascii        |\n        (0xc2..0xdf 0x80..0xbf)                         @two_byte_utf8_sequence     |\n        (0xe0..0xef 0x80..0xbf 0x80..0xbf)              @three_byte_utf8_sequence   |\n        (0xf0..0xf4 0x80..0xbf 0x80..0xbf 0x80..0xbf)   @four_byte_utf8_sequence\n        {\n            EMIT(DEFAULT);\n            out->column_stop = out->column_start + 1;\n            fbreak;\n        };\n\n    *|;\n\n    write data;\n}%%\n\n\/\/ for now we use the scanner as a tokenizer that returns one token at a time, just like ANTLR\n\/\/ ultimately we could look at embedding all of the transformation inside the scanner itself (combined scanner\/parser)\n\/\/ pass in the last token because that's useful for the scanner to know\n\/\/ p data pointer (required by Ragel machine); overriden with contents of last_token if supplied\n\/\/ pe data end pointer (required by Ragel machine)\nvoid next_token(token_t *out, token_t *last_token, char *p, char *pe)\n{\n    int last_token_type = NO_TOKEN;\n    if (last_token)\n    {\n        last_token_type     = last_token->type;\n        p = last_token->stop;\n        out->line_start     = out->line_stop    = last_token->line_stop;\n        out->column_start   = out->column_stop  = last_token->column_stop;\n    }\n    else\n    {\n        out->line_start     = 1;\n        out->column_start   = 1;\n        out->line_stop      = 1;\n        out->column_stop    = 1;\n    }\n    out->type       = NO_TOKEN;\n    out->code_point = 0;\n    out->start      = p;\n    if (p == pe)\n    {\n        \/\/ all done, have reached end of input\n        out->stop  = p;\n        out->type  = END_OF_FILE;\n        return;\n    }\n\n    char    *mark;      \/\/ for manual backtracking\n    char    *eof = pe;  \/\/ required for backtracking (longest match determination)\n    int     cs;         \/\/ current state (standard Ragel)\n    char    *ts;        \/\/ token start (scanner)\n    char    *te;        \/\/ token end (scanner)\n    int     act;        \/\/ identity of last patterned matched (scanner)\n    %% write init;\n    %% write exec;\n    if (cs == wikitext_error)\n        rb_raise(eWikitextParserError, \"failed before finding a token\");\n    else if (out->type == NO_TOKEN)\n        rb_raise(eWikitextParserError, \"failed to produce a token\");\n}\n","old_contents":"\/\/ Copyright 2008-2009 Wincent Colaiuta\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see .\n\n\/\/----------------------------------------------------------------------\/\/\n\/\/ NOTE: wikitext_ragel.c is generated from wikitext_ragel.rl, so       \/\/\n\/\/       if you make changes to the former they will be overwritten.    \/\/\n\/\/       You should perform all your edits in wikitext_ragel.rl.        \/\/\n\/\/----------------------------------------------------------------------\/\/\n\n#include \"wikitext_ragel.h\"\n#include \"wikitext.h\"\n#include \n\n#define EMIT(t)     do { out->type = t; out->stop = p + 1; out->column_stop += (out->stop - out->start); } while (0)\n#define MARK()      do { mark = p; } while (0)\n#define REWIND()    do { p = mark; } while (0)\n#define AT_END()    (p + 1 == pe)\n#define DISTANCE()  (p + 1 - ts)\n#define NEXT_CHAR() (*(p + 1))\n\n%%{\n    machine wikitext;\n\n    action mark\n    {\n        MARK();\n    }\n\n    action non_printable_ascii\n    {\n        out->code_point = *p & 0x7f;\n    }\n\n    action two_byte_utf8_sequence\n    {\n        out->code_point = ((uint32_t)(*(p - 1)) & 0x1f) << 6 |\n            (*p & 0x3f);\n    }\n\n    action three_byte_utf8_sequence\n    {\n        out->code_point = ((uint32_t)(*(p - 2)) & 0x0f) << 12 |\n            ((uint32_t)(*(p - 1)) & 0x3f) << 6 |\n            (*p & 0x3f);\n    }\n\n    action four_byte_utf8_sequence\n    {\n        out->code_point = ((uint32_t)(*(p - 3)) & 0x07) << 18 |\n            ((uint32_t)(*(p - 2)) & 0x3f) << 12 |\n            ((uint32_t)(*(p - 1)) & 0x3f) << 6 |\n            (*p & 0x3f);\n    }\n\n    # simple approximation for matching email addresses; not quite RFC 2822!\n    user                = (alnum | [_\\.] | '-')+ ;\n    tld                 = alpha{2,5} ;\n    domain              = (alnum+ '.')+ tld ;\n    mail                = user '@' domain ;\n\n    uri_chars           = (alnum | [@$&'(\\*\\+=%_~\/#] | '-')+ ;\n    special_uri_chars   = ([:!\\(\\),;\\.\\?])+ ;\n    uri                 = ('mailto:'i mail) |\n                          (('http'i [sS]? ':\/\/' | 'ftp:\/\/'i | 'svn:\/\/'i) uri_chars (special_uri_chars uri_chars)*) ;\n    path                = '\/' ([a-zA-Z0-9_\\-.]+ '\/'?)* ;\n\n    main := |*\n\n        ''i\n        {\n            EMIT(NO_WIKI_START);\n            fbreak;\n        };\n\n        '<\/nowiki>'i\n        {\n            EMIT(NO_WIKI_END);\n            fbreak;\n        };\n\n        '
'i\n        {\n            EMIT(PRE_START);\n            fbreak;\n        };\n\n        '<\/pre>'i\n        {\n            EMIT(PRE_END);\n            fbreak;\n        };\n\n        '
'i\n {\n EMIT(BLOCKQUOTE_START);\n fbreak;\n };\n\n '<\/blockquote>'i\n {\n EMIT(BLOCKQUOTE_END);\n fbreak;\n };\n\n \"'\"{1,5}\n {\n if (DISTANCE() == 5)\n EMIT(STRONG_EM);\n else if (DISTANCE() == 4)\n {\n p--;\n EMIT(STRONG_EM);\n }\n else if (DISTANCE() == 3)\n EMIT(STRONG);\n else if (DISTANCE() == 2)\n EMIT(EM);\n else\n EMIT(PRINTABLE);\n fbreak;\n };\n\n ''i\n {\n EMIT(STRONG_START);\n fbreak;\n };\n\n '<\/strong>'i\n {\n EMIT(STRONG_END);\n fbreak;\n };\n\n ''i\n {\n EMIT(EM_START);\n fbreak;\n };\n\n '<\/em>'i\n {\n EMIT(EM_END);\n fbreak;\n };\n\n '`'\n {\n EMIT(TT);\n fbreak;\n };\n\n ''i\n {\n EMIT(TT_START);\n fbreak;\n };\n\n '<\/tt>'i\n {\n EMIT(TT_END);\n fbreak;\n };\n\n # shorthand for
and <\/blockquote>\n '>' @mark ' '?\n {\n if (out->column_start == 1 || last_token_type == BLOCKQUOTE)\n EMIT(BLOCKQUOTE);\n else\n {\n REWIND();\n EMIT(GREATER);\n }\n fbreak;\n };\n\n # shorthand for
 and <\/pre>\n        ' ' @mark ' '*\n        {\n            if (out->column_start == 1 || last_token_type == BLOCKQUOTE)\n            {\n                REWIND();\n                EMIT(PRE);\n            }\n            else\n                EMIT(SPACE);\n            fbreak;\n        };\n\n        '#'\n        {\n            if (out->column_start == 1              ||\n                last_token_type == OL               ||\n                last_token_type == UL               ||\n                last_token_type == BLOCKQUOTE       ||\n                last_token_type == BLOCKQUOTE_START)\n                EMIT(OL);\n            else\n                EMIT(PRINTABLE);\n            fbreak;\n        };\n\n        '*'\n        {\n            if (out->column_start == 1              ||\n                last_token_type == OL               ||\n                last_token_type == UL               ||\n                last_token_type == BLOCKQUOTE       ||\n                last_token_type == BLOCKQUOTE_START)\n                EMIT(UL);\n            else\n                EMIT(PRINTABLE);\n            fbreak;\n        };\n\n        '='+ @mark ' '*\n        {\n            if (out->column_start == 1 || last_token_type == BLOCKQUOTE || last_token_type == BLOCKQUOTE_START)\n            {\n                REWIND();\n                if (DISTANCE() == 1)\n                    EMIT(H1_START);\n                else if (DISTANCE() == 2)\n                    EMIT(H2_START);\n                else if (DISTANCE() == 3)\n                    EMIT(H3_START);\n                else if (DISTANCE() == 4)\n                    EMIT(H4_START);\n                else if (DISTANCE() == 5)\n                    EMIT(H5_START);\n                else if (DISTANCE() == 6)\n                    EMIT(H6_START);\n                else if (DISTANCE() > 6)\n                {\n                    p = ts + 6;\n                    EMIT(H6_START);\n                }\n            }\n            else if (AT_END() || NEXT_CHAR() == '\\n' || NEXT_CHAR() == '\\r')\n            {\n                REWIND();\n                if (DISTANCE() == 1)\n                    EMIT(H1_END);\n                else if (DISTANCE() == 2)\n                    EMIT(H2_END);\n                else if (DISTANCE() == 3)\n                    EMIT(H3_END);\n                else if (DISTANCE() == 4)\n                    EMIT(H4_END);\n                else if (DISTANCE() == 5)\n                    EMIT(H5_END);\n                else if (DISTANCE() == 6)\n                    EMIT(H6_END);\n                else if (DISTANCE() > 6)\n                {\n                    p -= 6; \/\/ will scan the H6 on the next scan\n                    EMIT(PRINTABLE);\n                }\n            }\n            else\n            {\n                \/\/ note that a H*_END token will never match before a BLOCKQUOTE_END\n                REWIND();\n                EMIT(PRINTABLE);\n            }\n            fbreak;\n        };\n\n        uri\n        {\n            EMIT(URI);\n            fbreak;\n        };\n\n        mail\n        {\n            EMIT(MAIL);\n            fbreak;\n        };\n\n        path\n        {\n            EMIT(PATH);\n            fbreak;\n        };\n\n        '[['\n        {\n            EMIT(LINK_START);\n            fbreak;\n        };\n\n        ']]'\n        {\n            EMIT(LINK_END);\n            fbreak;\n        };\n\n        '|'\n        {\n            EMIT(SEPARATOR);\n            fbreak;\n        };\n\n        '['\n        {\n            EMIT(EXT_LINK_START);\n            fbreak;\n        };\n\n        ']'\n        {\n            EMIT(EXT_LINK_END);\n            fbreak;\n        };\n\n        '"'\n        {\n            EMIT(QUOT_ENTITY);\n            fbreak;\n        };\n\n        '&'\n        {\n            EMIT(AMP_ENTITY);\n            fbreak;\n        };\n\n        '&' alpha+ digit* ';'\n        {\n            EMIT(NAMED_ENTITY);\n            fbreak;\n        };\n\n        '&#' [xX] xdigit+ ';'\n        {\n            EMIT(HEX_ENTITY);\n            fbreak;\n        };\n\n        '&#' digit+ ';'\n        {\n            EMIT(DECIMAL_ENTITY);\n            fbreak;\n        };\n\n        '\"'\n        {\n            EMIT(QUOT);\n            fbreak;\n        };\n\n        '&'\n        {\n            EMIT(AMP);\n            fbreak;\n        };\n\n        '<'\n        {\n            EMIT(LESS);\n            fbreak;\n        };\n\n        '>'\n        {\n            EMIT(GREATER);\n            fbreak;\n        };\n\n        '{{'\n        {\n            EMIT(IMG_START);\n            fbreak;\n        };\n\n        '}}'\n        {\n            EMIT(IMG_END);\n            fbreak;\n        };\n\n        '{'\n        {\n            EMIT(LEFT_CURLY);\n            fbreak;\n        };\n\n        '}'\n        {\n            EMIT(RIGHT_CURLY);\n            fbreak;\n        };\n\n        (\"\\r\"? \"\\n\") | \"\\r\"\n        {\n            EMIT(CRLF);\n            out->column_stop = 1;\n            out->line_stop++;\n            fbreak;\n        };\n\n        # must tokenize these separately from the other PRINTABLE characters otherwise a string like:\n        #   See http:\/\/example.com\/.\n        # will get greedily tokenized as PRINABLE, SPACE, PRINTABLE rather than PRINTABLE, SPACE, URI, SPECIAL_URI_CHARS\n        # this also applies to MAIL tokenization and input strings like:\n        #   Email me (user@example.com) for more info.\n        special_uri_chars\n        {\n            EMIT(SPECIAL_URI_CHARS);\n            fbreak;\n        };\n\n        alnum+\n        {\n            EMIT(ALNUM);\n            fbreak;\n        };\n\n        # all the printable ASCII characters (0x20 to 0x7e) excluding those explicitly covered elsewhere:\n        # we skip space (0x20), exclamation mark (0x21), quote (0x22), hash (0x23), ampersand (0x26), apostrophe (0x27),\n        # left parenthesis (0x28), right parenthesis (0x29), numbers (0x30..0x39), asterisk (0x2a), comma (0x2c), period (0x2e),\n        # colon (0x3a), semi-colon (0x3b), less than (0x3c), equals (0x3d), greater than (0x3e), question mark (0x3f), uppercase\n        # letters (0x41..0x5a), left bracket (0x5b), right bracket (0x5d), backtick (0x60), lowercase letters (0x61..0x7a), left\n        # curly brace (0x7b), vertical bar (0x7c) and right curly brace (0x7d).\n        (0x24..0x25 | 0x2b | 0x2d | 0x2f | 0x40 | 0x5c | 0x5e..0x5f | 0x7e)+\n        {\n            EMIT(PRINTABLE);\n            fbreak;\n        };\n\n        # here is where we handle the UTF-8 and everything else\n        #\n        #     one_byte_sequence   = byte begins with zero;\n        #     two_byte_sequence   = first byte begins with 110 (0xc0..0xdf), next with 10 (0x80..9xbf);\n        #     three_byte_sequence = first byte begins with 1110 (0xe0..0xef), next two with 10 (0x80..9xbf);\n        #     four_byte_sequence  = first byte begins with 11110 (0xf0..0xf7), next three with 10 (0x80..9xbf);\n        #\n        #     within the ranges specified, we also exclude these illegal sequences:\n        #       1100000x (c0 c1)    overlong encoding, lead byte of 2 byte seq but code point <= 127\n        #       11110101 (f5)       restricted by RFC 3629 lead byte of 4-byte sequence for codepoint above 10ffff\n        #       1111011x (f6, f7)   restricted by RFC 3629 lead byte of 4-byte sequence for codepoint above 10ffff\n        (0x01..0x1f | 0x7f)                             @non_printable_ascii        |\n        (0xc2..0xdf 0x80..0xbf)                         @two_byte_utf8_sequence     |\n        (0xe0..0xef 0x80..0xbf 0x80..0xbf)              @three_byte_utf8_sequence   |\n        (0xf0..0xf4 0x80..0xbf 0x80..0xbf 0x80..0xbf)   @four_byte_utf8_sequence\n        {\n            EMIT(DEFAULT);\n            out->column_stop = out->column_start + 1;\n            fbreak;\n        };\n\n    *|;\n\n    write data;\n}%%\n\n\/\/ for now we use the scanner as a tokenizer that returns one token at a time, just like ANTLR\n\/\/ ultimately we could look at embedding all of the transformation inside the scanner itself (combined scanner\/parser)\n\/\/ pass in the last token because that's useful for the scanner to know\n\/\/ p data pointer (required by Ragel machine); overriden with contents of last_token if supplied\n\/\/ pe data end pointer (required by Ragel machine)\nvoid next_token(token_t *out, token_t *last_token, char *p, char *pe)\n{\n    int last_token_type = NO_TOKEN;\n    if (last_token)\n    {\n        last_token_type     = last_token->type;\n        p = last_token->stop;\n        out->line_start     = out->line_stop    = last_token->line_stop;\n        out->column_start   = out->column_stop  = last_token->column_stop;\n    }\n    else\n    {\n        out->line_start     = 1;\n        out->column_start   = 1;\n        out->line_stop      = 1;\n        out->column_stop    = 1;\n    }\n    out->type       = NO_TOKEN;\n    out->code_point = 0;\n    out->start      = p;\n    if (p == pe)\n    {\n        \/\/ all done, have reached end of input\n        out->stop  = p;\n        out->type  = END_OF_FILE;\n        return;\n    }\n\n    char    *mark;      \/\/ for manual backtracking\n    char    *eof = pe;  \/\/ required for backtracking (longest match determination)\n    int     cs;         \/\/ current state (standard Ragel)\n    char    *ts;        \/\/ token start (scanner)\n    char    *te;        \/\/ token end (scanner)\n    int     act;        \/\/ identity of last patterned matched (scanner)\n    %% write init;\n    %% write exec;\n    if (cs == wikitext_error)\n        rb_raise(eWikitextParserError, \"failed before finding a token\");\n    else if (out->type == NO_TOKEN)\n        rb_raise(eWikitextParserError, \"failed to produce a token\");\n}\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"}
{"commit":"c1bfe3b9d70e9a1a96e9fd746b18f41d41b0704f","subject":"Unify audio and subtitle scanning","message":"Unify audio and subtitle scanning\n\nAdd a subtitle scanner\n","repos":"yanfali\/gomkv","old_file":"src\/handbrake\/handbrake.rl","new_file":"src\/handbrake\/handbrake.rl","new_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\ntype Section int\nconst (\n\tNONE Section = iota\n\tCHAPTER\n\tAUDIO\n\tSUBTITLE\n)\n\nvar section Section = NONE\nfunc parseOutput(data string) (HandBrakeMeta) {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\t_,_,_,_ = top, ts, te, act\n\tvar stack = []int{0}\n\t_ = eof\n\tline := 1\n\tcsp := 0\n\tmeta := HandBrakeMeta{}\n\tfmt.Printf(\"%02d: \", line)\n\t_ = csp\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\tstitle := |*\n\t\t\t(alnum|space)+[.]*alnum* => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tsduration := |*\n\t\t\tspace*;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => { fmt.Printf(\"%s:\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} => { fmt.Printf(\"%s:\", data[ts:te]); fret;};\n\t\t*|;\n\t\tpaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1,4} \"\/\" digit{1,4} => { fmt.Printf(\"%s:\", data[ts:te]); fret; };\n\t\t*|;\n\t\tdaspect := |*\n\t\t\tspace*;\n\t\t\tdigit . \".\" . digit{1,3} => { fmt.Printf(\"%s:\", data[ts:te]); fret; };\n\t\t*|;\n\t\tsfps := |*\n\t\t\t\"\\n\" => { ts -= 10; fmt.Printf(\"%s\", data[ts:te-5]); p -= 1; fret; };\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tatrack := |*\n#\t\t\tspace+ \"+\" space+;\n# track\n#\t\t\tdigit => { fmt.Printf(\"%s,\", data[ts:te]); };\n#\t\t\t\",\" space+;\n# Language\n\t\t\t[A-Z] alpha+ => { fmt.Printf(\"a-%s:\", data[ts:te]); };\n\t\t\tspace;\n\t\t\t\"(\";\n# Codec\n\t\t\t\"AC3\" | \"DTS\" | \"aac\" => { fmt.Printf(\"b-%s:\", data[ts:te]); };\n\t\t\t\")\";\n\t\t\tspace;\n\t\t\t\"(\";\n# Channels\n\t\t\tdigit . \".\" . digit => { fmt.Printf(\"c-%s:\", data[ts:te]) };\n\t\t\tspace;\n\t\t\t\"ch) \";\n# Ignore this bit\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \"),\";\n# Hertz\n\t\t\tspace;\n\t\t\tdigit+ \"Hz,\" => { fmt.Printf(\"d-%s:\", data[ts:te-3]) };\n\t\t\tspace;\n# Bps\n\t\t\tdigit+ \"bps\" => { fmt.Printf(\"e-%s\", data[ts:te-3]); fret; };\n\t\t\t*|;\n\t\tsubtype = \"Bitmap\" | \"Text\";\n\t\tformat = \"VOBSUB\" | \"UTF-8\";\n\t\tsubtitle := |*\n\t\t\t[A-Z] alpha+ - subtype - format => { fmt.Printf(\"a-%s:\", data[ts:te]); };\n\t\t\tspace;\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \")\";\n\t\t\tspace;\n\t\t\t\"(\" subtype \")\" => { fmt.Printf(\"b-%s:\", data[ts+1:te-1]); };\n\t\t\t\"(\" format \")\" => { fmt.Printf(\"c-%s\", data[ts+1:te-1]); fret; };\n\t\t*|;\n\t\tword = [a-z]+;\n\t\tprefix = space+ \"+\";\n\t\tprefixsp = prefix space;\n\t\tstream = prefixsp \"stream:\" space*;\n\t\tduration = prefixsp \"duration:\";\n\t\tsize = prefixsp \"size:\";\n\t\tpixelaspect = prefix any+ \"pixel\" space+ \"aspect:\";\n\t\tdisplayaspect = prefix any+ \"display\" space+ \"aspect:\";\n\t\tfps = prefix any+ \"fps\";\n\t\tautocrop = prefixsp \"autocrop:\";\n\t\ttrack = prefixsp digit \",\" space;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tstream @{ fcall stitle; } |\n\t\t\tduration @{ fcall sduration; } |\n\t\t\tsize @{ fcall picture; } |\n\t\t\tpixelaspect @{ fcall paspect; } |\n\t\t\tdisplayaspect @{ fcall daspect; } |\n\t\t\tfps @{ fcall sfps; } |\n\t\t\tautocrop @{ fcall crop; } |\n\t\t\tprefixsp \"chapters:\" @{ section = CHAPTER; fmt.Printf(\"chapter\"); } |\n\t\t\tprefixsp \"audio tracks:\" @{ section = AUDIO; fmt.Printf(\"audio\"); } |\n\t\t\tprefixsp \"subtitle tracks:\" @{ section = SUBTITLE; fmt.Printf(\"subtitle\"); } |\n\t\t\ttrack @{\n\t\t\t\tswitch section {\n\t\t\t\tcase AUDIO:\n\t\t\t\t\tfcall atrack;\n\t\t\t\tcase SUBTITLE:\n\t\t\t\t\tfcall subtitle;\n\t\t\t\t}\n\t\t\t}\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","old_contents":"package handbrake\n\nimport (\n\t\"fmt\"\n)\n\n%%{\n\tmachine handbrake;\n\twrite data;\n}%%\n\ntype Section int\nconst (\n\tNONE Section = iota\n\tCHAPTER\n\tAUDIO\n\tSUBTITLE\n)\n\nvar section Section = NONE\nfunc parseOutput(data string) (HandBrakeMeta) {\n\tcs, p, pe, eof := 0, 0, len(data), 0\n\ttop, ts, te, act := 0,0,0,0\n\t_,_,_,_ = top, ts, te, act\n\tvar stack = []int{0}\n\t_ = eof\n\tline := 1\n\tcsp := 0\n\tmeta := HandBrakeMeta{}\n\tfmt.Printf(\"%02d: \", line)\n\t_ = csp\n\t%%{\n\t\taction newline { line +=1; fmt.Printf(\"\\n%02d: \", line) }\n\t\tnewline = any* '\\n' @ newline;\n\t\tstitle := |*\n\t\t\t(alnum|space)+[.]*alnum* => { fmt.Printf(\"%s\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tsduration := |*\n\t\t\tspace*;\n\t\t\tdigit{2}[:]digit{2}[:]digit{2} => { fmt.Printf(\"%s:\", data[ts:te]); fret;};\n\t\t\t\"\\n\" => { fret; };\n\t\t*|;\n\t\tpicture := |*\n\t\t\tspace*;\n\t\t\tdigit{3,4} \"x\" digit{3,4} => { fmt.Printf(\"%s:\", data[ts:te]); fret;};\n\t\t*|;\n\t\tpaspect := |*\n\t\t\tspace*;\n\t\t\tdigit{1,4} \"\/\" digit{1,4} => { fmt.Printf(\"%s:\", data[ts:te]); fret; };\n\t\t*|;\n\t\tdaspect := |*\n\t\t\tspace*;\n\t\t\tdigit . \".\" . digit{1,3} => { fmt.Printf(\"%s:\", data[ts:te]); fret; };\n\t\t*|;\n\t\tsfps := |*\n\t\t\t\"\\n\" => { ts -= 10; fmt.Printf(\"%s\", data[ts:te-5]); p -= 1; fret; };\n\t\t*|;\n\t\tcrop := |*\n\t\t\tspace*;\n\t\t\tdigit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} \"\/\" digit{1,3} => { fmt.Printf(\"%s\", data[ts:te]); fret; };\n\t\t*|;\n\t\tatrack := |*\n#\t\t\tspace+ \"+\" space+;\n# track\n#\t\t\tdigit => { fmt.Printf(\"%s,\", data[ts:te]); };\n#\t\t\t\",\" space+;\n# Language\n\t\t\t[A-Z] alpha+ => { fmt.Printf(\"a-%s:\", data[ts:te]); };\n\t\t\tspace;\n\t\t\t\"(\";\n# Codec\n\t\t\t\"AC3\" | \"DTS\" | \"aac\" => { fmt.Printf(\"b-%s:\", data[ts:te]); };\n\t\t\t\")\";\n\t\t\tspace;\n\t\t\t\"(\";\n# Channels\n\t\t\tdigit . \".\" . digit => { fmt.Printf(\"c-%s:\", data[ts:te]) };\n\t\t\tspace;\n\t\t\t\"ch) \";\n# Ignore this bit\n\t\t\t\"(iso\" digit{3} \"-\" digit \":\" space lower{3} \"),\";\n# Hertz\n\t\t\tspace;\n\t\t\tdigit+ \"Hz,\" => { fmt.Printf(\"d-%s:\", data[ts:te-3]) };\n\t\t\tspace;\n# Bps\n\t\t\tdigit+ \"bps\" => { fmt.Printf(\"e-%s\", data[ts:te-3]); fret; };\n\t\t\t*|;\n\t\tword = [a-z]+;\n\t\tprefix = space+ \"+\";\n\t\tprefixsp = prefix space;\n\t\tstream = prefixsp \"stream:\" space*;\n\t\tduration = prefixsp \"duration:\";\n\t\tsize = prefixsp \"size:\";\n\t\tpixelaspect = prefix any+ \"pixel\" space+ \"aspect:\";\n\t\tdisplayaspect = prefix any+ \"display\" space+ \"aspect:\";\n\t\tfps = prefix any+ \"fps\";\n\t\tautocrop = prefixsp \"autocrop:\";\n\t\taudiotrack = prefixsp digit \",\" space;\n\t\tmain := ( \n\t\t\tnewline |\n\t\t\tstream @{ fcall stitle; } |\n\t\t\tduration @{ fcall sduration; } |\n\t\t\tsize @{ fcall picture; } |\n\t\t\tpixelaspect @{ fcall paspect; } |\n\t\t\tdisplayaspect @{ fcall daspect; } |\n\t\t\tfps @{ fcall sfps; } |\n\t\t\tautocrop @{ fcall crop; } |\n\t\t\tprefixsp \"chapters:\" @{ section = CHAPTER; fmt.Printf(\"chapter\"); } |\n\t\t\tprefixsp \"audio tracks:\" @{ section = AUDIO; fmt.Printf(\"audio\"); } |\n\t\t\tprefixsp \"subtitle tracks:\" @{ section = SUBTITLE; fmt.Printf(\"subtitle\"); } |\n\t\t\taudiotrack @{ if section == AUDIO { fcall atrack; } }\n\t\t)*;\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\treturn meta\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"}
{"commit":"0108efcc2c012c174761b9ddc545aa2622ddda66","subject":"(hopefully) remove all carriage return characters...","message":"(hopefully) remove all carriage return characters...\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner_parser.rl","new_file":"src\/mfilescanner_parser.rl","new_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n  machine MFileScanner;\n  write data;\n\n  # end of file character\n  EOF = 0;\n\n  # any character other than end of file\n  default = ^0;\n\n  # end of line character\n  EOL = ('\\r'? . '\\n') %{ ++line; };\n\n  # scanner for comment blocks\n  in_comment_block :=\n  (\n   ([ \\t]* >{ tmp_p = p; } .\n   # comment line begins with a percent sign\n   '%')\n     @{ fout_ << \"\\n\";\n        fout_.write(tmp_p, p - tmp_p);\n        tmp_p = p+1; fout_ << \" *\";\n      }\n   # and then some default characters\n   . (default - [\\r\\n])* . EOL\n     @{ fout_.write(tmp_p, p - tmp_p); }\n  )*\n  $!{\n    fout_ << \" *\/\\n\";\n\/\/    if(is_getter_ || is_setter_)\n\/\/    {\n\/\/      fout_ << \"*\/\\n\";\n\/\/    }\n    fhold;\n    while (*p == ' ')\n      fhold;\n    if (extra_hold_in_cblock)\n    {\n      fhold;\n      --line;\n      extra_hold_in_cblock = false;\n    }\n    fret;\n  };\n\n  action end_doxy_block\n  {\n    if(!docline)\n    {\n      p = ts-1;\n      \/* go backward until first non-whitespace is found *\/\n      for(p=p-1; *p==' ' || *p == '\\t'; --p)\n        ;\n\n      if(is_class_)\n      {\n        if(class_part_ == Header)\n        {\n          end_of_class_doc();\n          fgoto classbody;\n        } else if(class_part_ == Method || class_part_ == AtMethod)\n        {\n          if(runMode_.mode == RunMode::ParseParams)\n            return 1;\n          print_function_synopsis();\n          fgoto funcbody;\n        }\n        else if(class_part_ == MethodDeclaration)\n        {\n          fgoto funcdef;\n        }\n        else if(class_part_ == Property || class_part_ == Event)\n        {\n          fgoto propertybody;\n        }\n        else if(class_part_ == InClassComment)\n        {\n          class_part_ = Method;\n          fgoto methods;\n        }\n        else\n        {\n          cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n        }\n      }\n      else\n      {\n        if(runMode_.mode == RunMode::ParseParams)\n          return 1;\n        print_function_synopsis();\n        fgoto funcbody;\n      }\n    }\n  }\n\n  # executed when end of file is reached\n  action end_of_file\n  {\n    end_function();\n    for(  list::iterator it = namespaces_.begin();\n          it != namespaces_.end(); ++it)\n    {\n      fout_ << \"};\\n\";\n    }\n  }\n\n  # executed when we reached a comment block\n  action in_c_block\n  {\n    assert(p >= tmp_p-1);\n    fout_.write(tmp_p, p-tmp_p+1);\n    fcall in_comment_block;\n  }\n\n  action echo { fout_ << fc; }\n\n  action st_tok { tmp_p = p; }\n\n  action st_tok2 { tmp_p2 = p; }\n\n  action echo_tok {\n    assert (p >= tmp_p);\n    fout_.write(tmp_p, p - tmp_p);\n  }\n\n  action string_tok {\n    assert ( p >= tmp_p );\n    tmp_string.assign(tmp_p, p-tmp_p);\n  }\n\n  # common definitions {{{2\n\n  # comment in function body that might also be added to the doxygen block for\n  # the function description\n  is_doxy_comment =\n    (\n    # RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n    # comment\n     '|' @{ \n\/\/    if(is_getter_ || is_setter_)\n\/\/            {\n\/\/              fout_ << \"*\/\";\n\/\/            }\n            fout_ << \"\/**\"; tmp_p = p+1;\n          }\n     . (default - [\\r\\n])*\n     . ( EOL . [ \\t]*\n       . '%' @{\n                assert(p >= tmp_p -1);\n                fout_.write(tmp_p, p - tmp_p);\n                fout_ << \" * \";\n                tmp_p = p+1;\n              }\n     . (default - [\\r\\n])* )* . EOL\n     |\n    # RAGEL comment: else: a regular comment\n     ( (default - '|')\n       @{\n\/\/         if(is_getter_ || is_setter_)\n\/\/         {\n\/\/           fout_ << \"\\n#endif\\n\";\n\/\/         }\n         if (string(p, 8) != string(\"@@remove\"))\n           fout_ << \"\/* \";\n         tmp_p = p;\n         } )\n     . (default - [\\r\\n])* . EOL\n    );\n\n  # comment block in function body\n  comment_block = (( [ \\t]* >(st_tok)  . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n  # an empty line\n  empty_line = [\\t ]* . EOL;\n\n  # documentation line begin\n  doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n  # swallow a comment line till the end of the line (make it a c comment)\n  garble_comment_line =\n    ( (default - [\\r\\n])* . EOL )\n      @{\n\/\/        if(is_getter_ || is_setter_)\n\/\/        {\n\/\/          fout_ << \"\\n#endif\\n\";\n\/\/        }\n        fout_ << \"\/* \";\n        assert( p >= tmp_p );\n        fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n\/\/        if(is_getter_ || is_setter_)\n\/\/        {\n\/\/          fout_ << \"\\n#if 0\\n\";\n\/\/        }\n      };\n  garble_comment_line_wo_eol =\n    (default - [\\r\\n])*;\n\n  # white space or comment\n  WSOC =\n    ( ([ \\t]+ \n       @{\n          {\n            int i=0;\n            if (*(p+1) != ' ' && *(p+1) != '\\t')\n            {\n              while (*(p-i) == ' ' || *(p-i) == '\\t')\n                i++;\n              if (*(p-i) == '\\n')\n                fout_ << std::string(i, ' ');\n            }\n          }\n        })\n      | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n      | ('...'.[ \\t]*.EOL)\n    );\n\n  # white space or line continuation\n  WS =\n    ( [ \\t]+\n      | ('...'.[\\t]*.EOL)\n    );\n\n  # matlab identifier\n  IDENTEND = [A-Za-z0-9_];\n  IDENT = [A-Za-z_]IDENTEND**;\n\n\n  # matlab identifier with .\n  IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n  # default arguments in function declarations\n  default_arg = ([^,)\\n] | EOL)** @echo;\n\n  #}}}2\n\n  # parameter list for functions {{{2\n  paramlist =\n    (\n     (WSOC | ',' | EOL\n     | ( '=' . default_arg ) )+\n     |\n     # matlab identifier (parameter)\n     (IDENT | '~' )\n       >st_tok\n       %{\n         assert(p >= tmp_p);\n         string s(tmp_p, p - tmp_p);\n         bool addBlock = true;\n         \/\/ do not print this pointer\n         if( is_class_ && ( !methodparams_.statical\n                            && (\n                                ( class_part_ == Method\n                                  && cfuncname_ != classname_\n                                )\n                                || class_part_ == AtMethod\n                                || class_part_ == MethodDeclaration\n                               )\n                          )\n                       && ( ! (\n                               methodparams_.abstr\n                               && !runMode_.remove_first_arg_in_abstract_methods\n                              )\n                          )\n           )\n         {\n            if(paramlist_.empty())\n            {\n              addBlock = false;\n              paramlist_.push_back(string(\"this\"));\n            }\n            else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n              paramlist_.clear();\n         }\n\n         if(addBlock) {\n\n#ifdef DEBUG\n{\n  ostringstream oss;\n  oss << \"found parameter: \" << s;\n  debug_output(oss.str(), p);\n}\n#endif\n           postprocess_unused_params(s, param_list_);\n           \/\/ add an empty docu block for parameter \\a s\n           if(param_list_.find(s) == param_list_.end())\n           {\n             param_list_[s] = DocuBlock();\n           }\n#ifdef DEBUG\n{\n  ostringstream oss;\n  oss << \"in paramlist: add to paramlist: \" << s;\n  debug_output(oss.str(), p);\n}\n#endif\n           paramlist_.push_back(s);\n         }\n       }\n    )**;\n\n  \n  matrix_or_cell := (\n      '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n      |\n      '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n      );\n\n  matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n  \n  \n  # return parameter list for functions\n  lparamlist =\n    ( (WSOC | EOL )+\n      | ','\n      # matlab identifier (return value)\n      | ( (IDENT | '~') > st_tok\n          %{\n            assert(p >= tmp_p);\n            string s(tmp_p, p - tmp_p);\n            postprocess_unused_params(s, return_list_);\n            returnlist_.push_back(s);\n            \/\/ add an empty docu block for return value \\a s\n            if(return_list_.find(s) == return_list_.end())\n            {\n              return_list_[s] = DocuBlock();\n            }\n          }\n        )\n    )**;\n\n  # return parameter or return parameter list\n  lparams =\n    (\n      (\n        (\n         # matlab identifier\n         ( IDENT | '~' )\n           >st_tok\n           %{\n             assert(p >= tmp_p);\n             string s(tmp_p, p - tmp_p);\n             postprocess_unused_params(s, return_list_);\n             returnlist_.push_back(s);\n             \/\/ add an empty docu block for single return value \\a s\n\n             if(return_list_.find(s) == return_list_.end())\n             {\n               return_list_[s] = DocuBlock();\n             }\n#ifdef DEBUG\n  cerr << \"\\n In return list: \" << endl;\n#endif\n           }\n        )\n        | ( '['\n          . lparamlist\n          . ']'\n          )\n      )\n      . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n      :> '=' . WSOC*\n    );\n    # }}}2\n\n  # a line in the function body {{{2\n  funcline := |*\n    # empty line\n    ([ \\t]+)\n      => { fout_.write(ts, te-ts); };\n\n    # line continuation\n    ('...' . [ \\t]* . EOL)\n      => { fout_.write(ts, te-ts); };\n\n    # two single quote in a row need to be changed to nothing\n    ('\\'\\'');\n\n    # a string should not be parsed for comment blocks, so we handle it separately.\n    ('\\'' . [^'\\n]+ . '\\'')\n      => {\n           \/\/ change double quotes to quotes and vice versa...\n           fout_ << \"\\\" \";\n           string s(ts+1, te-ts-2);\n           std::replace(s.begin(), s.end(), '\\\"', '\\'');\n           fout_ << s;\n           fout_ << \" \\\"\";\n         };\n\n    # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n    (comment_block)\n      => {\n           assert(p >= tmp_p);\n           fout_.write(tmp_p, p - tmp_p);\n           extra_hold_in_cblock = true;\n           fcall in_comment_block;\n         };\n\n     (IDENT %{tmp_string.assign(ts,p-ts);})\n     . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n     {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n       varargin_parser_candidate_ = tmp_string;\n     };\n\n     ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n       . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n       => {\n         fout_.write(ts, te-ts);\n         if (tmp_string == varargin_parser_candidate_ )\n         {\n           varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n         }\n       };\n     \n     ((IDENT %{tmp_string.assign(ts, p - ts);})\n         . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n         . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n       => {\n         fout_.write(ts, te-ts);\n         if (tmp_string == varargin_parser_candidate_ )\n         {\n           varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n         }\n       };\n\n\n    ('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n      . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n    \n    ((IDENT %{tmp_string.assign(ts, p - ts);})\n      . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n      . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n\n\n    ('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n      . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL ) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n    \n    ((IDENT %{tmp_string.assign(ts, p - ts);})\n      . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n      . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n\n\n    # automatically add return value fields to retval_list_\n    (\n     # matlab identifier (which can be a return value and a structure)\n     (IDENT\n        %{tmp_string.assign(ts,p-ts);})\n     . '.'\n     # matlab identifer (fieldname)\n     . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n     # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n     . [ \\t]* . '=' . (^'=')\n    )\n    => {\n      fhold;\n      \/\/ store fieldname\n      assert(tmp_p2 >= tmp_p);\n      string s(tmp_p, tmp_p2 - tmp_p);\n      fout_ << tmp_string << \".\" << s << \"=\";\n      \/\/ typedef of iterators\n      typedef DocuList     :: iterator list_iterator;\n      typedef DocuListMap  :: iterator map_iterator;\n      typedef DocuBlock    :: iterator iterator;\n\n      \/\/ check wether first IDENT is a return value\n      iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n      if(it != returnlist_.end())\n      {\n        \/\/ if it is a return value...\n        \/\/ ... check wether its found field is still missing a DocuBlock in the\n        \/\/ retval list.\n        bool missing = true;\n        map_iterator rvoit = retval_list_.find(tmp_string);\n        if(rvoit != retval_list_.end())\n        {\n          list_iterator lit = (*rvoit).second.find(s);\n          if(lit != (*rvoit).second.end())\n            missing = false;\n        }\n        \/\/ if it is missing, add an empty docu block\n        if(missing)\n        {\n          retval_list_[tmp_string][s] = DocuBlock();\n        }\n      }\n    };\n\n    # automatically add parameter fields to required_list_\n    (\n     # matlab identifier (which can be a parameter and a structure)\n     (IDENT\n        %{tmp_string.assign(ts,p-ts);})\n     . '.'\n     # matlab identifer (fieldname)\n     . (IDENT_W_DOT\n         >(st_tok)\n       )\n    )\n    => {\n      \/\/ store fieldname\n      assert(p >= tmp_p);\n      string s(tmp_p, p - tmp_p+1);\n      fout_ << tmp_string << \".\" << s;\n      typedef DocuList     :: iterator list_iterator;\n      typedef DocuListMap  :: iterator map_iterator;\n      typedef DocuBlock    :: iterator iterator;\n\n      \/\/ check wether first IDENT is a parameter\n      iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n      if(it != paramlist_.end())\n      {\n        \/\/ if it is a parameter ...\n        \/\/ ... check wether its found field is still missing a DocuBlock in the\n        \/\/ return, optional and the required list.\n        bool missing = true;\n        map_iterator rvoit = retval_list_.find(tmp_string);\n        if(rvoit != retval_list_.end())\n        {\n          list_iterator lit = (*rvoit).second.find(s);\n          \/\/ found match in retval list\n          if(lit != (*rvoit).second.end())\n            missing = false;\n        }\n        map_iterator moit = optional_list_.find(tmp_string);\n        if(moit != optional_list_.end())\n        {\n          \/\/ found match in optional list\n          list_iterator lit = (*moit).second.find(s);\n          if(lit != (*moit).second.end())\n            missing = false;\n        }\n        map_iterator roit = required_list_.find(tmp_string);\n        if(roit != required_list_.end())\n        {\n          \/\/ found match in required list\n          list_iterator lit = (*roit).second.find(s);\n          if(lit != (*roit).second.end())\n            missing = false;\n        }\n        \/\/ in case it IS missing, add an empty field to the required block.\n        if(missing)\n        {\n          required_list_[tmp_string][s] = DocuBlock();\n        }\n      }\n    };\n\n    # add a @deprecated command to function declaration if disp_deprecated is\n    # used in function body\n    ('disp_deprecated' . [ \\t]*\n      . (\n          ';'\n            @{tmp_string.assign(\"\");}\n          |\n          '(' . [\\t ]* . \"'\"\n          . ([^\\n']*\n              >(st_tok)\n              %(string_tok)\n            )\n          . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n        )\n      . [\\t ]* . EOL\n    )\n      => {\n        string s;\n        if(tmp_string.empty())\n        {\n          s.assign(\"@deprecated function deprecated\\n\");\n        }\n        else\n        {\n          s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n        }\n        docuextra_.push_back(s);\n        fhold;\n      };\n\n    # simple matlab identifier\n    (IDENT)\n      => { fout_.write(ts, te-ts); };\n\n    # translate curly brackets in edgy brackets, because otherwise the doxygen\n    # parser breaks.\n    ('{')\n      => { fout_ << '['; };\n\n    ('}')\n      => { fout_ << ']'; };\n    \n    ('\\'')\n      => { fout_ << \"^t\"; };\n\n    # simply output all other characters\n    (default - [\\r\\n{}\\'])\n      => { fout_ << fc; };\n\n    # after EOL try to check for new function\n    EOL\n      => { fout_ << fc; fgoto funcbody; };\n\n  *|;\n  # }}}2\n\n  # function body {{{2\n  funcbody := |*\n\n      # things that got replaced in function body {{{4\n      ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n        => {\n          new_syntax_ = true;\n          fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n        };\n\n      ([ \\t]* . '%@@remove' . ((default - '%') | ('%' . (default - '@')) | ('%' . '@' .  (default -'@')))* . '%@@endremove');\n\n      # a comment block\n      ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n        => {\n          assert(p >= tmp_p);\n          fout_.write(tmp_p, p - tmp_p);\n          fcall in_comment_block;\n        };\n\n      # empty line\n      ([ \\t]* . EOL)\n        => { fout_ << '\\n'; };\n\n      #}}}4\n\n      # line not beginning with words 'function' or 'end'\n      ([ \\t]*\n       . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n      )\n        => {\n          p = ts-1;\n          \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n          fgoto funcline;\n        };\n\n      # things that could end the function body {{{4\n      # line only containing word 'end'\n      # the keyword needs to be in the same indentation level as beginning function\n      ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n          => {\n              if(is_class_ && class_part_ == Method)\n              {\n                tmp_string.assign(ts,p-ts+1);\n\n                if(tmp_string.find(\"e\") == funcindent_)\n                {\n                  end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n                  fgoto methods;\n                }\n              }\n              \/\/ else\n              p=ts-1;\n              \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n              fgoto funcline;\n          };\n\n      # line beginning with word 'function'\n      ([ \\t]*. 'function ')\n      {\n        tmp_string.assign(ts,p-ts+1);\n        p = ts-1;\n\n        if (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n        {\n          \/\/ end the previous function if existent\n          end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n          fgoto main;\n        }\n        else\n        {\n          fgoto funcline;\n        }\n      };\n\n      (EOF) $eof(end_of_file);\n\n      # }}}4\n\n  *|;\n   # }}}2\n\n  # fill a docublock list with input {{{2\n  fill_list := |*\n\n  # match an argument\n  ( doc_begin . [ \\t]*\n    . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*)  >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n    . ( default - [\\r\\n] )* . EOL\n  )\n    => {\n      assert(tmp_p2 >= tmp_p3);\n      tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n      \/\/    std::fout_ << tmp_string << '\\n';\n      assert(p >= tmp_p);\n      (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n    };\n\n  # expand the paragraph for last argument matched\n  ( doc_begin . [ \\t]*\n    # at least one word (non white-space characters and no double-colon)\n    . ( default - [ \\r\\t:\\n] )+ .\n    # followed by something that is a white-space or a new-line, i.e *no*\n    # double-colon\n    (\n     EOL\n     |\n     [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - [\\r\\n])* . EOL)\n     # [ \\t] . (default - '\\n')* . EOL\n    )\n  )\n    => {\n      assert(p+1 >= tmp_p);\n      string s(tmp_p, p - tmp_p + 1);\n      (*clist_)[tmp_string].push_back(s);\n      \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n    };\n\n  # return on empty line\n  ( doc_begin . [ \\t]* . EOL )\n    => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n   # end of comment block\n  ( [\\t ]* . ( (default - '%') | EOL) )\n    => {\n      p =ts-1;\n      \/\/ fout_ << \"*\/\\n\";\n      fret;\n    };\n\n  *|; #}}}2\n\n  # parse body of documentation block {{{2\n  doxy_get_body := |*\n\n    # special lists {{{4\n\n    # begin required_list\n    ( doc_begin . [ \\t]*\n      . \/required fields of \/i\n      . (IDENT >(st_tok) %(string_tok) )\n      . [ \\t]* . ':' . [ \\t]* . EOL\n    )\n      => {\n        \/\/fout_ << tmp_string << '\\n';\n        clist_ = &(required_list_[tmp_string]);\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin optional_list\n    ( doc_begin . [ \\t]*\n      . \/optional fields of \/i\n      . (IDENT\n          >(st_tok)\n          %(string_tok) )\n      . [ \\t]* . ':' . [ \\t]* . EOL )\n      => {\n        clist_ = &(optional_list_[tmp_string]);\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin optional_list\n    ( doc_begin . [ \\t]*\n      . \/generated fields of \/i\n      . (IDENT\n          >(st_tok)\n          %(string_tok) )\n      . [ \\t]* . ':' . [ \\t]* . EOL )\n      => {\n        clist_ = &(retval_list_[tmp_string]);\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin parameter list\n    ( doc_begin . [ \\t]*\n      . \/parameters\/i . [ \\t]* . ':'\n      . [ \\t]* . EOL )\n      => {\n        clist_ = ¶m_list_;\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin return list\n    ( doc_begin . [ \\t]*\n      . \/return values\/i . [ \\t]* . ':'\n      . [ \\t]* . EOL )\n      => {\n        clist_ = &return_list_;\n        docline = false;\n        fcall fill_list;\n      };\n    #}}}4\n\n    # default substitutions {{{4\n\n    # empty line\n    ( doc_begin . [ \\t]* . EOL )\n      => {\n        \/*fout_ << \"*\\n  \";*\/\n        docubody_.push_back(\"\\n\");\n        docline = false;\n      };\n\n    # paragraph line\n    ( [ \\t]* . '%' )\n      => {\n        if(!docline)\n        {\n          docline = true;\n          tmp_p = p;\n        }\n      };\n\n    # paragraph line with \"see also\" substituted by \"@sa\"\n    ( \/see also\/i . ':'? )\n      => {\n        string s;\n        assert(ts > tmp_p);\n        s.assign(tmp_p+1, ts - tmp_p-1);\n        docubody_.push_back(s+\"@sa\");\n        tmp_p = p;\n      };\n\n    # lines that could end doxyblock {{{6\n    # words\n    #  RAGEL comment:  ( default - [ \\t:%'`\\n] )+\n    ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n    # non-words\/non-whitespace\n    #  RAGEL comment:  ([:'`]) => {\n    (':') @(end_doxy_block) ;\n\n\n    # whitespace only\n    ( [ \\t] );\n\n    # titled paragraph\n    ( ':' . EOL )\n      @(end_doxy_block)\n      @{ if(docline)\n         {\n           assert(ts > tmp_p);\n           docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n           docline = false;\n         }\n       };\n    # }}}6\n    # }}}4\n\n    # end of line {{{4\n    ( EOL )\n       @(end_doxy_block)\n       @{ if(docline)\n          {\n            int offset = ( latex_begin ? 0 : 1 );\n            assert(p >= tmp_p + offset);\n            docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n            docline = false;\n          }\n        };\n      # }}}4\n\n  *|;\n  #}}}2\n\n  # doxy header parsing {{{2\n  # swallow the synopsis line\n  doxyfunction_garble := |*\n    garbage = ( (default - [\\r\\n] )* -- '...' );\n\n    ( doc_begin . (garbage . '...')+ . [\\t ]* .  EOL );\n\n    ( doc_begin . (garbage . '...')* . garbage . EOL )\n      => { fgoto doxy_get_brief; };\n  *|;\n\n\n  # read first paragraph\n  doxy_get_brief := |*\n\n    # read in one comment line\n    ( doc_begin . [\\t ]*\n      . (default - [\\r\\n\\t ]) . (default - [\\r\\n])* . EOL\n    )\n      => {\n        \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n        assert(p >= tmp_p);\n        docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n      };\n\n    # empty line\n    ( doc_begin . [\\t ]* . EOL )\n      => {\n        \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n  debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n        fgoto doxy_get_body;\n      };\n\n    # end of comment block;\n    ( [\\t ]* . [^%] )\n      => {\n        p=ts-1;\n#ifdef DEBUG\n   debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n        \/\/fout_ << \"*\/\\n\";\n        if(is_class_)\n        {\n#ifdef DEBUG\n  debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n          if(class_part_ == Header)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto classbody\",p);\n#endif\n            end_of_class_doc();\n            fgoto classbody;\n          } else if(class_part_ == Method || class_part_ == AtMethod)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n            if(runMode_.mode == RunMode::ParseParams)\n              return 1;\n            print_function_synopsis();\n            fgoto funcbody;\n          }\n          else if(class_part_ == MethodDeclaration)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n            fgoto funcdef;\n          }\n          else if(class_part_ == Property || class_part_ == Event)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n            fgoto propertybody;\n          }\n          else if(class_part_ == InClassComment)\n          {\n            class_part_ = Method;\n            fgoto methods;\n          }\n        }\n        else\n        {\n          if(runMode_.mode == RunMode::ParseParams)\n            return 1;\n          print_function_synopsis();\n          fgoto funcbody;\n        }\n      };\n\n  *|;\n  # }}}2\n\n  # garble synopsis line and then parse the documentation header {{{2\n  doxyheader := (\n    '%' . [ \\t]* .\n       (\n        ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n       )\n      $!{\n#ifdef DEBUG\n        debug_output(\"doxy_get_brief\",p);\n#endif\n        p = tmp_p - 2;\n        fgoto doxy_get_brief;\n      }\n   ); #}}}2\n\n  # access specifier expressions\n  spec_public = ( 'public'i | \"'public'\"i );\n  spec_protected = ( 'protected'i | \"'protected'\"i );\n  spec_private = ( 'private'i | \"'private'\"i );\n  \n  spec_class_single = \n\t (\n\t   ('?' . (IDENT_W_DOT**) >st_tok )\n\t   %{\n\t\t\ttmp_string.assign(tmp_p, p - tmp_p);\n\t\t\t\/\/cerr << \"Detected \" << access_.state << \" modifier by class \" << tmp_string << \"\\n\";\n\t\t\taccess_.classMemberAccess.push_back(make_pair(access_.state, tmp_string));\n        }\n     ) . WS*;\n  \n  spec_class_multi = '{' . WS* . spec_class_single . ( [,; ] . WS* . spec_class_single )* . '}';\n  \n  spec_classes = ( spec_class_single | spec_class_multi );\n    \n  # helper for setting the access specifier {{{2\n  paramaccess =\n    ( ('SetAccess' @{ access_.state = SetAccess; } . WS* . '=' . WS*\n      . ( ( spec_public \n            %{ access_.full = Public; access_.set = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.get == Public ? Public : Protected );\n               access_.set = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.get; access_.set = Private;\n             } )\n        )\n      )\n     | ( 'GetAccess' @{ access_.state = GetAccess; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.get = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.set == Public ? Public : Protected );\n               access_.get = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.set; access_.get = Private;\n             } )\n        )\n       )\n     | ( 'Access' @{ access_.state = Access; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.get = Public; access_.set = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = Protected; access_.get = Protected; access_.set = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = Private; access_.get = Private; access_.set = Private;\n             } )\n          )\n     )\n    ); #}}}2\n\n  eventparam =\n    ( ('ListenAccess' @{ access_.state = ListenAccess; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.get = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.set == Public ? Public : Protected );\n               access_.get = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.set; access_.get = Private;\n             } )\n        )\n      )\n     | ( 'NotifyAccess' @{ access_.state = NotifyAccess; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.set = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.get == Public ? Public : Protected );\n               access_.set = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.get; access_.set = Private;\n             } )\n        )\n       )\n     | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.hidden = true;\n         } )\n     );\n\n  # method and property params {{{2\n  methodparam =\n   (\n    ( paramaccess )\n    | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.abstr = true;\n         } )\n    | ( ( 'Static' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.statical = true;\n         } )\n    | ( ('Hidden' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.hidden = true;\n         } )\n    | ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.sealed = true;\n         } )\n    | ( ( 'Test' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.test = true;\n         } )\n    | ( ( 'TestMethodSetup' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.testMethodSetup = true;\n         } )\n    | ( ( 'TestMethodTeardown' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.testMethodTeardown = true;\n         } )\n   );\n\n  propertyparam =\n   (\n    ( paramaccess )\n    | ( ( 'Constant' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.constant = true;\n         } )\n    | ( ( 'Transient' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.transient = true;\n         } )\n    | ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.dependent = true;\n         } )\n    | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.hidden = true;\n         } )\n    | ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.setObservable = true;\n         } )\n    | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.abstr = true;\n         } )\n    | ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.abortSet = true;\n         } )\n   );\n\n  methodparams =\n   (\n    '(' . WSOC*\n    . methodparam\n    . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n   );\n\n  eventparams =\n   (\n    '(' . WSOC*\n    . eventparam\n    . ( WSOC* . ',' . WSOC* . eventparam )* . WSOC* . ')'\n   ); #}}}2\n\n  propertyparams =\n   (\n    '(' . WSOC*\n    . propertyparam\n    . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n   ); #}}}2\n\n  # methods and properties {{{2\n  # methods {{{4\n  methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n    (empty_line) => {\n      if(runMode_.mode != RunMode::ParseMethodParams)\n      {\n        end_method();\n        fout_ << \"\\n\";\n      }\n    };\n\n    # default: method definition\n    ([ \\t]* . 'function' )\n      => {\n        tmp_string.assign(ts, te - ts+1);\n        funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n        fout_ << string(ts, ts+funcindent_);\n        #if DEBUG\n            {\n              ostringstream oss;\n              oss << \"in methods: funcindent: \" << funcindent_;\n              debug_output(oss.str(), p);\n            }\n        #endif\n        p=ts+funcindent_-1;\n        fgoto funct;\n       };\n\n    # end of methods block\n    ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n      => {\n           if(runMode_.mode != RunMode::ParseMethodParams)\n           {\n             end_method();\n             #if DEBUG\n               debug_output(\"in methods: found end keyword, goto classbody\",p);\n             #endif\n           }\n           fgoto classbody;\n         };\n\n    # comment between two methods\n    ([ \\t]* . '%' ) => {\n      #if DEBUG\n        debug_output(\"in methods: garble comment line\",p);\n      #endif\n\n      p = ts-1;\n      class_part_ = InClassComment;\n\/*      fcall in_comment_block; *\/\n      fgoto expect_doxyblock;\n    };\n\n    # if we reach this: method declaration without definition is found\n    ([ \\t]* . [^% \\t\\n]) =>\n    {\n      #if DEBUG\n        debug_output(\"in methods: found method declaration, going to funcdef\",p);\n      #endif\n      class_part_ = MethodDeclaration;\n      p = ts-1;\n      fgoto funcdef;\n    };\n\n      *|;\n\n\n  methodsheader := (\n    [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n         @{\n            print_access_specifier(access_.full, methodparams_, propertyparams_);\n            fgoto methods;\n          }\n          );\n\n   #}}}4\n\n  # single property {{{4\n  prop = ( ( [ \\t]* . (IDENT) >st_tok\n            %{\n              {\n                char *i = tmp_p-1;\n                for (; *i == ' ' || *i == '\\t'; --i)\n                  fout_ << *i;\n              }\n              \n              end_of_property_doc();\n              string s(tmp_p, p - tmp_p);\n              if (s == \"end\")\n                fgoto classbody;\n              if (propertyparams_.dependent)\n                specifier_[s].dependent = true;\n              property_list_.push_back(s);\n              \/\/            fout_ << propertyparams_.ccprefix() << \" \" << s;\n              undoced_prop_ = true;\n            }\n          )\n        . WS* . ( ( '%' @{ fhold; } | ';' | EOL )  @{defaultprop_ = \"\";}\n            |\n            ( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n            @{\n              defaultprop_ = string(tmp_p2, p - tmp_p2);\n              string::size_type last_elem = defaultprop_.length() -1;\n              if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n              {\n                defaultprop_[0] = '\\\"';\n                defaultprop_[last_elem] = '\\\"';\n              }\n              string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n              string::size_type last_paren;\n              if (first_paren == string::npos)\n              {\n                first_paren = 1;\n                last_paren = last_elem;\n              }\n              else\n              {\n                last_paren = defaultprop_.find_last_of(\")]}\");\n                if (last_paren == string::npos)\n                  last_paren=last_elem-1;\n                else\n                {\n                  if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n                  {\n                    first_paren++;\n                    last_paren--;\n                  }\n                  defaultprop_.insert(first_paren, 1,'\"');\n                  defaultprop_.insert(last_paren+2, 1,'\"');\n                  first_paren++;\n                  last_paren++;\n                }\n              }\n              for (unsigned int i = first_paren; i < last_paren; ++i)\n              {\n                if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n                {\n                  defaultprop_[i]   = ' ';\n                  defaultprop_[i+1] = ' ';\n                  defaultprop_[i+2] = ' ';\n                }\n\/*                else if(defaultprop_[i] == '[')\n                  defaultprop_[i] = '{';\n                else if(defaultprop_[i] == ']')\n                  defaultprop_[i] = '}'; *\/\n                else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n                  defaultprop_[i] = ',';\n                else if(defaultprop_[i] == '\\\"')\n                  defaultprop_[i] = '\\'';\n                else if(defaultprop_[i] == '@')\n                {\n                  defaultprop_.insert(i, 1, '\\\\');\n                  ++i;\n                }\n                else if(defaultprop_[i] == '\\n')\n                {\n                  defaultprop_.insert(i, 1, '\\\\');\n                  ++i;\n                }\n              }\n             }\n          )\n      );\n\n  #}}}4\n\n  #property body {{{4\n  propertybody = (\n    (prop)\n    |\n    ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n    |\n    ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n    );\n\n  properties := ( (\n    WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n        print_access_specifier(access_.full, methodparams_, propertyparams_);\n        }\n    . propertybody* )\n      );\n\n  #property body {{{4\n  eventbody = (\n    (prop)\n    |\n    ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n    |\n    ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n    );\n\n  events := ((\n    WSOC* . eventparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n        print_access_specifier(access_.full, methodparams_, propertyparams_);\n        }\n    . eventbody* )\n      );\n  #}}}4\n\n  #}}}2\n\n  # class body {{{2\n  classbody := |*\n\n    # a comment block\n    (comment_block)\n      => {\n        fout_.write(tmp_p, p - tmp_p);\n        fcall in_comment_block;\n      };\n\n    (WSOC); # => { fout_.write(ts, te-ts); };\n\n    (EOL) => { fout_ << \"\\n\"; };\n\n    ('end' . [ \\t]* ';'?) => {\n      std::map::iterator specIt;\n      for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n      {\n        fout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n        if ( (*specIt).second.dependent)\n        {\n          if( (*specIt).second.getter && ! (*specIt).second.setter )\n          {\n            fout_ << \"@note [readonly]\\n *\";\n          }\n        }\n        else\n        {\n          fout_ << \"@note This property has custom functionality when its value is \";\n          if ((*specIt).second.getter)\n          {\n            fout_ << \"retrieved\";\n            if ((*specIt).second.setter)\n              fout_ << \" or changed\";\n          }\n          else if ((*specIt).second.setter)\n            fout_ << \"changed\";\n          fout_ << \".\";\n        }\n        fout_ << \"\\n *\/\\n\";\n      }\n      fout_ << \"\\n};\\n\";\n      for(  list::iterator it = namespaces_.begin();\n            it != namespaces_.end(); ++it)\n      {\n        fout_ << \"}\\n\";\n      }\n    };\n\n    ([ \\t]* . 'properties')\n      => {\n        propertyparams_ = PropParams();\n        access_ = AccessStruct();\n        class_part_ = Property;\n        fgoto properties;\n      };\n    ([ \\t]* . 'methods')\n      => {\n        methodparams_ = MethodParams();\n        access_ = AccessStruct();\n        class_part_ = Method;\n        fgoto methodsheader;\n      };\n    ([ \\t]* . 'events')\n      => {\n        propertyparams_ = PropParams();\n        propertyparams_.event = true;\n        access_ = AccessStruct();\n        class_part_ = Event;\n        fgoto events;\n      };\n  *|; #}}}2\n\n  # doxyblock expect {{{2\n  # after function declaration expect a documentation block or the function\n  # body\n  expect_doxyblock :=\n  (\n    doc_begin\n      @{\n        \/\/fout_ << \"\/*\";\n        p--;\n        fgoto doxyheader;\n      }\n  )\n $!{\n    fhold;\n    {\n      int i = 0;\n      for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n        ;\n      std::string whitespaces(i, ' ');\n\/\/    if (string(p, 5) == \" if ~\")\n\/\/    {\n\/\/      debug_output(\"break;\", p);\n\/\/      fout_ << \"\/* start *\/\";\n\/\/    }\n\/\/    for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/      fout_ << *i;\n\/\/     fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n    debug_output(\"stopping expect_doxyblock\", p);\n#endif\n    if(is_class_)\n    {\n      if(class_part_ == Header)\n      {\n        end_of_class_doc();\n        fgoto classbody;\n      } else if(class_part_ == Method || class_part_ == AtMethod)\n      {\n        string endstringtest;\n        endstringtest.assign(p, 100);\n        string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n        if(runMode_.mode == RunMode::ParseParams)\n          return 1;\n        if (endstringtest.substr(first_char, 3) == \"end\")\n        {\n          p += first_char+4;\n          print_function_synopsis();\n          end_function();\n          fgoto methods;\n        }\n        else\n        {\n          print_function_synopsis();\n          fout_ << whitespaces;\n          fgoto funcbody;\n        }\n      }\n      else if(class_part_ == Property || class_part_ == Event)\n      {\n        fgoto propertybody;\n      }\n      else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n      {\n        class_part_ = Method;\n        fgoto methods;\n      }\n      else{\n        cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n      }\n    }\n    else\n    {\n      if(runMode_.mode == RunMode::ParseParams)\n        return 1;\n      print_function_synopsis();\n      fout_ << whitespaces;\n      fgoto funcbody;\n    }\n    }\n  };\n  #}}}2\n\n  # function declaration {{{2\n  funcdef = (\n      (WSOC)* .\n      # return values (if found opt = true)\n      (lparams)? .\n      # matlab identifier (function name stored in cfuncname_)\n      ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n        IDENT\n          >st_tok\n          %{\n            cfuncname_.assign(tmp_p, p - tmp_p);\n            #ifdef DEBUG\n              cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n            #endif\n            \/\/ in ParseMethodParams mode, we only check for the method\n            \/\/ parameters of a specific method.\n            if(is_class_ && class_part_ == MethodDeclaration\n               && runMode_.mode == RunMode::ParseMethodParams)\n            {\n              if(runMode_.methodname == cfuncname_)\n              {\n                return 0;\n              }\n            }\n            if(runMode_.mode == RunMode::Normal\n               && is_class_ && class_part_ == AtMethod)\n            {\n              update_method_params(cfuncname_);\n            }\n            is_script_ = false;\n          }\n      )\n      . WSOC*\n      . (\n           '('\n           # parameter list\n           . ( paramlist\n               %{\n                 if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n                 { paramlist_.clear(); }\n               }\n             )\n           . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n             . garble_comment_line_wo_eol) | ( ';' ) )*\n           . EOL\n           @{\n             if(comment_found)\n             {\n                tmp_string.assign(tmp_p+1, p - tmp_p-1);\n                tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n             }\n             else\n             {\n                tmp_string = \"\";\n             }\n             comment_found = false;\n             if(is_class_ && class_part_ == MethodDeclaration )\n             {\n               class_part_ = Method;\n               #if DEBUG\n                 debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n               #endif\n               fgoto methods;\n             }\n             else\n             {\n               \/\/               fout_ << tmp_string << \"{\\n\";\n               \/\/ check for documentation block\n               fgoto expect_doxyblock;\n             }\n           }\n        # no parameter list && first function => ( script || method )\n        | (( [ \\t]\n              |\n             ('%' @{ tmp_p=p; comment_found=true; }\n              . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n            @{\n                 if(comment_found)\n                 {\n                   tmp_string.assign(tmp_p+1, p - tmp_p-1);\n                   tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n                 }\n                 else\n                 {\n                   tmp_string = \"\";\n                 }\n                 comment_found = false;\n                 #if DEBUG\n                   debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n                 #endif\n                 if(is_class_ && class_part_ == MethodDeclaration)\n                 {\n                    class_part_ = Method;\n                    fgoto methods;\n                 }\n                 else\n                 {\n                   fgoto expect_doxyblock;\n                 }\n             }\n        )\n      );\n\n  funct :=\n  (\n    (\n      comment_block @in_c_block\n      | [ \\t]*. EOL\n    )*\n    . ([\\t]*) . 'function' . funcdef\n  ) $eof( end_of_file ) ; #}}}2\n\n  # no function definition => a script {{{2\n  script := (default)\n    @{\n       string :: size_type found = filename_.rfind(\"\/\");\n       if(found == string :: npos)\n         found = -1;\n       string funcname = filename_.substr(found+1, filename_.size()-3-found);\n       cfuncname_.assign( funcname );\n  \/*     fout_ << \"noret::substitute \";\n       if(!is_first_function_)\n         fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n       fout_ << funcname << \"() {\\n\";*\/\n       is_script_ = true;\n       fhold;\n       fgoto expect_doxyblock;\n     }; #}}}2\n\n  # class definitions {{{2\n  classparams =\n      '(' . [^)]* . ')';\n\n  superclass =\n    ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n                      @{ if(*p == '.')\n                           fout_ << \"::\";\n                         else fout_ << *p; } );\n\n  superclasses = (\n      '<' @{ fout_ << \"\\n  :\"; } . WSOC* . superclass . WSOC*\n          . ('&' @{ fout_ << \",\\n   \"; } . WSOC* . superclass . WSOC*)* );\n\n  classdef := (\n      'classdef' . WSOC* . ('(' . WSOC*\n        . (( 'Sealed'i\n          @{\n            docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n           }\n          )\n\n\t\t  |( 'Hidden'i\n          @{\n            docuextra_.push_back(std::string(\"@note This class has the class property 'Hidden' and is invisible.\"));\n           }\n          )\n          |( 'Abstract'i\n\t\t  @{\n\t\t    docuextra_.push_back(std::string(\"@note This class has the class property 'Abstract' and needs to be inherited in order to be instantiable.\"));\n\t\t   }\n\t\t   )) . [^)]* . ')')? . WSOC* .\n      # matlab identifier (class name stored in classname_)\n      ( IDENT\n          >st_tok\n          %{\n            classname_.assign(tmp_p, p - tmp_p);\n            is_class_ = true;\n            fout_ << \"class \" << classname_;\n          }\n      )\n      . WSOC*\n      . classparams?\n      . WSOC*\n      . superclasses?\n      . [ \\t;]*\n      . ( '%'. garble_comment_line_wo_eol )?\n      EOL\n      @{\n        fout_ << \" {\\n\";\n        fgoto expect_doxyblock;\n      } );\n\n  # }}}2\n\n  # main loop {{{2\n  expect_function_script_or_class =\n  (\n    # either we find a function or classdef definition with a possibly\n    # preceding comment block or we have a script\n    ( any\n       @{\n          fhold;\n          tmp_p = p;\n        }\n      .\n    (\n      [ \\t]*. '%' . (any - '\\n')* . EOL\n      | [ \\t]*. EOL\n    )*\n    . [\\t]*\n    . ( 'function' @{\n                     p-=8;\n                     char *tp;\n                     for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n                       ;\n                     funcindent_ = (int)(p - tp);\n#if DEBUG\n                     {\n                       ostringstream oss;\n                       oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n                       debug_output(oss.str(), p);\n                     }\n#endif\n                     if(is_class_ && class_part_ == Header)\n                       class_part_ = AtMethod;\n                     fgoto funct;\n                    }\n      | 'classdef' @{\n                     p-=8;\n                     fgoto classdef;\n                    }\n      ) )\n  $!{\n#ifdef DEBUG\n    debug_output(\"goto script\",p);\n#endif\n    p=tmp_p;\n    fgoto script;\n  }\n  );\n\n  main := expect_function_script_or_class*;\n  # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n  std::ios::sync_with_stdio(false);\n\n  fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n  fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n  fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n  fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n  fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n  fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n  fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n  fout_ << \" * the correct locations in the source code browser.\\n\";\n  fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n  \n  %% write init;\n\n  \/* Do the first read. *\/\n  bool done = false;\n  while ( !done )\n  {\n    char *p = buf + have;\n    char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n    string tmp_string, tmp_string2, tmp_string3;\n    bool docline = false;\n    bool latex_begin = true;\n    bool comment_found = false;\n    int space = BUFSIZE - have;\n\n    if ( space == 0 )\n    {\n      \/* We filled up the buffer trying to scan a token. *\/\n      cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n      exit(-1);\n    }\n\n    fin_.read( p, space );\n    int len = fin_.gcount();\n    char *pe = p + len;\n    char *rpe = pe;\n    char *eof = 0;\n\n    \/* If we see eof then append the EOF char. *\/\n    if ( fin_.eof() )\n    {\n      char eof_c = *pe;\n      *pe = '\\n';\n      pe++;\n      *pe = eof_c;\n      eof = pe;\n      rpe = pe;\n\n      done = true;\n    }\n    else\n    {\n      \/* Find the last newline by searching backwards. This is where\n       * we will stop processing on this iteration. *\/\n      while ( pe >= p )\n      {\n        if( *pe != '\\n')\n          pe--;\n        else\n        {\n          if(pe >= p+3\n              && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n            pe-=3;\n          else\n            break;\n        }\n      }\n    }\n\n    %% write exec;\n\n    \/* Check if we failed. *\/\n    if ( cs == MFileScanner_error )\n    {\n      \/* Machine failed before finding a token. *\/\n      cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n      debug_output(\"Grrrr!!!!\", p);\n      exit(-1);\n    }\n\n    \/* Now set up the prefix. *\/\n    if ( ts == 0 )\n    {\n      have = rpe - pe;\n      \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n      memmove( buf, pe, have );\n    }\n    else\n    {\n      have = rpe - ts;\n      \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n      memmove( buf, ts, have );\n    }\n\n    if ( ts != 0 )\n    {\n      te -= (ts-buf);\n      ts = buf;\n    }\n  }\n\n  return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","old_contents":"#include \"mfilescanner.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::ostringstream;\n\n%%{\n  machine MFileScanner;\n  write data;\n\n  # end of file character\n  EOF = 0;\n\n  # any character other than end of file\n  default = ^0;\n\n  # end of line character\n  EOL = ('\\r'? . '\\n') %{ ++line; };\n\n  # scanner for comment blocks\n  in_comment_block :=\n  (\n   ([ \\t]* >{ tmp_p = p; } .\n   # comment line begins with a percent sign\n   '%')\n     @{ fout_ << \"\\n\";\n        fout_.write(tmp_p, p - tmp_p);\n        tmp_p = p+1; fout_ << \" *\";\n      }\n   # and then some default characters\n   . (default - '\\n')* . EOL\n     @{ fout_.write(tmp_p, p - tmp_p); }\n  )*\n  $!{\n    fout_ << \" *\/\\n\";\n\/\/    if(is_getter_ || is_setter_)\n\/\/    {\n\/\/      fout_ << \"*\/\\n\";\n\/\/    }\n    fhold;\n    while (*p == ' ')\n      fhold;\n    if (extra_hold_in_cblock)\n    {\n      fhold;\n      --line;\n      extra_hold_in_cblock = false;\n    }\n    fret;\n  };\n\n  action end_doxy_block\n  {\n    if(!docline)\n    {\n      p = ts-1;\n      \/* go backward until first non-whitespace is found *\/\n      for(p=p-1; *p==' ' || *p == '\\t'; --p)\n        ;\n\n      if(is_class_)\n      {\n        if(class_part_ == Header)\n        {\n          end_of_class_doc();\n          fgoto classbody;\n        } else if(class_part_ == Method || class_part_ == AtMethod)\n        {\n          if(runMode_.mode == RunMode::ParseParams)\n            return 1;\n          print_function_synopsis();\n          fgoto funcbody;\n        }\n        else if(class_part_ == MethodDeclaration)\n        {\n          fgoto funcdef;\n        }\n        else if(class_part_ == Property || class_part_ == Event)\n        {\n          fgoto propertybody;\n        }\n        else if(class_part_ == InClassComment)\n        {\n          class_part_ = Method;\n          fgoto methods;\n        }\n        else\n        {\n          cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n        }\n      }\n      else\n      {\n        if(runMode_.mode == RunMode::ParseParams)\n          return 1;\n        print_function_synopsis();\n        fgoto funcbody;\n      }\n    }\n  }\n\n  # executed when end of file is reached\n  action end_of_file\n  {\n    end_function();\n    for(  list::iterator it = namespaces_.begin();\n          it != namespaces_.end(); ++it)\n    {\n      fout_ << \"};\\n\";\n    }\n  }\n\n  # executed when we reached a comment block\n  action in_c_block\n  {\n    assert(p >= tmp_p-1);\n    fout_.write(tmp_p, p-tmp_p+1);\n    fcall in_comment_block;\n  }\n\n  action echo { fout_ << fc; }\n\n  action st_tok { tmp_p = p; }\n\n  action st_tok2 { tmp_p2 = p; }\n\n  action echo_tok {\n    assert (p >= tmp_p);\n    fout_.write(tmp_p, p - tmp_p);\n  }\n\n  action string_tok {\n    assert ( p >= tmp_p );\n    tmp_string.assign(tmp_p, p-tmp_p);\n  }\n\n  # common definitions {{{2\n\n  # comment in function body that might also be added to the doxygen block for\n  # the function description\n  is_doxy_comment =\n    (\n    # RAGEL comment: if percent character is followed by a bar we make the comment a doxygen\n    # comment\n     '|' @{ \n\/\/    if(is_getter_ || is_setter_)\n\/\/            {\n\/\/              fout_ << \"*\/\";\n\/\/            }\n            fout_ << \"\/**\"; tmp_p = p+1;\n          }\n     . (default - '\\n')*\n     . ( EOL . [ \\t]*\n       . '%' @{\n                assert(p >= tmp_p -1);\n                fout_.write(tmp_p, p - tmp_p);\n                fout_ << \" * \";\n                tmp_p = p+1;\n              }\n     . (default - '\\n')* )* . EOL\n     |\n    # RAGEL comment: else: a regular comment\n     ( (default - '|')\n       @{\n\/\/         if(is_getter_ || is_setter_)\n\/\/         {\n\/\/           fout_ << \"\\n#endif\\n\";\n\/\/         }\n         if (string(p, 8) != string(\"@@remove\"))\n           fout_ << \"\/* \";\n         tmp_p = p;\n         } )\n     . (default - '\\n')* . EOL\n    );\n\n  # comment block in function body\n  comment_block = (( [ \\t]* >(st_tok)  . '%') @{fout_.write(tmp_p, p - tmp_p);}) . is_doxy_comment;\n\n  # an empty line\n  empty_line = [\\t ]* . EOL;\n\n  # documentation line begin\n  doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n  # swallow a comment line till the end of the line (make it a c comment)\n  garble_comment_line =\n    ( (default - [\\r\\n])* . EOL )\n      @{\n\/\/        if(is_getter_ || is_setter_)\n\/\/        {\n\/\/          fout_ << \"\\n#endif\\n\";\n\/\/        }\n        fout_ << \"\/* \";\n        assert( p >= tmp_p );\n        fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n\/\/        if(is_getter_ || is_setter_)\n\/\/        {\n\/\/          fout_ << \"\\n#if 0\\n\";\n\/\/        }\n      };\n  garble_comment_line_wo_eol =\n    (default - [\\r\\n])*;\n\n  # white space or comment\n  WSOC =\n    ( ([ \\t]+ \n       @{\n          {\n            int i=0;\n            if (*(p+1) != ' ' && *(p+1) != '\\t')\n            {\n              while (*(p-i) == ' ' || *(p-i) == '\\t')\n                i++;\n              if (*(p-i) == '\\n')\n                fout_ << std::string(i, ' ');\n            }\n          }\n        })\n      | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n      | ('...'.[ \\t]*.EOL)\n    );\n\n  # white space or line continuation\n  WS =\n    ( [ \\t]+\n      | ('...'.[\\t]*.EOL)\n    );\n\n  # matlab identifier\n  IDENTEND = [A-Za-z0-9_];\n  IDENT = [A-Za-z_]IDENTEND**;\n\n\n  # matlab identifier with .\n  IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n  # default arguments in function declarations\n  default_arg = ([^,)\\n] | EOL)** @echo;\n\n  #}}}2\n\n  # parameter list for functions {{{2\n  paramlist =\n    (\n     (WSOC | ',' | EOL\n     | ( '=' . default_arg ) )+\n     |\n     # matlab identifier (parameter)\n     (IDENT | '~' )\n       >st_tok\n       %{\n         assert(p >= tmp_p);\n         string s(tmp_p, p - tmp_p);\n         bool addBlock = true;\n         \/\/ do not print this pointer\n         if( is_class_ && ( !methodparams_.statical\n                            && (\n                                ( class_part_ == Method\n                                  && cfuncname_ != classname_\n                                )\n                                || class_part_ == AtMethod\n                                || class_part_ == MethodDeclaration\n                               )\n                          )\n                       && ( ! (\n                               methodparams_.abstr\n                               && !runMode_.remove_first_arg_in_abstract_methods\n                              )\n                          )\n           )\n         {\n            if(paramlist_.empty())\n            {\n              addBlock = false;\n              paramlist_.push_back(string(\"this\"));\n            }\n            else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n              paramlist_.clear();\n         }\n\n         if(addBlock) {\n\n#ifdef DEBUG\n{\n  ostringstream oss;\n  oss << \"found parameter: \" << s;\n  debug_output(oss.str(), p);\n}\n#endif\n           postprocess_unused_params(s, param_list_);\n           \/\/ add an empty docu block for parameter \\a s\n           if(param_list_.find(s) == param_list_.end())\n           {\n             param_list_[s] = DocuBlock();\n           }\n#ifdef DEBUG\n{\n  ostringstream oss;\n  oss << \"in paramlist: add to paramlist: \" << s;\n  debug_output(oss.str(), p);\n}\n#endif\n           paramlist_.push_back(s);\n         }\n       }\n    )**;\n\n  \n  matrix_or_cell := (\n      '[' . ( [^[{\\]\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n      |\n      '{' . ( [^[{}\\n] | EOL | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n      );\n\n  matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n  \n  \n  # return parameter list for functions\n  lparamlist =\n    ( (WSOC | EOL )+\n      | ','\n      # matlab identifier (return value)\n      | ( (IDENT | '~') > st_tok\n          %{\n            assert(p >= tmp_p);\n            string s(tmp_p, p - tmp_p);\n            postprocess_unused_params(s, return_list_);\n            returnlist_.push_back(s);\n            \/\/ add an empty docu block for return value \\a s\n            if(return_list_.find(s) == return_list_.end())\n            {\n              return_list_[s] = DocuBlock();\n            }\n          }\n        )\n    )**;\n\n  # return parameter or return parameter list\n  lparams =\n    (\n      (\n        (\n         # matlab identifier\n         ( IDENT | '~' )\n           >st_tok\n           %{\n             assert(p >= tmp_p);\n             string s(tmp_p, p - tmp_p);\n             postprocess_unused_params(s, return_list_);\n             returnlist_.push_back(s);\n             \/\/ add an empty docu block for single return value \\a s\n\n             if(return_list_.find(s) == return_list_.end())\n             {\n               return_list_[s] = DocuBlock();\n             }\n#ifdef DEBUG\n  cerr << \"\\n In return list: \" << endl;\n#endif\n           }\n        )\n        | ( '['\n          . lparamlist\n          . ']'\n          )\n      )\n      . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n      :> '=' . WSOC*\n    );\n    # }}}2\n\n  # a line in the function body {{{2\n  funcline := |*\n    # empty line\n    ([ \\t]+)\n      => { fout_.write(ts, te-ts); };\n\n    # line continuation\n    ('...' . [ \\t]* . EOL)\n      => { fout_.write(ts, te-ts); };\n\n    # two single quote in a row need to be changed to nothing\n    ('\\'\\'');\n\n    # a string should not be parsed for comment blocks, so we handle it separately.\n    ('\\'' . [^'\\n]+ . '\\'')\n      => {\n           \/\/ change double quotes to quotes and vice versa...\n           fout_ << \"\\\" \";\n           string s(ts+1, te-ts-2);\n           std::replace(s.begin(), s.end(), '\\\"', '\\'');\n           fout_ << s;\n           fout_ << \" \\\"\";\n         };\n\n    # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n    (comment_block)\n      => {\n           assert(p >= tmp_p);\n           fout_.write(tmp_p, p - tmp_p);\n           extra_hold_in_cblock = true;\n           fcall in_comment_block;\n         };\n\n     (IDENT %{tmp_string.assign(ts,p-ts);})\n     . [ \\t]* . '=' . [ \\t]* . 'inputParser' . [ \\t]* . ';'\n     {\n#ifdef DEBUG\n std::cerr << \"Found varargin parser candidate: \" << tmp_string << std::endl;\n#endif\n       varargin_parser_candidate_ = tmp_string;\n     };\n\n     ('addRequired' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok) %{tmp_string.assign(tmp_p, p - tmp_p);})\n       . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n       => {\n         fout_.write(ts, te-ts);\n         if (tmp_string == varargin_parser_candidate_ )\n         {\n           varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n         }\n       };\n     \n     ((IDENT %{tmp_string.assign(ts, p - ts);})\n         . '.addRequired' . [ \\t]* . '(' . [ \\t]* \n         . '\\'' . (IDENT > (st_tok) %{tmp_string2.assign(tmp_p, p - tmp_p);}) . '\\'' )\n       => {\n         fout_.write(ts, te-ts);\n         if (tmp_string == varargin_parser_candidate_ )\n         {\n           varargin_parser_values_[tmp_string2] = make_pair(0, \"\");\n #ifdef DEBUG\n std::cerr << \"Found required varargin: \" << tmp_string2 << std::endl;\n #endif\n         }\n       };\n\n\n    ('addOptional' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n      . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n    \n    ((IDENT %{tmp_string.assign(ts, p - ts);})\n      . '.addOptional' . [ \\t]* . '(' . [ \\t]* \n      . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);} ) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(1, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found optional varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n\n\n    ('addParamValue' . [ \\t]* . '(' . [ \\t]* . (IDENT > (st_tok2) %{tmp_string.assign(tmp_p2, p - tmp_p2);})\n      . [ \\t]* . ',' . [ \\t]* . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL ) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n    \n    ((IDENT %{tmp_string.assign(ts, p - ts);})\n      . '.addParamValue' . [ \\t]* . '(' . [ \\t]*\n      . '\\'' . (IDENT > (st_tok2) %{tmp_string2.assign(tmp_p2, p - tmp_p2);}) . '\\''\n      . [ \\t]* . ',' . [ \\t]* . ( [^;\\n]* > (st_tok2) %{tmp_string3.assign(tmp_p2, p - tmp_p2);}) . (';' | EOL) )\n      => {\n        fout_.write(ts, te-ts);\n        if (tmp_string == varargin_parser_candidate_ )\n        {\n          extract_default_argument_of_inputparser(tmp_string3);\n          varargin_parser_values_[tmp_string2] = make_pair(2, tmp_string3);\n#ifdef DEBUG\nstd::cerr << \"Found param value for varargin: \" << tmp_string2 << \" with default value \" << tmp_string3 << std::endl;\n#endif\n        }\n        if (*p == '\\n')\n          fgoto funcbody;\n      };\n\n\n    # automatically add return value fields to retval_list_\n    (\n     # matlab identifier (which can be a return value and a structure)\n     (IDENT\n        %{tmp_string.assign(ts,p-ts);})\n     . '.'\n     # matlab identifer (fieldname)\n     . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n     # RAGEL comment: if a value is assigned to this field, the field is generated\/modified\n     . [ \\t]* . '=' . (^'=')\n    )\n    => {\n      fhold;\n      \/\/ store fieldname\n      assert(tmp_p2 >= tmp_p);\n      string s(tmp_p, tmp_p2 - tmp_p);\n      fout_ << tmp_string << \".\" << s << \"=\";\n      \/\/ typedef of iterators\n      typedef DocuList     :: iterator list_iterator;\n      typedef DocuListMap  :: iterator map_iterator;\n      typedef DocuBlock    :: iterator iterator;\n\n      \/\/ check wether first IDENT is a return value\n      iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n      if(it != returnlist_.end())\n      {\n        \/\/ if it is a return value...\n        \/\/ ... check wether its found field is still missing a DocuBlock in the\n        \/\/ retval list.\n        bool missing = true;\n        map_iterator rvoit = retval_list_.find(tmp_string);\n        if(rvoit != retval_list_.end())\n        {\n          list_iterator lit = (*rvoit).second.find(s);\n          if(lit != (*rvoit).second.end())\n            missing = false;\n        }\n        \/\/ if it is missing, add an empty docu block\n        if(missing)\n        {\n          retval_list_[tmp_string][s] = DocuBlock();\n        }\n      }\n    };\n\n    # automatically add parameter fields to required_list_\n    (\n     # matlab identifier (which can be a parameter and a structure)\n     (IDENT\n        %{tmp_string.assign(ts,p-ts);})\n     . '.'\n     # matlab identifer (fieldname)\n     . (IDENT_W_DOT\n         >(st_tok)\n       )\n    )\n    => {\n      \/\/ store fieldname\n      assert(p >= tmp_p);\n      string s(tmp_p, p - tmp_p+1);\n      fout_ << tmp_string << \".\" << s;\n      typedef DocuList     :: iterator list_iterator;\n      typedef DocuListMap  :: iterator map_iterator;\n      typedef DocuBlock    :: iterator iterator;\n\n      \/\/ check wether first IDENT is a parameter\n      iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n      if(it != paramlist_.end())\n      {\n        \/\/ if it is a parameter ...\n        \/\/ ... check wether its found field is still missing a DocuBlock in the\n        \/\/ return, optional and the required list.\n        bool missing = true;\n        map_iterator rvoit = retval_list_.find(tmp_string);\n        if(rvoit != retval_list_.end())\n        {\n          list_iterator lit = (*rvoit).second.find(s);\n          \/\/ found match in retval list\n          if(lit != (*rvoit).second.end())\n            missing = false;\n        }\n        map_iterator moit = optional_list_.find(tmp_string);\n        if(moit != optional_list_.end())\n        {\n          \/\/ found match in optional list\n          list_iterator lit = (*moit).second.find(s);\n          if(lit != (*moit).second.end())\n            missing = false;\n        }\n        map_iterator roit = required_list_.find(tmp_string);\n        if(roit != required_list_.end())\n        {\n          \/\/ found match in required list\n          list_iterator lit = (*roit).second.find(s);\n          if(lit != (*roit).second.end())\n            missing = false;\n        }\n        \/\/ in case it IS missing, add an empty field to the required block.\n        if(missing)\n        {\n          required_list_[tmp_string][s] = DocuBlock();\n        }\n      }\n    };\n\n    # add a @deprecated command to function declaration if disp_deprecated is\n    # used in function body\n    ('disp_deprecated' . [ \\t]*\n      . (\n          ';'\n            @{tmp_string.assign(\"\");}\n          |\n          '(' . [\\t ]* . \"'\"\n          . ([^\\n']*\n              >(st_tok)\n              %(string_tok)\n            )\n          . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n        )\n      . [\\t ]* . EOL\n    )\n      => {\n        string s;\n        if(tmp_string.empty())\n        {\n          s.assign(\"@deprecated function deprecated\\n\");\n        }\n        else\n        {\n          s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n        }\n        docuextra_.push_back(s);\n        fhold;\n      };\n\n    # simple matlab identifier\n    (IDENT)\n      => { fout_.write(ts, te-ts); };\n\n    # translate curly brackets in edgy brackets, because otherwise the doxygen\n    # parser breaks.\n    ('{')\n      => { fout_ << '['; };\n\n    ('}')\n      => { fout_ << ']'; };\n    \n    ('\\'')\n      => { fout_ << \"^t\"; };\n\n    # simply output all other characters\n    (default - [\\n{}\\'])\n      => { fout_ << fc; };\n\n    # after EOL try to check for new function\n    EOL\n      => { fout_ << fc; fgoto funcbody; };\n\n  *|;\n  # }}}2\n\n  # function body {{{2\n  funcbody := |*\n\n      # things that got replaced in function body {{{4\n      ('% TO BE ADJUSTED TO NEW SYNTAX' . EOL)\n        => {\n          new_syntax_ = true;\n          fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n        };\n\n      ([ \\t]* . '%@@remove' . ((default - '%') | ('%' . (default - '@')) | ('%' . '@' .  (default -'@')))* . '%@@endremove');\n\n      # a comment block\n      ( ([ \\t]* . '%' @{ fout_.write(ts, p - ts); }) . is_doxy_comment)\n        => {\n          assert(p >= tmp_p);\n          fout_.write(tmp_p, p - tmp_p);\n          fcall in_comment_block;\n        };\n\n      # empty line\n      ([ \\t]* . EOL)\n        => { fout_ << '\\n'; };\n\n      #}}}4\n\n      # line not beginning with words 'function' or 'end'\n      ([ \\t]*\n       . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n      )\n        => {\n          p = ts-1;\n          \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n          fgoto funcline;\n        };\n\n      # things that could end the function body {{{4\n      # line only containing word 'end'\n      # the keyword needs to be in the same indentation level as beginning function\n      ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n          => {\n              if(is_class_ && class_part_ == Method)\n              {\n                tmp_string.assign(ts,p-ts+1);\n\n                if(tmp_string.find(\"e\") == funcindent_)\n                {\n                  end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n                  fgoto methods;\n                }\n              }\n              \/\/ else\n              p=ts-1;\n              \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n              fgoto funcline;\n          };\n\n      # line beginning with word 'function'\n      ([ \\t]*. 'function ')\n      {\n        tmp_string.assign(ts,p-ts+1);\n        p = ts-1;\n\n        if (!is_class_ && tmp_string.find(\"f\") <= funcindent_)\n        {\n          \/\/ end the previous function if existent\n          end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n          fgoto main;\n        }\n        else\n        {\n          fgoto funcline;\n        }\n      };\n\n      (EOF) $eof(end_of_file);\n\n      # }}}4\n\n  *|;\n   # }}}2\n\n  # fill a docublock list with input {{{2\n  fill_list := |*\n\n  # match an argument\n  ( doc_begin . [ \\t]*\n    . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*)  >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n    . ( default - '\\n' )* . EOL\n  )\n    => {\n      assert(tmp_p2 >= tmp_p3);\n      tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n      \/\/    std::fout_ << tmp_string << '\\n';\n      assert(p >= tmp_p);\n      (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n    };\n\n  # expand the paragraph for last argument matched\n  ( doc_begin . [ \\t]*\n    # at least one word (non white-space characters and no double-colon)\n    . ( default - [ \\r\\t:\\n] )+ .\n    # followed by something that is a white-space or a new-line, i.e *no*\n    # double-colon\n    (\n     EOL\n     |\n     [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n     # [ \\t] . (default - '\\n')* . EOL\n    )\n  )\n    => {\n      assert(p+1 >= tmp_p);\n      string s(tmp_p, p - tmp_p + 1);\n      (*clist_)[tmp_string].push_back(s);\n      \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n    };\n\n  # return on empty line\n  ( doc_begin . [ \\t]* . EOL )\n    => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n   # end of comment block\n  ( [\\t ]* . ( (default - '%') | EOL) )\n    => {\n      p =ts-1;\n      \/\/ fout_ << \"*\/\\n\";\n      fret;\n    };\n\n  *|; #}}}2\n\n  # parse body of documentation block {{{2\n  doxy_get_body := |*\n\n    # special lists {{{4\n\n    # begin required_list\n    ( doc_begin . [ \\t]*\n      . \/required fields of \/i\n      . (IDENT >(st_tok) %(string_tok) )\n      . [ \\t]* . ':' . [ \\t]* . EOL\n    )\n      => {\n        \/\/fout_ << tmp_string << '\\n';\n        clist_ = &(required_list_[tmp_string]);\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin optional_list\n    ( doc_begin . [ \\t]*\n      . \/optional fields of \/i\n      . (IDENT\n          >(st_tok)\n          %(string_tok) )\n      . [ \\t]* . ':' . [ \\t]* . EOL )\n      => {\n        clist_ = &(optional_list_[tmp_string]);\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin optional_list\n    ( doc_begin . [ \\t]*\n      . \/generated fields of \/i\n      . (IDENT\n          >(st_tok)\n          %(string_tok) )\n      . [ \\t]* . ':' . [ \\t]* . EOL )\n      => {\n        clist_ = &(retval_list_[tmp_string]);\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin parameter list\n    ( doc_begin . [ \\t]*\n      . \/parameters\/i . [ \\t]* . ':'\n      . [ \\t]* . EOL )\n      => {\n        clist_ = ¶m_list_;\n        docline = false;\n        fcall fill_list;\n      };\n\n    # begin return list\n    ( doc_begin . [ \\t]*\n      . \/return values\/i . [ \\t]* . ':'\n      . [ \\t]* . EOL )\n      => {\n        clist_ = &return_list_;\n        docline = false;\n        fcall fill_list;\n      };\n    #}}}4\n\n    # default substitutions {{{4\n\n    # empty line\n    ( doc_begin . [ \\t]* . EOL )\n      => {\n        \/*fout_ << \"*\\n  \";*\/\n        docubody_.push_back(\"\\n\");\n        docline = false;\n      };\n\n    # paragraph line\n    ( [ \\t]* . '%' )\n      => {\n        if(!docline)\n        {\n          docline = true;\n          tmp_p = p;\n        }\n      };\n\n    # paragraph line with \"see also\" substituted by \"@sa\"\n    ( \/see also\/i . ':'? )\n      => {\n        string s;\n        assert(ts > tmp_p);\n        s.assign(tmp_p+1, ts - tmp_p-1);\n        docubody_.push_back(s+\"@sa\");\n        tmp_p = p;\n      };\n\n    # lines that could end doxyblock {{{6\n    # words\n    #  RAGEL comment:  ( default - [ \\t:%'`\\n] )+\n    ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n    # non-words\/non-whitespace\n    #  RAGEL comment:  ([:'`]) => {\n    (':') @(end_doxy_block) ;\n\n\n    # whitespace only\n    ( [ \\t] );\n\n    # titled paragraph\n    ( ':' . EOL )\n      @(end_doxy_block)\n      @{ if(docline)\n         {\n           assert(ts > tmp_p);\n           docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n           docline = false;\n         }\n       };\n    # }}}6\n    # }}}4\n\n    # end of line {{{4\n    ( EOL )\n       @(end_doxy_block)\n       @{ if(docline)\n          {\n            int offset = ( latex_begin ? 0 : 1 );\n            assert(p >= tmp_p + offset);\n            docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n            docline = false;\n          }\n        };\n      # }}}4\n\n  *|;\n  #}}}2\n\n  # doxy header parsing {{{2\n  # swallow the synopsis line\n  doxyfunction_garble := |*\n    garbage = ( (default - '\\n' )* -- '...' );\n\n    ( doc_begin . (garbage . '...')+ . [\\t ]* .  EOL );\n\n    ( doc_begin . (garbage . '...')* . garbage . EOL )\n      => { fgoto doxy_get_brief; };\n  *|;\n\n\n  # read first paragraph\n  doxy_get_brief := |*\n\n    # read in one comment line\n    ( doc_begin . [\\t ]*\n      . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n    )\n      => {\n        \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n        assert(p >= tmp_p);\n        docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n      };\n\n    # empty line\n    ( doc_begin . [\\t ]* . EOL )\n      => {\n        \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n  debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n        fgoto doxy_get_body;\n      };\n\n    # end of comment block;\n    ( [\\t ]* . [^%] )\n      => {\n        p=ts-1;\n#ifdef DEBUG\n   debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n        \/\/fout_ << \"*\/\\n\";\n        if(is_class_)\n        {\n#ifdef DEBUG\n  debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n          if(class_part_ == Header)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto classbody\",p);\n#endif\n            end_of_class_doc();\n            fgoto classbody;\n          } else if(class_part_ == Method || class_part_ == AtMethod)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n            if(runMode_.mode == RunMode::ParseParams)\n              return 1;\n            print_function_synopsis();\n            fgoto funcbody;\n          }\n          else if(class_part_ == MethodDeclaration)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n            fgoto funcdef;\n          }\n          else if(class_part_ == Property || class_part_ == Event)\n          {\n#ifdef DEBUG\n  debug_output(\"  in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n            fgoto propertybody;\n          }\n          else if(class_part_ == InClassComment)\n          {\n            class_part_ = Method;\n            fgoto methods;\n          }\n        }\n        else\n        {\n          if(runMode_.mode == RunMode::ParseParams)\n            return 1;\n          print_function_synopsis();\n          fgoto funcbody;\n        }\n      };\n\n  *|;\n  # }}}2\n\n  # garble synopsis line and then parse the documentation header {{{2\n  doxyheader := (\n    '%' . [ \\t]* .\n       (\n        ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n       )\n      $!{\n#ifdef DEBUG\n        debug_output(\"doxy_get_brief\",p);\n#endif\n        p = tmp_p - 2;\n        fgoto doxy_get_brief;\n      }\n   ); #}}}2\n\n  # access specifier expressions\n  spec_public = ( 'public'i | \"'public'\"i );\n  spec_protected = ( 'protected'i | \"'protected'\"i );\n  spec_private = ( 'private'i | \"'private'\"i );\n  \n  spec_class_single = \n\t (\n\t   ('?' . (IDENT_W_DOT**) >st_tok )\n\t   %{\n\t\t\ttmp_string.assign(tmp_p, p - tmp_p);\n\t\t\t\/\/cerr << \"Detected \" << access_.state << \" modifier by class \" << tmp_string << \"\\n\";\n\t\t\taccess_.classMemberAccess.push_back(make_pair(access_.state, tmp_string));\n        }\n     ) . WS*;\n  \n  spec_class_multi = '{' . WS* . spec_class_single . ( [,; ] . WS* . spec_class_single )* . '}';\n  \n  spec_classes = ( spec_class_single | spec_class_multi );\n    \n  # helper for setting the access specifier {{{2\n  paramaccess =\n    ( ('SetAccess' @{ access_.state = SetAccess; } . WS* . '=' . WS*\n      . ( ( spec_public \n            %{ access_.full = Public; access_.set = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.get == Public ? Public : Protected );\n               access_.set = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.get; access_.set = Private;\n             } )\n        )\n      )\n     | ( 'GetAccess' @{ access_.state = GetAccess; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.get = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.set == Public ? Public : Protected );\n               access_.get = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.set; access_.get = Private;\n             } )\n        )\n       )\n     | ( 'Access' @{ access_.state = Access; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.get = Public; access_.set = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = Protected; access_.get = Protected; access_.set = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = Private; access_.get = Private; access_.set = Private;\n             } )\n          )\n     )\n    ); #}}}2\n\n  eventparam =\n    ( ('ListenAccess' @{ access_.state = ListenAccess; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.get = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.set == Public ? Public : Protected );\n               access_.get = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.set; access_.get = Private;\n             } )\n        )\n      )\n     | ( 'NotifyAccess' @{ access_.state = NotifyAccess; } . WS* . '=' . WS*\n      . ( ( spec_public\n            %{ access_.full = Public; access_.set = Public;\n             } )\n        | ( ( spec_protected | spec_classes )\n            %{ access_.full = (access_.get == Public ? Public : Protected );\n               access_.set = Protected;\n             } )\n        | ( spec_private\n            %{ access_.full = access_.get; access_.set = Private;\n             } )\n        )\n       )\n     | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.hidden = true;\n         } )\n     );\n\n  # method and property params {{{2\n  methodparam =\n   (\n    ( paramaccess )\n    | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.abstr = true;\n         } )\n    | ( ( 'Static' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.statical = true;\n         } )\n    | ( ('Hidden' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.hidden = true;\n         } )\n    | ( ( 'Sealed' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.sealed = true;\n         } )\n    | ( ( 'Test' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.test = true;\n         } )\n    | ( ( 'TestMethodSetup' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.testMethodSetup = true;\n         } )\n    | ( ( 'TestMethodTeardown' . ([^,)\\n] | EOL)* )\n        @{\n           methodparams_.testMethodTeardown = true;\n         } )\n   );\n\n  propertyparam =\n   (\n    ( paramaccess )\n    | ( ( 'Constant' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.constant = true;\n         } )\n    | ( ( 'Transient' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.transient = true;\n         } )\n    | ( ( 'Dependent' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.dependent = true;\n         } )\n    | ( ( 'Hidden' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.hidden = true;\n         } )\n    | ( ( 'SetObservable' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.setObservable = true;\n         } )\n    | ( ( 'Abstract' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.abstr = true;\n         } )\n    | ( ( 'AbortSet' . ([^,)\\n] | EOL)* )\n        @{\n           propertyparams_.abortSet = true;\n         } )\n   );\n\n  methodparams =\n   (\n    '(' . WSOC*\n    . methodparam\n    . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n   );\n\n  eventparams =\n   (\n    '(' . WSOC*\n    . eventparam\n    . ( WSOC* . ',' . WSOC* . eventparam )* . WSOC* . ')'\n   ); #}}}2\n\n  propertyparams =\n   (\n    '(' . WSOC*\n    . propertyparam\n    . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n   ); #}}}2\n\n  # methods and properties {{{2\n  # methods {{{4\n  methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n    (empty_line) => {\n      if(runMode_.mode != RunMode::ParseMethodParams)\n      {\n        end_method();\n        fout_ << \"\\n\";\n      }\n    };\n\n    # default: method definition\n    ([ \\t]* . 'function' )\n      => {\n        tmp_string.assign(ts, te - ts+1);\n        funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n        fout_ << string(ts, ts+funcindent_);\n        #if DEBUG\n            {\n              ostringstream oss;\n              oss << \"in methods: funcindent: \" << funcindent_;\n              debug_output(oss.str(), p);\n            }\n        #endif\n        p=ts+funcindent_-1;\n        fgoto funct;\n       };\n\n    # end of methods block\n    ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n      => {\n           if(runMode_.mode != RunMode::ParseMethodParams)\n           {\n             end_method();\n             #if DEBUG\n               debug_output(\"in methods: found end keyword, goto classbody\",p);\n             #endif\n           }\n           fgoto classbody;\n         };\n\n    # comment between two methods\n    ([ \\t]* . '%' ) => {\n      #if DEBUG\n        debug_output(\"in methods: garble comment line\",p);\n      #endif\n\n      p = ts-1;\n      class_part_ = InClassComment;\n\/*      fcall in_comment_block; *\/\n      fgoto expect_doxyblock;\n    };\n\n    # if we reach this: method declaration without definition is found\n    ([ \\t]* . [^% \\t\\n]) =>\n    {\n      #if DEBUG\n        debug_output(\"in methods: found method declaration, going to funcdef\",p);\n      #endif\n      class_part_ = MethodDeclaration;\n      p = ts-1;\n      fgoto funcdef;\n    };\n\n      *|;\n\n\n  methodsheader := (\n    [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n         @{\n            print_access_specifier(access_.full, methodparams_, propertyparams_);\n            fgoto methods;\n          }\n          );\n\n   #}}}4\n\n  # single property {{{4\n  prop = ( ( [ \\t]* . (IDENT) >st_tok\n            %{\n              {\n                char *i = tmp_p-1;\n                for (; *i == ' ' || *i == '\\t'; --i)\n                  fout_ << *i;\n              }\n              \n              end_of_property_doc();\n              string s(tmp_p, p - tmp_p);\n              if (s == \"end\")\n                fgoto classbody;\n              if (propertyparams_.dependent)\n                specifier_[s].dependent = true;\n              property_list_.push_back(s);\n              \/\/            fout_ << propertyparams_.ccprefix() << \" \" << s;\n              undoced_prop_ = true;\n            }\n          )\n        . WS* . ( ( '%' @{ fhold; } | ';' | EOL )  @{defaultprop_ = \"\";}\n            |\n            ( ('=' . [ ]*) %{tmp_p2 = p;} . ( matrix | [^[{;\\n%] | ('...'.[ \\t]*.EOL) )* . (';' | EOL | '%' @{fhold; } ))\n            @{\n              defaultprop_ = string(tmp_p2, p - tmp_p2);\n              string::size_type last_elem = defaultprop_.length() -1;\n              if(defaultprop_[0] == '\\'' && defaultprop_[last_elem] == '\\'')\n              {\n                defaultprop_[0] = '\\\"';\n                defaultprop_[last_elem] = '\\\"';\n              }\n              string::size_type first_paren = defaultprop_.find_first_of(\"([{\");\n              string::size_type last_paren;\n              if (first_paren == string::npos)\n              {\n                first_paren = 1;\n                last_paren = last_elem;\n              }\n              else\n              {\n                last_paren = defaultprop_.find_last_of(\")]}\");\n                if (last_paren == string::npos)\n                  last_paren=last_elem-1;\n                else\n                {\n                  if((first_paren >0 && defaultprop_[first_paren] == '(') || defaultprop_[first_paren] == '{')\n                  {\n                    first_paren++;\n                    last_paren--;\n                  }\n                  defaultprop_.insert(first_paren, 1,'\"');\n                  defaultprop_.insert(last_paren+2, 1,'\"');\n                  first_paren++;\n                  last_paren++;\n                }\n              }\n              for (unsigned int i = first_paren; i < last_paren; ++i)\n              {\n                if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n                {\n                  defaultprop_[i]   = ' ';\n                  defaultprop_[i+1] = ' ';\n                  defaultprop_[i+2] = ' ';\n                }\n\/*                else if(defaultprop_[i] == '[')\n                  defaultprop_[i] = '{';\n                else if(defaultprop_[i] == ']')\n                  defaultprop_[i] = '}'; *\/\n                else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n                  defaultprop_[i] = ',';\n                else if(defaultprop_[i] == '\\\"')\n                  defaultprop_[i] = '\\'';\n                else if(defaultprop_[i] == '@')\n                {\n                  defaultprop_.insert(i, 1, '\\\\');\n                  ++i;\n                }\n                else if(defaultprop_[i] == '\\n')\n                {\n                  defaultprop_.insert(i, 1, '\\\\');\n                  ++i;\n                }\n              }\n             }\n          )\n      );\n\n  #}}}4\n\n  #property body {{{4\n  propertybody = (\n    (prop)\n    |\n    ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n    |\n    ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n    );\n\n  properties := ( (\n    WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n        print_access_specifier(access_.full, methodparams_, propertyparams_);\n        }\n    . propertybody* )\n      );\n\n  #property body {{{4\n  eventbody = (\n    (prop)\n    |\n    ( (empty_line) @{ end_of_property_doc(); fout_ << \"\\n\";} )\n    |\n    ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n    );\n\n  events := ((\n    WSOC* . eventparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n        print_access_specifier(access_.full, methodparams_, propertyparams_);\n        }\n    . eventbody* )\n      );\n  #}}}4\n\n  #}}}2\n\n  # class body {{{2\n  classbody := |*\n\n    # a comment block\n    (comment_block)\n      => {\n        fout_.write(tmp_p, p - tmp_p);\n        fcall in_comment_block;\n      };\n\n    (WSOC); # => { fout_.write(ts, te-ts); };\n\n    (EOL) => { fout_ << \"\\n\"; };\n\n    ('end' . [ \\t]* ';'?) => {\n      std::map::iterator specIt;\n      for (specIt = specifier_.begin(); specIt != specifier_.end(); specIt++)\n      {\n        fout_ << \"\/** @var \" << (*specIt).first << \"\\n *\\n *\";\n        if ( (*specIt).second.dependent)\n        {\n          if( (*specIt).second.getter && ! (*specIt).second.setter )\n          {\n            fout_ << \"@note [readonly]\\n *\";\n          }\n        }\n        else\n        {\n          fout_ << \"@note This property has custom functionality when its value is \";\n          if ((*specIt).second.getter)\n          {\n            fout_ << \"retrieved\";\n            if ((*specIt).second.setter)\n              fout_ << \" or changed\";\n          }\n          else if ((*specIt).second.setter)\n            fout_ << \"changed\";\n          fout_ << \".\";\n        }\n        fout_ << \"\\n *\/\\n\";\n      }\n      fout_ << \"\\n};\\n\";\n      for(  list::iterator it = namespaces_.begin();\n            it != namespaces_.end(); ++it)\n      {\n        fout_ << \"}\\n\";\n      }\n    };\n\n    ([ \\t]* . 'properties')\n      => {\n        propertyparams_ = PropParams();\n        access_ = AccessStruct();\n        class_part_ = Property;\n        fgoto properties;\n      };\n    ([ \\t]* . 'methods')\n      => {\n        methodparams_ = MethodParams();\n        access_ = AccessStruct();\n        class_part_ = Method;\n        fgoto methodsheader;\n      };\n    ([ \\t]* . 'events')\n      => {\n        propertyparams_ = PropParams();\n        propertyparams_.event = true;\n        access_ = AccessStruct();\n        class_part_ = Event;\n        fgoto events;\n      };\n  *|; #}}}2\n\n  # doxyblock expect {{{2\n  # after function declaration expect a documentation block or the function\n  # body\n  expect_doxyblock :=\n  (\n    doc_begin\n      @{\n        \/\/fout_ << \"\/*\";\n        p--;\n        fgoto doxyheader;\n      }\n  )\n $!{\n    fhold;\n    {\n      int i = 0;\n      for (i = 0; *(p-i) == ' ' || *(p-i) == '\\t'; ++i)\n        ;\n      std::string whitespaces(i, ' ');\n\/\/    if (string(p, 5) == \" if ~\")\n\/\/    {\n\/\/      debug_output(\"break;\", p);\n\/\/      fout_ << \"\/* start *\/\";\n\/\/    }\n\/\/    for (char * i = p; *i == ' ' || *i == '\\t'; --i)\n\/\/      fout_ << *i;\n\/\/     fout_ << \"\/* end *\/\"; \n#ifdef DEBUG\n    debug_output(\"stopping expect_doxyblock\", p);\n#endif\n    if(is_class_)\n    {\n      if(class_part_ == Header)\n      {\n        end_of_class_doc();\n        fgoto classbody;\n      } else if(class_part_ == Method || class_part_ == AtMethod)\n      {\n        string endstringtest;\n        endstringtest.assign(p, 100);\n        string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n        if(runMode_.mode == RunMode::ParseParams)\n          return 1;\n        if (endstringtest.substr(first_char, 3) == \"end\")\n        {\n          p += first_char+4;\n          print_function_synopsis();\n          end_function();\n          fgoto methods;\n        }\n        else\n        {\n          print_function_synopsis();\n          fout_ << whitespaces;\n          fgoto funcbody;\n        }\n      }\n      else if(class_part_ == Property || class_part_ == Event)\n      {\n        fgoto propertybody;\n      }\n      else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n      {\n        class_part_ = Method;\n        fgoto methods;\n      }\n      else{\n        cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n      }\n    }\n    else\n    {\n      if(runMode_.mode == RunMode::ParseParams)\n        return 1;\n      print_function_synopsis();\n      fout_ << whitespaces;\n      fgoto funcbody;\n    }\n    }\n  };\n  #}}}2\n\n  # function declaration {{{2\n  funcdef = (\n      (WSOC)* .\n      # return values (if found opt = true)\n      (lparams)? .\n      # matlab identifier (function name stored in cfuncname_)\n      ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n        IDENT\n          >st_tok\n          %{\n            cfuncname_.assign(tmp_p, p - tmp_p);\n            #ifdef DEBUG\n              cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n            #endif\n            \/\/ in ParseMethodParams mode, we only check for the method\n            \/\/ parameters of a specific method.\n            if(is_class_ && class_part_ == MethodDeclaration\n               && runMode_.mode == RunMode::ParseMethodParams)\n            {\n              if(runMode_.methodname == cfuncname_)\n              {\n                return 0;\n              }\n            }\n            if(runMode_.mode == RunMode::Normal\n               && is_class_ && class_part_ == AtMethod)\n            {\n              update_method_params(cfuncname_);\n            }\n            is_script_ = false;\n          }\n      )\n      . WSOC*\n      . (\n           '('\n           # parameter list\n           . ( paramlist\n               %{\n                 if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n                 { paramlist_.clear(); }\n               }\n             )\n           . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n             . garble_comment_line_wo_eol) | ( ';' ) )*\n           . EOL\n           @{\n             if(comment_found)\n             {\n                tmp_string.assign(tmp_p+1, p - tmp_p-1);\n                tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n             }\n             else\n             {\n                tmp_string = \"\";\n             }\n             comment_found = false;\n             if(is_class_ && class_part_ == MethodDeclaration )\n             {\n               class_part_ = Method;\n               #if DEBUG\n                 debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n               #endif\n               fgoto methods;\n             }\n             else\n             {\n               \/\/               fout_ << tmp_string << \"{\\n\";\n               \/\/ check for documentation block\n               fgoto expect_doxyblock;\n             }\n           }\n        # no parameter list && first function => ( script || method )\n        | (( [ \\t]\n              |\n             ('%' @{ tmp_p=p; comment_found=true; }\n              . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n            @{\n                 if(comment_found)\n                 {\n                   tmp_string.assign(tmp_p+1, p - tmp_p-1);\n                   tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n                 }\n                 else\n                 {\n                   tmp_string = \"\";\n                 }\n                 comment_found = false;\n                 #if DEBUG\n                   debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n                 #endif\n                 if(is_class_ && class_part_ == MethodDeclaration)\n                 {\n                    class_part_ = Method;\n                    fgoto methods;\n                 }\n                 else\n                 {\n                   fgoto expect_doxyblock;\n                 }\n             }\n        )\n      );\n\n  funct :=\n  (\n    (\n      comment_block @in_c_block\n      | [ \\t]*. EOL\n    )*\n    . ([\\t]*) . 'function' . funcdef\n  ) $eof( end_of_file ) ; #}}}2\n\n  # no function definition => a script {{{2\n  script := (default)\n    @{\n       string :: size_type found = filename_.rfind(\"\/\");\n       if(found == string :: npos)\n         found = -1;\n       string funcname = filename_.substr(found+1, filename_.size()-3-found);\n       cfuncname_.assign( funcname );\n  \/*     fout_ << \"noret::substitute \";\n       if(!is_first_function_)\n         fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n       fout_ << funcname << \"() {\\n\";*\/\n       is_script_ = true;\n       fhold;\n       fgoto expect_doxyblock;\n     }; #}}}2\n\n  # class definitions {{{2\n  classparams =\n      '(' . [^)]* . ')';\n\n  superclass =\n    ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n                      @{ if(*p == '.')\n                           fout_ << \"::\";\n                         else fout_ << *p; } );\n\n  superclasses = (\n      '<' @{ fout_ << \"\\n  :\"; } . WSOC* . superclass . WSOC*\n          . ('&' @{ fout_ << \",\\n   \"; } . WSOC* . superclass . WSOC*)* );\n\n  classdef := (\n      'classdef' . WSOC* . ('(' . WSOC*\n        . (( 'Sealed'i\n          @{\n            docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n           }\n          )\n\n\t\t  |( 'Hidden'i\n          @{\n            docuextra_.push_back(std::string(\"@note This class has the class property 'Hidden' and is invisible.\"));\n           }\n          )\n          |( 'Abstract'i\n\t\t  @{\n\t\t    docuextra_.push_back(std::string(\"@note This class has the class property 'Abstract' and needs to be inherited in order to be instantiable.\"));\n\t\t   }\n\t\t   )) . [^)]* . ')')? . WSOC* .\n      # matlab identifier (class name stored in classname_)\n      ( IDENT\n          >st_tok\n          %{\n            classname_.assign(tmp_p, p - tmp_p);\n            is_class_ = true;\n            fout_ << \"class \" << classname_;\n          }\n      )\n      . WSOC*\n      . classparams?\n      . WSOC*\n      . superclasses?\n      . [ \\t;]*\n      . ( '%'. garble_comment_line_wo_eol )?\n      EOL\n      @{\n        fout_ << \" {\\n\";\n        fgoto expect_doxyblock;\n      } );\n\n  # }}}2\n\n  # main loop {{{2\n  expect_function_script_or_class =\n  (\n    # either we find a function or classdef definition with a possibly\n    # preceding comment block or we have a script\n    ( any\n       @{\n          fhold;\n          tmp_p = p;\n        }\n      .\n    (\n      [ \\t]*. '%' . (any - '\\n')* . EOL\n      | [ \\t]*. EOL\n    )*\n    . [\\t]*\n    . ( 'function' @{\n                     p-=8;\n                     char *tp;\n                     for(tp=p; *tp == ' ' || *tp == '\\t'; --tp)\n                       ;\n                     funcindent_ = (int)(p - tp);\n#if DEBUG\n                     {\n                       ostringstream oss;\n                       oss << \"in expect_function_script_or_class funcindent: \" << funcindent_ << \" \" << (size_t) p << \" \" <<(size_t)tp;\n                       debug_output(oss.str(), p);\n                     }\n#endif\n                     if(is_class_ && class_part_ == Header)\n                       class_part_ = AtMethod;\n                     fgoto funct;\n                    }\n      | 'classdef' @{\n                     p-=8;\n                     fgoto classdef;\n                    }\n      ) )\n  $!{\n#ifdef DEBUG\n    debug_output(\"goto script\",p);\n#endif\n    p=tmp_p;\n    fgoto script;\n  }\n  );\n\n  main := expect_function_script_or_class*;\n  # }}}2\n\n}%%\n\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n  std::ios::sync_with_stdio(false);\n\n  fout_ << \"\\n\/* (Autoinserted by mtoc++)\\n * This source code has been filtered by the mtoc++ executable,\\n\";\n  fout_ << \" * which generates code that can be processed by the doxygen documentation tool.\\n *\\n\";\n  fout_ << \" * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.\\n\";\n  fout_ << \" * Except for the comments, the function bodies of your M-file functions are untouched.\\n\";\n  fout_ << \" * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce\\n\";\n  fout_ << \" * attached source files that are highly readable by humans.\\n *\\n\";\n  fout_ << \" * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to\\n\";\n  fout_ << \" * the correct locations in the source code browser.\\n\";\n  fout_ << \" * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.\\n *\/\\n\\n\";\n  \n  %% write init;\n\n  \/* Do the first read. *\/\n  bool done = false;\n  while ( !done )\n  {\n    char *p = buf + have;\n    char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n    string tmp_string, tmp_string2, tmp_string3;\n    bool docline = false;\n    bool latex_begin = true;\n    bool comment_found = false;\n    int space = BUFSIZE - have;\n\n    if ( space == 0 )\n    {\n      \/* We filled up the buffer trying to scan a token. *\/\n      cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n      exit(-1);\n    }\n\n    fin_.read( p, space );\n    int len = fin_.gcount();\n    char *pe = p + len;\n    char *rpe = pe;\n    char *eof = 0;\n\n    \/* If we see eof then append the EOF char. *\/\n    if ( fin_.eof() )\n    {\n      char eof_c = *pe;\n      *pe = '\\n';\n      pe++;\n      *pe = eof_c;\n      eof = pe;\n      rpe = pe;\n\n      done = true;\n    }\n    else\n    {\n      \/* Find the last newline by searching backwards. This is where\n       * we will stop processing on this iteration. *\/\n      while ( pe >= p )\n      {\n        if( *pe != '\\n')\n          pe--;\n        else\n        {\n          if(pe >= p+3\n              && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n            pe-=3;\n          else\n            break;\n        }\n      }\n    }\n\n    %% write exec;\n\n    \/* Check if we failed. *\/\n    if ( cs == MFileScanner_error )\n    {\n      \/* Machine failed before finding a token. *\/\n      cerr << \"MTOC++:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << \" (Most common issue: wrong MatLab-indentation)\" << endl;\n      debug_output(\"Grrrr!!!!\", p);\n      exit(-1);\n    }\n\n    \/* Now set up the prefix. *\/\n    if ( ts == 0 )\n    {\n      have = rpe - pe;\n      \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n      memmove( buf, pe, have );\n    }\n    else\n    {\n      have = rpe - ts;\n      \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n      memmove( buf, ts, have );\n    }\n\n    if ( ts != 0 )\n    {\n      te -= (ts-buf);\n      ts = buf;\n    }\n  }\n\n  return 0;\n}\n\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"}
{"commit":"36f912586c8a4c84804a11724c2eebbc74ce5486","subject":"Fixed code confusing GCC overflow checks in unpack.","message":"Fixed code confusing GCC overflow checks in unpack.\n","repos":"rubinius\/rapa","old_file":"actions\/rubinius\/unpack_actions.rl","new_file":"actions\/rubinius\/unpack_actions.rl","new_contents":"\/\/ vim: filetype=ragel\n\n%%{\n\n  machine unpack;\n\n  action start {\n    count = 1;\n    rest = false;\n    platform = false;\n  }\n\n  action start_digit {\n    count = fc - '0';\n  }\n\n  action count {\n    count = count * 10 + (fc - '0');\n  }\n\n  action rest {\n    count = 0;\n    rest = true;\n  }\n\n  action zero_count {\n    count = 0;\n  }\n\n  action platform {\n    platform = true;\n  }\n\n  action byte_width {\n    width = 1;\n  }\n\n  action short_width {\n    width = 2;\n  }\n\n  action int_width {\n    width = 4;\n  }\n\n  action long_width {\n    width = 8;\n  }\n\n  action platform_width {\n    if(platform) {\n#if RBX_SIZEOF_LONG == 4\n      width = 4;\n#else\n      width = 8;\n#endif\n    } else {\n      width = 4;\n    }\n  }\n\n  action set_stop {\n    if(!rest) {\n      stop = index + width * count;\n    }\n\n    if(rest || stop > bytes_size) {\n      stop = index + ((bytes_size - index) \/ width) * width;\n    }\n  }\n\n  action extra {\n    for(; count > 0; count--) {\n      array->append(state, Qnil);\n    }\n  }\n\n  # Integers\n\n  action C {\n    unpack_integer(ubyte);\n  }\n\n  action c {\n    unpack_integer(sbyte);\n  }\n\n  action S {\n    unpack_integer(u2bytes);\n  }\n\n  action s {\n    unpack_integer(s2bytes);\n  }\n\n  action I {\n    unpack_integer(u4bytes);\n  }\n\n  action i {\n    unpack_integer(s4bytes);\n  }\n\n  action L {\n    if(platform) {\n#if RBX_SIZEOF_LONG == 4\n      unpack_integer(u4bytes);\n#else\n      unpack_integer(u8bytes);\n#endif\n    } else {\n      unpack_integer(u4bytes);\n    }\n  }\n\n  action l {\n    if(platform) {\n#if RBX_SIZEOF_LONG == 4\n      unpack_integer(s4bytes);\n#else\n      unpack_integer(s8bytes);\n#endif\n    } else {\n      unpack_integer(s4bytes);\n    }\n  }\n\n  action N {\n    unpack_integer(u4bytes_be);\n  }\n\n  action n {\n    unpack_integer(u2bytes_be);\n  }\n\n  action V {\n    unpack_integer(u4bytes_le);\n  }\n\n  action v {\n    unpack_integer(u2bytes_le);\n  }\n\n  action Q {\n    unpack_integer(u8bytes);\n  }\n\n  action q {\n    unpack_integer(s8bytes);\n  }\n\n  # Floats\n\n  action D {\n    unpack_double;\n  }\n\n  action E {\n    unpack_double_le;\n  }\n\n  action e {\n    unpack_float_le;\n  }\n\n  action F {\n    unpack_float;\n  }\n\n  action G {\n    unpack_double_be;\n  }\n\n  action g {\n    unpack_float_be;\n  }\n\n  # Moves\n\n  action X {\n    if(rest) count = bytes_size - index;\n    index -= count;\n  }\n\n  action x {\n    if(rest) {\n      index = bytes_size;\n    } else {\n      index += count;\n    }\n  }\n\n  action at {\n    if(!rest) {\n      index = count;\n    }\n  }\n\n  action check_bounds {\n    if(index < 0 || index > bytes_size) {\n      std::ostringstream msg;\n      msg << *p << \" outside of string\";\n      Exception::argument_error(state, msg.str().c_str());\n    }\n  }\n\n  # String \/ Encoding helpers\n\n  action bytes {\n    bytes = (const char*)self->byte_address() + index;\n  }\n\n  action bytes_end {\n    bytes_end = (const char*)self->byte_address() + bytes_size;\n  }\n\n  action string_width {\n    width = 1;\n  }\n\n  action bit_width {\n    width = 8;\n  }\n\n  action hex_width {\n    width = 2;\n  }\n\n  action remainder {\n    remainder = bytes_size - index;\n  }\n\n  action rest_count {\n    if(rest) {\n      count = remainder;\n    } else if(count > remainder) {\n      count = remainder;\n    }\n  }\n\n  action string_size {\n    if(rest || count > remainder * width) {\n      count = remainder * width;\n    }\n  }\n\n  # Strings\n\n  action A {\n    String* string;\n\n    if(count > 0) {\n      native_int i;\n      for(i = count; i > 0; i--) {\n        uint8_t c = bytes[i-1];\n        if(c != ' ' && c != '\\0')\n          break;\n      }\n      string = String::create(state, bytes, i);\n    } else {\n      string = String::create(state, \"\");\n    }\n\n    array->append(state, string);\n    unpack::increment(index, count, bytes_size);\n  }\n\n  action a {\n    array->append(state, String::create(state, bytes, count));\n\n    unpack::increment(index, count, bytes_size);\n  }\n\n  action Z {\n    native_int c;\n    for(c = 0; c < count; c++) {\n      if(bytes[c] == '\\0') break;\n    }\n    array->append(state, String::create(state, bytes, c));\n\n    if(rest) {\n      unpack::increment(index, c < count ? c + 1 : count, bytes_size);\n    } else {\n      unpack::increment(index, count, bytes_size);\n    }\n  }\n\n  # Encodings\n\n  action index_increment {\n    unpack::increment(index,\n                      bytes - ((const char*)self->byte_address() + index),\n                      bytes_size);\n  }\n\n  action B {\n    array->append(state, unpack::bit_high(state, bytes, count));\n  }\n\n  action b {\n    array->append(state, unpack::bit_low(state, bytes, count));\n  }\n\n  action H {\n    array->append(state, unpack::hex_high(state, bytes, count));\n  }\n\n  action h {\n    array->append(state, unpack::hex_low(state, bytes, count));\n  }\n\n  action M {\n    array->append(state, unpack::quotable_printable(state, bytes, bytes_end, remainder));\n  }\n\n  action m {\n    array->append(state, unpack::base64_decode(state, bytes, bytes_end, remainder));\n  }\n\n  action U {\n    unpack::utf8_decode(state, array, bytes, bytes_end, count, index);\n  }\n\n  action u {\n    array->append(state, unpack::uu_decode(state, bytes, bytes_end, remainder));\n  }\n\n  action w {\n    unpack::ber_decode(state, array, bytes, bytes_end, count, index);\n    index = bytes - (const char*)self->byte_address();\n  }\n\n  action non_native_error {\n    std::ostringstream msg;\n    msg << \"'\" << *p << \"' allowed only after types sSiIlL\";\n    Exception::argument_error(state, msg.str().c_str());\n  }\n\n  action done {\n    return array;\n  }\n}%%\n","old_contents":"\/\/ vim: filetype=ragel\n\n%%{\n\n  machine unpack;\n\n  action start {\n    count = 1;\n    rest = false;\n    platform = false;\n  }\n\n  action start_digit {\n    count = fc - '0';\n  }\n\n  action count {\n    count = count * 10 + (fc - '0');\n  }\n\n  action rest {\n    count = 0;\n    rest = true;\n  }\n\n  action zero_count {\n    count = 0;\n  }\n\n  action platform {\n    platform = true;\n  }\n\n  action byte_width {\n    width = 1;\n  }\n\n  action short_width {\n    width = 2;\n  }\n\n  action int_width {\n    width = 4;\n  }\n\n  action long_width {\n    width = 8;\n  }\n\n  action platform_width {\n    if(platform) {\n#if RBX_SIZEOF_LONG == 4\n      width = 4;\n#else\n      width = 8;\n#endif\n    } else {\n      width = 4;\n    }\n  }\n\n  action set_stop {\n    stop = rest ? bytes_size + 1 : index + width * count;\n    if(stop > bytes_size) {\n      stop = index + ((bytes_size - index) \/ width) * width;\n    }\n  }\n\n  action extra {\n    for(; count > 0; count--) {\n      array->append(state, Qnil);\n    }\n  }\n\n  # Integers\n\n  action C {\n    unpack_integer(ubyte);\n  }\n\n  action c {\n    unpack_integer(sbyte);\n  }\n\n  action S {\n    unpack_integer(u2bytes);\n  }\n\n  action s {\n    unpack_integer(s2bytes);\n  }\n\n  action I {\n    unpack_integer(u4bytes);\n  }\n\n  action i {\n    unpack_integer(s4bytes);\n  }\n\n  action L {\n    if(platform) {\n#if RBX_SIZEOF_LONG == 4\n      unpack_integer(u4bytes);\n#else\n      unpack_integer(u8bytes);\n#endif\n    } else {\n      unpack_integer(u4bytes);\n    }\n  }\n\n  action l {\n    if(platform) {\n#if RBX_SIZEOF_LONG == 4\n      unpack_integer(s4bytes);\n#else\n      unpack_integer(s8bytes);\n#endif\n    } else {\n      unpack_integer(s4bytes);\n    }\n  }\n\n  action N {\n    unpack_integer(u4bytes_be);\n  }\n\n  action n {\n    unpack_integer(u2bytes_be);\n  }\n\n  action V {\n    unpack_integer(u4bytes_le);\n  }\n\n  action v {\n    unpack_integer(u2bytes_le);\n  }\n\n  action Q {\n    unpack_integer(u8bytes);\n  }\n\n  action q {\n    unpack_integer(s8bytes);\n  }\n\n  # Floats\n\n  action D {\n    unpack_double;\n  }\n\n  action E {\n    unpack_double_le;\n  }\n\n  action e {\n    unpack_float_le;\n  }\n\n  action F {\n    unpack_float;\n  }\n\n  action G {\n    unpack_double_be;\n  }\n\n  action g {\n    unpack_float_be;\n  }\n\n  # Moves\n\n  action X {\n    if(rest) count = bytes_size - index;\n    index -= count;\n  }\n\n  action x {\n    if(rest) {\n      index = bytes_size;\n    } else {\n      index += count;\n    }\n  }\n\n  action at {\n    if(!rest) {\n      index = count;\n    }\n  }\n\n  action check_bounds {\n    if(index < 0 || index > bytes_size) {\n      std::ostringstream msg;\n      msg << *p << \" outside of string\";\n      Exception::argument_error(state, msg.str().c_str());\n    }\n  }\n\n  # String \/ Encoding helpers\n\n  action bytes {\n    bytes = (const char*)self->byte_address() + index;\n  }\n\n  action bytes_end {\n    bytes_end = (const char*)self->byte_address() + bytes_size;\n  }\n\n  action string_width {\n    width = 1;\n  }\n\n  action bit_width {\n    width = 8;\n  }\n\n  action hex_width {\n    width = 2;\n  }\n\n  action remainder {\n    remainder = bytes_size - index;\n  }\n\n  action rest_count {\n    if(rest) {\n      count = remainder;\n    } else if(count > remainder) {\n      count = remainder;\n    }\n  }\n\n  action string_size {\n    if(rest || count > remainder * width) {\n      count = remainder * width;\n    }\n  }\n\n  # Strings\n\n  action A {\n    String* string;\n\n    if(count > 0) {\n      native_int i;\n      for(i = count; i > 0; i--) {\n        uint8_t c = bytes[i-1];\n        if(c != ' ' && c != '\\0')\n          break;\n      }\n      string = String::create(state, bytes, i);\n    } else {\n      string = String::create(state, \"\");\n    }\n\n    array->append(state, string);\n    unpack::increment(index, count, bytes_size);\n  }\n\n  action a {\n    array->append(state, String::create(state, bytes, count));\n\n    unpack::increment(index, count, bytes_size);\n  }\n\n  action Z {\n    native_int c;\n    for(c = 0; c < count; c++) {\n      if(bytes[c] == '\\0') break;\n    }\n    array->append(state, String::create(state, bytes, c));\n\n    if(rest) {\n      unpack::increment(index, c < count ? c + 1 : count, bytes_size);\n    } else {\n      unpack::increment(index, count, bytes_size);\n    }\n  }\n\n  # Encodings\n\n  action index_increment {\n    unpack::increment(index,\n                      bytes - ((const char*)self->byte_address() + index),\n                      bytes_size);\n  }\n\n  action B {\n    array->append(state, unpack::bit_high(state, bytes, count));\n  }\n\n  action b {\n    array->append(state, unpack::bit_low(state, bytes, count));\n  }\n\n  action H {\n    array->append(state, unpack::hex_high(state, bytes, count));\n  }\n\n  action h {\n    array->append(state, unpack::hex_low(state, bytes, count));\n  }\n\n  action M {\n    array->append(state, unpack::quotable_printable(state, bytes, bytes_end, remainder));\n  }\n\n  action m {\n    array->append(state, unpack::base64_decode(state, bytes, bytes_end, remainder));\n  }\n\n  action U {\n    unpack::utf8_decode(state, array, bytes, bytes_end, count, index);\n  }\n\n  action u {\n    array->append(state, unpack::uu_decode(state, bytes, bytes_end, remainder));\n  }\n\n  action w {\n    unpack::ber_decode(state, array, bytes, bytes_end, count, index);\n    index = bytes - (const char*)self->byte_address();\n  }\n\n  action non_native_error {\n    std::ostringstream msg;\n    msg << \"'\" << *p << \"' allowed only after types sSiIlL\";\n    Exception::argument_error(state, msg.str().c_str());\n  }\n\n  action done {\n    return array;\n  }\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"}
{"commit":"f1fcdfbacb9c3c51aa01e946cbaba59002a7fefb","subject":"Cleaned up the Ragel bits of the lexer.","message":"Cleaned up the Ragel bits of the lexer.\n\nThis removes some of the complexity that existed before (e.g. too many state\nmachines) and fixes a bunch of problems with nested data.\n","repos":"ttasanen\/oga,YorickPeterse\/oga,ttasanen\/oga,jeffreybaird\/oga,altmetric\/oga,dfockler\/oga,YorickPeterse\/oga,altmetric\/oga,jeffreybaird\/oga,dfockler\/oga,jeffreybaird\/oga,altmetric\/oga,ttasanen\/oga,altmetric\/oga,ttasanen\/oga,altmetric\/oga,YorickPeterse\/oga,dfockler\/oga,YorickPeterse\/oga,dfockler\/oga,ttasanen\/oga,jeffreybaird\/oga,dfockler\/oga,jeffreybaird\/oga,YorickPeterse\/oga","old_file":"lib\/oga\/lexer.rl","new_file":"lib\/oga\/lexer.rl","new_contents":"%%machine lexer; # %\n\nmodule Oga\n  ##\n  #\n  class Lexer\n    %% write data; # %\n\n    attr_reader :html\n\n    HTML_VOID_ELEMENTS = [\n      'area',\n      'base',\n      'br',\n      'col',\n      'command',\n      'embed',\n      'hr',\n      'img',\n      'input',\n      'keygen',\n      'link',\n      'meta',\n      'param',\n      'source',\n      'track',\n      'wbr'\n    ]\n\n    # Lazy way of forwarding instance method calls used internally by Ragel to\n    # their corresponding class methods.\n    private_methods.grep(\/^_lexer_\/).each do |name|\n      define_method(name) do\n        return self.class.send(name)\n      end\n\n      private(name)\n    end\n\n    def initialize(options = {})\n      options.each do |key, value|\n        instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n      end\n\n      reset\n    end\n\n    def reset\n      @line     = 1\n      @column   = 1\n      @data     = nil\n      @ts       = nil\n      @te       = nil\n      @tokens   = []\n      @stack    = []\n      @top      = 0\n      @elements = []\n\n      @string_buffer = ''\n      @text_buffer   = ''\n    end\n\n    def lex(data)\n      @data       = data\n      lexer_start = self.class.lexer_start\n      eof         = data.length\n\n      %% write init;\n      %% write exec;\n\n      tokens = @tokens\n\n      reset\n\n      return tokens\n    end\n\n    def html?\n      return !!html\n    end\n\n    private\n\n    def advance_line(amount = 1)\n      @line  += amount\n      @column = 1\n    end\n\n    def advance_column(length = 1)\n      @column += length\n    end\n\n    def t(type, start = @ts, stop = @te)\n      value = text(start, stop)\n\n      add_token(type, value)\n    end\n\n    def text(start = @ts, stop = @te)\n      return @data[start...stop]\n    end\n\n    def add_token(type, value)\n      token = [type, value, @line, @column]\n\n      advance_column(value.length) if value\n\n      @tokens << token\n    end\n\n    def emit_text_buffer\n      return if @text_buffer.empty?\n\n      add_token(:T_TEXT, @text_buffer)\n\n      lines = @text_buffer.count(\"\\n\")\n\n      advance_line(lines) if lines > 0\n\n      @text_buffer = ''\n    end\n\n    def buffer_text_until_eof(eof)\n      @text_buffer << text\n\n      emit_text_buffer if @te == eof\n    end\n\n    def emit_string_buffer\n      add_token(:T_STRING, @string_buffer)\n      advance_column\n\n      @string_buffer = ''\n    end\n\n    def current_element\n      return @elements.last\n    end\n\n    %%{\n      # Use instance variables for `ts` and friends.\n      access @;\n\n      newline    = '\\n' | '\\r\\n';\n      whitespace = [ \\t];\n\n      # Strings\n      #\n      # Strings in HTML can either be single or double quoted. If a string\n      # starts with one of these quotes it must be closed with the same type of\n      # quote.\n      dquote = '\"';\n      squote = \"'\";\n\n      action buffer_text {\n        @text_buffer << text\n      }\n\n      action buffer_string {\n        @string_buffer << text\n      }\n\n      action start_string_dquote {\n        fcall string_dquote;\n      }\n\n      action start_string_squote {\n        fcall string_squote;\n      }\n\n      # Machine for processing double quoted strings.\n      string_dquote := |*\n        ^dquote => buffer_string;\n        dquote  => {\n          emit_string_buffer\n          advance_column\n          fret;\n        };\n      *|;\n\n      # Machine for processing single quoted strings.\n      string_squote := |*\n        ^squote => buffer_string;\n        squote  => {\n          emit_string_buffer\n          advance_column\n          fret;\n        };\n      *|;\n\n      # DOCTYPES\n      #\n      # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n      #\n      # These rules support the 3 flavours of doctypes:\n      #\n      # 1. Normal doctypes, as introduced in the HTML5 specification.\n      # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n      # 3. Legacy doctypes\n      #\n      doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n        # Lex the public\/system IDs as regular strings.\n        dquote => start_string_dquote;\n        squote => start_string_squote;\n\n        # Whitespace inside doctypes is ignored since there's no point in\n        # including it.\n        whitespace => { advance_column };\n\n        '>' => {\n          t(:T_DOCTYPE_END)\n          fret;\n        };\n      *|;\n\n      # CDATA\n      #\n      # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n      #\n      # CDATA tags are broken up into 3 parts: the start, the content and the\n      # end tag.\n      #\n      # In HTML CDATA tags have no meaning\/are not supported. Oga does\n      # support them but treats their contents as plain text.\n      #\n      cdata_start = '';\n\n      action start_cdata {\n        emit_text_buffer\n        t(:T_CDATA_START)\n        fcall cdata;\n      }\n\n      # Machine that for processing the contents of CDATA tags. Everything\n      # inside a CDATA tag is treated as plain text.\n      cdata := |*\n        cdata_end => {\n          emit_text_buffer\n          t(:T_CDATA_END)\n          fret;\n        };\n\n        any => buffer_text;\n      *|;\n\n      # Comments\n      #\n      # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n      #\n      # Comments are lexed into 3 parts: the start tag, the content and the end\n      # tag.\n      #\n      # Unlike the W3 specification these rules *do* allow character sequences\n      # such as `--` and `->`. Putting extra checks in for these sequences\n      # would actually make the rules\/actions more complex.\n      #\n      comment_start = '';\n\n      action start_comment {\n        emit_text_buffer\n        t(:T_COMMENT_START)\n        fcall comment;\n      }\n\n      # Machine used for processing the contents of a comment. Everything\n      # inside a comment is treated as plain text (similar to CDATA tags).\n      comment := |*\n        comment_end => {\n          emit_text_buffer\n          t(:T_COMMENT_END)\n          fret;\n        };\n\n        any => buffer_text;\n      *|;\n\n      # Elements\n      #\n      # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n      #\n\n      # Action that creates the tokens for the opening tag, name and namespace\n      # (if any). Remaining work is delegated to a dedicated machine.\n      action start_element {\n        emit_text_buffer\n        add_token(:T_ELEM_OPEN, nil)\n        advance_column\n\n        # Add the element name. If the name includes a namespace we'll break\n        # the name up into two separate tokens.\n        name = text(@ts + 1)\n\n        if name.include?(':')\n          ns, name = name.split(':')\n\n          add_token(:T_ELEM_NS, ns)\n\n          # Advance the column for the colon (:) that separates the namespace\n          # and element name.\n          advance_column\n        end\n\n        @elements << name\n\n        add_token(:T_ELEM_NAME, name)\n\n        fcall element_head;\n      }\n\n      element_name  = [a-zA-Z0-9\\-_:]+;\n      element_start = '<' element_name;\n\n      # Machine used for processing the characters inside a element head. An\n      # element head is everything between ``.\n      #\n      # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n (whitespace | '=') => { advance_column };\n\n # Attribute names.\n element_name => { t(:T_ATTR) };\n\n # Attribute values.\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n element_start => start_element;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_CLOSE, nil)\n @elements.pop\n end\n\n advance_column\n };\n\n # Regular closing tags.\n '<\/' element_name '>' => {\n emit_text_buffer\n add_token(:T_ELEM_CLOSE, nil)\n\n advance_column(@te - @ts)\n\n @elements.pop\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n advance_column\n add_token(:T_ELEM_CLOSE, nil)\n\n @elements.pop\n };\n\n # Note that this rule should be declared at the very bottom as it will\n # otherwise take precedence over the other rules.\n any => { buffer_text_until_eof(eof) };\n *|;\n }%%\n end # Lexer\nend # Oga\n","old_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n attr_reader :html\n\n HTML_VOID_ELEMENTS = [\n 'area',\n 'base',\n 'br',\n 'col',\n 'command',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n ]\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize(options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n end\n\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n @elements = []\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n def html?\n return !!html\n end\n\n private\n\n def advance_line(amount = 1)\n @line += amount\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length) if value\n\n @tokens << token\n end\n\n def emit_text_buffer\n return if @text_buffer.empty?\n\n add_token(:T_TEXT, @text_buffer)\n\n lines = @text_buffer.count(\"\\n\")\n\n advance_line(lines) if lines > 0\n\n @text_buffer = ''\n end\n\n def buffer_text_until_eof(eof)\n @text_buffer << text\n\n emit_text_buffer if @te == eof\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n def current_element\n return @elements.last\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n fcall string_dquote;\n }\n\n action string_squote {\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n t(:T_CDATA_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the end\n # tag.\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences\n # would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n comment := |*\n comment_end => {\n emit_text_buffer\n t(:T_COMMENT_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and namespace\n # (if any). Remaining work is delegated to a dedicated machine.\n action open_element {\n emit_text_buffer\n add_token(:T_ELEM_OPEN, nil)\n advance_column\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(@ts + 1)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n\n # Advance the column for the colon (:) that separates the namespace\n # and element name.\n advance_column\n end\n\n @elements << name\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element;\n }\n\n element_name = [a-zA-Z0-9\\-_:]+;\n element_start = '<' element_name;\n\n element_text := |*\n ^'<' => {\n buffer_text_until_eof(eof)\n };\n\n '<' => {\n emit_text_buffer\n fhold;\n fret;\n };\n *|;\n\n element_closing_tag := |*\n whitespace => { advance_column };\n\n element_name => {\n emit_text_buffer\n add_token(:T_ELEM_CLOSE, nil)\n\n # Advance the column for the <\/\n advance_column(2)\n\n # Advance the column for the closing name.\n advance_column(text.length)\n\n fret;\n };\n\n '>' => { fret; };\n *|;\n\n element := |*\n whitespace => { advance_column };\n\n element_start => open_element;\n\n # Consume the text inside the element.\n '>' => {\n # If HTML lexing is enabled and we're in a void element we'll bail\n # out right away.\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_CLOSE, nil)\n @elements.pop\n end\n\n advance_column\n\n fcall element_text;\n };\n\n # Attributes and their values.\n element_name %{ t(:T_ATTR, @ts, p) }\n\n # The value of the attribute. Attribute values are not required. e.g.\n # in

<\/p> data-foo would be a boolean attribute.\n (\n '=' >{ advance_column }\n\n # The value of the attribute, wrapped in either single or double\n # quotes.\n (dquote @string_dquote | squote @string_squote)\n )*;\n\n # Non self-closing elements.\n '<\/' => {\n fcall element_closing_tag;\n\n @elements.pop\n\n fret;\n };\n\n # self-closing \/ void elements.\n '\/>' => {\n advance_column\n add_token(:T_ELEM_CLOSE, nil)\n\n @elements.pop\n\n fret;\n };\n *|;\n\n main := |*\n doctype_start => {\n emit_text_buffer\n t(:T_DOCTYPE_START)\n fcall doctype;\n };\n\n cdata_start => {\n emit_text_buffer\n t(:T_CDATA_START)\n fcall cdata;\n };\n\n comment_start => {\n emit_text_buffer\n t(:T_COMMENT_START)\n fcall comment;\n };\n\n element_start => open_element;\n\n any => {\n buffer_text_until_eof(eof)\n };\n *|;\n }%%\n end # Lexer\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"764e07d4818a24c9970aceaf26514f8996792c6c","subject":"SSA: \\r shouldn't reset positioning","message":"SSA: \\r shouldn't reset positioning\n","repos":"JanX2\/Perian,JanX2\/Perian,JanX2\/Perian,MaddTheSane\/perian,MaddTheSane\/perian,JanX2\/Perian,MaddTheSane\/perian,MaddTheSane\/perian,MaddTheSane\/perian,JanX2\/Perian,MaddTheSane\/perian","old_file":"SSATagParsing.m.rl","new_file":"SSATagParsing.m.rl","new_contents":"\/*\n * SSARenderCodec.m\n * Copyright (c) 2007 Perian Project\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nvoid SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\n\/\/not worth it\n\/*\nstatic void PruneIdenticalStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\t\n\tif (re->multipart_drawing || re->style_count <= 1) return;\n\n\tsize_t style_count_new = 1, remaining = re->style_count-1;\n\tint i=1;\n\t\n\t\n\tstyles_new[0] = re->styles[0];\n\t\n\twhile (remaining) {\n\t\tATSUStyleComparison asc;\n\t\tATSUCompareStyles(styles_new[style_count_new-1]->astyle,re->styles[i]->astyle,&asc);\n\t\t\n\t\tif (asc == kATSUStyleEquals) {\n styles_new[style_count_new-1]->range.length += re->styles[i]->range.length;\n\t\t\t[re->styles[i] release];\n re->styles[i] = nil;\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t\t\n\t\ti++;\n\t\tremaining--;\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n*\/\n\nstatic void UpdateAlignment(int inum, int cur_posx, int *valign, int *halign, ATSUTextLayout cur_layout)\n{\n\tint cur_halign, cur_valign;\n\t\n\tswitch (inum) \n\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\n\tswitch (inum)\n\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\n\t*halign = cur_halign;\n\t*valign = cur_valign;\n\tFract alignment;\n\t\n\tif (cur_posx != -1) {\n\t\tswitch(cur_halign) {\n\t\t\tcase S_LeftAlign:\n\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\tbreak;\n\t\t\tcase S_CenterAlign: default:\n\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\tbreak;\n\t\t\tcase S_RightAlign: \n\t\t\t\talignment = FloatToFract(1.);\n\t\t}\n\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t} \n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i=0, j, pcount = 1; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\n\tfor (; i < pcount; i ++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:(ssa->collisiontype == NormalCollisions) ? i : (pcount - i - 1)]\n\t\t\t\t\t\t componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipart_drawing=NO;\n\t\tre->is_shape=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\tif (cur_range.length) {[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->angle = cur_frz;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;}\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin = p, *strbegin = p, *skipbegin = p, *intbegin = p, *pb = p, *posbegin=p, *strparambegin=p;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow, cur_scalex = re->style->scalex, cur_scaley = re->style->scaley, cur_frz=re->style->angle;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx=-1, cur_posy=-1;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\tCGAffineTransform matrix;\n\t\t\t\n\t\t\tunsigned long inum=0;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag=0, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {cur_frz = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tnum *= (72.\/96.); \/\/ scale from Windows 96dpi\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction ftrack {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUTrackingTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscalex {\n\t\t\t\t\tcur_scalex = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscaley {\n\t\t\t\t\tcur_scaley = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction strp_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(inum, cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\n\t\t\t\taction ssa_alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(SSA2ASSAlignment(inum), cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondarycolor {\n\t\t\t\t\tcur_color.secondary = ParseColorTag(inum,cur_color.secondary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primaryalpha {\n\t\t\t\t\tcur_color.primary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondaryalpha {\n\t\t\t\t\tcur_color.secondary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinealpha {\n\t\t\t\t\tcur_color.outline.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowalpha {\n\t\t\t\t\tcur_color.shadow.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tNSString *append = @\"\\n\";\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\tif (*(p - 1) == 'h') append = @\" \";\n \n\t\t\t\t\t[output appendString:append];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tunsigned taglen = p - skipbegin;\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:taglen];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n \n if (cur_range.length) {\n [re increasestyles];\n re->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n re->styles[re->style_count-1]->outline = cur_outline;\n re->styles[re->style_count-1]->shadow = cur_shadow;\n re->styles[re->style_count-1]->angle = cur_frz;\n re->styles[re->style_count-1]->astyle = cur_style;\n re->styles[re->style_count-1]->range = cur_range;\n re->styles[re->style_count-1]->outlineblur = cur_be;\n re->styles[re->style_count-1]->color = cur_color;\n ATSUCreateAndCopyStyle(cur_style,&cur_style);\n }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\t\/\/ XXX exit_tag ideally should run one char later, so we just pretend it does\n\t\t\t\t\tp++;\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n \n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[[SSARenderEntity alloc] init] autorelease];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipart_drawing = NO;\n\t\t\t\t\t\tnre->is_shape = re->is_shape;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction styleset {\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t\tssastyleline *the_style = re->style;\n\t\t\t\t\tNSString *searchsn = [NSString stringWithCharacters:strparambegin length:p-strparambegin];\n\t\t\t\t\t\n\t\t\t\t\tif ([searchsn length] > 0) {\n\t\t\t\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\t\t\t\tif ([searchsn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\t\t\t\tthe_style = &ssa->styles[j]; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tATSUCopyAttributes(the_style->atsustyle,cur_style);\n\t\t\t\t\tcur_color = the_style->color;\n\t\t\t\t\tcur_outline = the_style->outline;\n\t\t\t\t\tcur_shadow = the_style->shadow;\n\t\t\t\t\tcur_frz = the_style->angle;\n\t\t\t\t\tcur_scalex = cur_scaley = 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction skip_t_tag {\n\t\t\t\t\twhile (p != pe && *p != ')' && *p != '}') p++;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction draw_mode {\n\t\t\t\t\tre->is_shape = inum != 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (fl == '0' || fl == '1') flag = fl - '0';})? > {flag = 0;};\n\t\t\t\tnum_ = \"-\"? digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = \"-\"? (digit+) > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|\"fsp\" num %ftrack\n\t\t\t\t\t\t\t\t|\"fscx\" num %fscalex\n\t\t\t\t\t\t\t\t|\"fscy\" num %fscaley\n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > strp_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"a\" intnum %ssa_alignment\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"1c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"2c\" color %secondarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t|\"1a\" color %primaryalpha\n\t\t\t\t\t\t\t\t|\"2a\" color %secondaryalpha\n\t\t\t\t\t\t\t\t|\"3a\" color %outlinealpha\n\t\t\t\t\t\t\t\t|\"4a\" color %shadowalpha\n\t\t\t\t\t\t\t\t|(\"r\" [^\\\\}]* > strp_begin %styleset)\n\t\t\t\t\t\t\t\t|(\"fe\"|\"k\"|\"kf\"|\"K\"|\"ko\"|\"q\"|\"fr\"|\"fad\"|\"move\"|\"clip\"|\"o\"|\"frx\"|\"fry\") [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"p\" num %draw_mode\n\t\t\t\t\t\t\t\t#|\"t\" [^)}]* # enabling this crashes ragel\n\t\t\t\t\t\t\t\t|\"t(\" % skip_t_tag\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = (\"\\\\\" :> cmd_specific)+;\n\t\t\t\t\n\t\t\t\tplaintext = [^}]*;\n\n\t\t\t\ttag = \"{\" (cmd | plaintext) % exit_tag \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nnh];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | (tag > enter_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (pb[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\t\t\tif (!cur_range.length) ATSUDisposeStyle(cur_style);\n \/\/PruneIdenticalStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\treturn rentities;\n}\n","old_contents":"\/*\n * SSARenderCodec.m\n * Copyright (c) 2007 Perian Project\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nvoid SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nvoid SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, const ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\n\/\/not worth it\n\/*\nstatic void PruneIdenticalStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\t\n\tif (re->multipart_drawing || re->style_count <= 1) return;\n\n\tsize_t style_count_new = 1, remaining = re->style_count-1;\n\tint i=1;\n\t\n\t\n\tstyles_new[0] = re->styles[0];\n\t\n\twhile (remaining) {\n\t\tATSUStyleComparison asc;\n\t\tATSUCompareStyles(styles_new[style_count_new-1]->astyle,re->styles[i]->astyle,&asc);\n\t\t\n\t\tif (asc == kATSUStyleEquals) {\n styles_new[style_count_new-1]->range.length += re->styles[i]->range.length;\n\t\t\t[re->styles[i] release];\n re->styles[i] = nil;\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t\t\n\t\ti++;\n\t\tremaining--;\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n*\/\n\nstatic void UpdateAlignment(int inum, int cur_posx, int *valign, int *halign, ATSUTextLayout cur_layout)\n{\n\tint cur_halign, cur_valign;\n\t\n\tswitch (inum) \n\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\n\tswitch (inum)\n\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\n\t*halign = cur_halign;\n\t*valign = cur_valign;\n\tFract alignment;\n\t\n\tif (cur_posx != -1) {\n\t\tswitch(cur_halign) {\n\t\t\tcase S_LeftAlign:\n\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\tbreak;\n\t\t\tcase S_CenterAlign: default:\n\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\tbreak;\n\t\t\tcase S_RightAlign: \n\t\t\t\talignment = FloatToFract(1.);\n\t\t}\n\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t} \n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i=0, j, pcount = 1; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\n\tfor (; i < pcount; i ++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:(ssa->collisiontype == NormalCollisions) ? i : (pcount - i - 1)]\n\t\t\t\t\t\t componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipart_drawing=NO;\n\t\tre->is_shape=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\tif (cur_range.length) {[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->angle = cur_frz;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;}\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin = p, *strbegin = p, *skipbegin = p, *intbegin = p, *pb = p, *posbegin=p, *strparambegin=p;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow, cur_scalex = re->style->scalex, cur_scaley = re->style->scaley, cur_frz=re->style->angle;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx=-1, cur_posy=-1;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\tCGAffineTransform matrix;\n\t\t\t\n\t\t\tunsigned long inum=0;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag=0, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {cur_frz = num; re->multipart_drawing = YES;}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tnum *= (72.\/96.); \/\/ scale from Windows 96dpi\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction ftrack {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUTrackingTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscalex {\n\t\t\t\t\tcur_scalex = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fscaley {\n\t\t\t\t\tcur_scaley = num;\n\t\t\t\t\tmatrix = CGAffineTransformMakeScale(cur_scalex\/100.,cur_scaley\/100.);\t\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontMatrixTag, sizeof(matrix), &matrix);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction strp_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(inum, cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\n\t\t\t\taction ssa_alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tUpdateAlignment(SSA2ASSAlignment(inum), cur_posx, &cur_valign, &cur_halign, cur_layout);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondarycolor {\n\t\t\t\t\tcur_color.secondary = ParseColorTag(inum,cur_color.secondary.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primaryalpha {\n\t\t\t\t\tcur_color.primary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction secondaryalpha {\n\t\t\t\t\tcur_color.secondary.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinealpha {\n\t\t\t\t\tcur_color.outline.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowalpha {\n\t\t\t\t\tcur_color.shadow.alpha = (255 - inum) \/ 255.f;\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tNSString *append = @\"\\n\";\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\tif (*(p - 1) == 'h') append = @\" \";\n \n\t\t\t\t\t[output appendString:append];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tunsigned taglen = p - skipbegin;\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:taglen];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n \n if (cur_range.length) {\n [re increasestyles];\n re->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n re->styles[re->style_count-1]->outline = cur_outline;\n re->styles[re->style_count-1]->shadow = cur_shadow;\n re->styles[re->style_count-1]->angle = cur_frz;\n re->styles[re->style_count-1]->astyle = cur_style;\n re->styles[re->style_count-1]->range = cur_range;\n re->styles[re->style_count-1]->outlineblur = cur_be;\n re->styles[re->style_count-1]->color = cur_color;\n ATSUCreateAndCopyStyle(cur_style,&cur_style);\n }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\t\/\/ XXX exit_tag ideally should run one char later, so we just pretend it does\n\t\t\t\t\tp++;\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n \n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[[SSARenderEntity alloc] init] autorelease];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipart_drawing = NO;\n\t\t\t\t\t\tnre->is_shape = re->is_shape;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction styleset {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tre->multipart_drawing = YES;\n\t\t\t\t\tssastyleline *the_style = re->style;\n\t\t\t\t\tNSString *searchsn = [NSString stringWithCharacters:strparambegin length:p-strparambegin];\n\t\t\t\t\t\n\t\t\t\t\tif ([searchsn length] > 0) {\n\t\t\t\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\t\t\t\tif ([searchsn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\t\t\t\tthe_style = &ssa->styles[j]; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tATSUCopyAttributes(the_style->atsustyle,cur_style);\n\t\t\t\t\tcur_color = the_style->color;\n\t\t\t\t\tcur_outline = the_style->outline;\n\t\t\t\t\tcur_shadow = the_style->shadow;\n\t\t\t\t\tcur_frz = the_style->angle;\n\t\t\t\t\tcur_scalex = cur_scaley = 1;\n\t\t\t\t\tcur_posx = cur_posy = -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction skip_t_tag {\n\t\t\t\t\twhile (p != pe && *p != ')' && *p != '}') p++;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction draw_mode {\n\t\t\t\t\tre->is_shape = inum != 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (fl == '0' || fl == '1') flag = fl - '0';})? > {flag = 0;};\n\t\t\t\tnum_ = \"-\"? digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = \"-\"? (digit+) > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = (\"H\"|\"&\"){,2} (xdigit+) > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|\"fsp\" num %ftrack\n\t\t\t\t\t\t\t\t|\"fscx\" num %fscalex\n\t\t\t\t\t\t\t\t|\"fscy\" num %fscaley\n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > strp_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"a\" intnum %ssa_alignment\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"1c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"2c\" color %secondarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t|\"1a\" color %primaryalpha\n\t\t\t\t\t\t\t\t|\"2a\" color %secondaryalpha\n\t\t\t\t\t\t\t\t|\"3a\" color %outlinealpha\n\t\t\t\t\t\t\t\t|\"4a\" color %shadowalpha\n\t\t\t\t\t\t\t\t|(\"r\" [^\\\\}]* > strp_begin %styleset)\n\t\t\t\t\t\t\t\t|(\"fe\"|\"k\"|\"kf\"|\"K\"|\"ko\"|\"q\"|\"fr\"|\"fad\"|\"move\"|\"clip\"|\"o\"|\"frx\"|\"fry\") [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"p\" num %draw_mode\n\t\t\t\t\t\t\t\t#|\"t\" [^)}]* # enabling this crashes ragel\n\t\t\t\t\t\t\t\t|\"t(\" % skip_t_tag\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = (\"\\\\\" :> cmd_specific)+;\n\t\t\t\t\n\t\t\t\tplaintext = [^}]*;\n\n\t\t\t\ttag = \"{\" (cmd | plaintext) % exit_tag \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nnh];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | (tag > enter_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (pb[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\t\t\tif (!cur_range.length) ATSUDisposeStyle(cur_style);\n \/\/PruneIdenticalStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\treturn rentities;\n}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"60a5063052e4811f15deceaddc6d0b4f85711774","subject":"lexer.rl: reduce literal method calls","message":"lexer.rl: reduce literal method calls\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n lit = literal\n if !lit.heredoc? && (token = lit.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n lit.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n lit = literal\n if lit.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if lit.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if lit.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n lit.extend_string(tok, @ts, @te)\n else\n lit.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if lit.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n lit.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n lit.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n lit = literal\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(lit.str_s, lit.str_s + 1)\n end\n\n if lit.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if lit.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n RBRACE_OR_RPAREN = %w\"} ]\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if RBRACE_OR_RPAREN.include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"926d326965a40b17673827b1cf2c7d85e6936512","subject":"* fix a bug","message":"* fix a bug\n","repos":"nineties\/amber","old_file":"rlc1\/eval.rl","new_file":"rlc1\/eval.rl","new_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: eval.rl 2010-05-29 11:05:11 nineties $\n %);\n\ninclude(stddef,code);\nexport(init_evaluator, assign, deref, check_arity, eval_sexp);\n\nsymbol_map: NULL; (% (symbol name, scope id) -> symbol object %);\n\nscopeid: 0;\nscopeid_stack: NULL;\n\n(% p0: (symbol name, scope id) %);\nsymbol_hash: (p0) {\n return strhash(p0[0])*3 + p0[1];\n};\n\nsymbol_equal: (p0, p1) {\n if (p0[1] != p1[1]) { return FALSE; };\n return streq(p0[0], p1[0]);\n};\n\nscope_push: () {\n scopeid = scopeid + 1;\n vec_pushback(scopeid_stack, scopeid);\n};\n\nscope_pop: () {\n vec_popback(scopeid_stack);\n};\n\n\n(% p0: symbol name, p1: value %);\nassign: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(symbol_map, mktup2(p0, x0), p1);\n};\n\n(% p0: symbol object %);\nderef: (p0) {\n allocate(4);\n x0 = vec_size(scopeid_stack)-1;\n x3 = sym_name(p0);\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(symbol_map, mktup2(x3, x1));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return p0;\n};\n\ncheck_arity: (p0, p1, p2) {\n if (length(p0) != p1) {\n fputs(stderr, \"ERROR '\");\n fputs(stderr, p2);\n fputs(stderr, \"': required \");\n fputi(stderr, p1);\n fputs(stderr, \" arguments\");\n exit(1);\n }\n};\n\neval_args: (p0) {\n if (p0 == nil_sym) { return nil_sym; };\n return mkcons(eval_sexp(car(p0)), eval_args(cdr(p0)));\n};\n\neval_cons: (p0) {\n allocate(2);\n x0 = car(p0);\n if (sym_p(x0) == nil_sym) { goto &eval_cons_error; };\n x1 = eval_sexp(x0);\n if (x1 == var_sym) { return eval_var(cdr(p0)); };\n if (x1 == set_sym) { return eval_set(cdr(p0)); };\n if (x1 == if_sym) { return eval_if(cdr(p0)); };\n if (x1 == cond_sym) { return eval_cond(cdr(p0)); };\n if (x1 == while_sym) { return eval_while(cdr(p0)); };\n if (x1 == do_sym) { return eval_do(cdr(p0)); };\n if (x1 == lambda_sym) { return eval_lambda(cdr(p0)); };\n if (x1 == macro_sym) { return eval_macro(cdr(p0)); };\n if (x1 == import_sym) { return eval_import(cdr(p0)); };\n if (prim_p(x1) != nil_sym) { return (prim_funptr(x1))(eval_args(cdr(p0))); };\n if (lambda_p(x1) != nil_sym) { return eval_applambda(x1, cdr(p0)); };\n if (macro_p(x1) != nil_sym) { return eval_appmacro(x1, cdr(p0)); };\nlabel eval_cons_error;\n fputs(stderr, \"ERROR: invalid application of '\");\n pp_sexp(stderr, car(p0));\n fputs(stderr, \"'\\n\");\n exit(1);\n};\n\n(% (var ) %);\neval_var: (p0) {\n allocate(2);\n check_arity(p0, 2, \"var\");\n x0 = car(p0);\n x1 = eval_sexp(cadr(p0));\n sym_set(x0, x1);\n assign(sym_name(x0), x0);\n return x0;\n};\n\neval_set: (p0) {\n allocate(2);\n check_arity(p0, 2, \"set\");\n x0 = deref(car(p0));\n x1 = eval_sexp(cadr(p0));\n if (sym_value(x0) == NULL) {\n fputs(stderr, \"ERROR 'eval_set': undefined variable '\");\n fputs(stderr, sym_name(x0));\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n sym_set(x0, x1);\n return x0;\n};\n\neval_quote: (p0) {\n allocate(1);\n if (cons_p(p0) != nil_sym) {\n return mkcons(eval_quote(car(p0)), eval_quote(cdr(p0)));\n };\n if (unquote_p(p0) != nil_sym) {\n return eval_sexp(unquote_sexp(p0));\n };\n return p0;\n};\n\n(% p0 : (cond ifthen ifelse) %);\neval_if: (p0) {\n allocate(2);\n check_arity(p0, 3, \"if\");\n scope_push();\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n if (x0 != nil_sym) {\n x1 = eval_sexp(car(p0));\n scope_pop();\n return x1;\n };\n x1 = eval_sexp(cadr(p0));\n scope_pop();\n return x1;\n};\n\neval_cond: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = car(p0);\n check_arity(x0, 2, \"cond\");\n if (eval_sexp(car(x0)) != nil_sym) {\n scope_pop();\n return eval_sexp(cadr(x0));\n };\n p0 = cdr(p0);\n };\n fputs(stderr, \"ERROR 'eval_cond': any condition was not met\\n\");\n exit(1);\n};\n\n(% p0: (cond body) %);\neval_while: (p0) {\n allocate(3);\n check_arity(p0, 2, \"while\");\n scope_push();\n x0 = car(p0); (% condition %);\n x1 = cadr(p0); (% body %);\n x2 = eval_sexp(x0);\n while (x2 != nil_sym) {\n eval_sexp(x1);\n x2 = eval_sexp(x0);\n };\n scope_pop();\n if (x2 != nil_sym) {\n fputs(stderr, \"ERROR 'while': conditional expression could not evaluated to true\/false\\n\");\n exit(1);\n };\n return nil_sym;\n};\n\neval_do: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n };\n scope_pop();\n return x0;\n};\n\n(% (lambda (params) body) %);\neval_lambda: (p0) {\n allocate(2);\n check_arity(p0, 2, \"lambda\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mklambda(x0, x1);\n};\n\n(% (macro (params) body) %);\neval_macro: (p0) {\n allocate(2);\n check_arity(p0, 2, \"macro\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mkmacro(x0, x1);\n};\n\n(% p0: argument pattern, p1:arguments %);\nmatch_args: (p0, p1) {\n allocate(1);\n if (sym_p(p0) != nil_sym) {\n x0 = mksym(sym_name(p0));\n sym_set(x0, p1);\n assign(sym_name(x0), x0);\n return;\n };\n if (cons_p(p0) != nil_sym) {\n match_args(car(p0), car(p1));\n match_args(cdr(p0), cdr(p1));\n return;\n };\n fputs(stderr, \"ERROR: invalid argument pattern\\n\");\n exit(1);\n};\n\n(% p0: lambda, p1: params %);\neval_applambda: (p0, p1) {\n allocate(1);\n scope_push();\n match_args(lambda_params(p0), eval_args(p1));\n x0 = eval_sexp(lambda_body(p0));\n scope_pop();\n return x0;\n};\n\n(% p0: macro, p1: params %);\neval_appmacro: (p0, p1) {\n allocate(3);\n scope_push();\n match_args(macro_params(p0), p1);\n x0 = eval_sexp(macro_body(p0));\n scope_pop();\n return eval_sexp(x0);\n (%\n x0 = macro_params(p0);\n if (length(x0) != length(p1)) {\n fputs(stderr, \"ERROR: invalid number of argument (must be \");\n fputi(stderr, length(x0));\n fputs(stderr, \")\\n\");\n exit(1);\n };\n\n scope_push();\n while (x0 != nil_sym) {\n x1 = mksym(sym_name(car(x0)));\n sym_set(x1, car(p1));\n assign(sym_name(x1), x1);\n x0 = cdr(x0);\n p1 = cdr(p1);\n };\n x2 = eval_sexp(macro_body(p0));\n scope_pop();\n return eval_sexp(x2);\n %);\n};\n\nimported : NULL;\n\neval_import: (p0) {\n allocate(3);\n check_arity(p0, 1, \"import\");\n x0 = eval_sexp(car(p0));\n if (string_p(x0) == nil_sym) {\n\tfputs(stderr, \"ERROR 'import': required string\\n\");\n\texit(1);\n };\n x1 = string_value(x0);\n if (set_contains(imported, x1)) {\n return nil_sym;\n };\n set_add(imported, x1);\n x2 = parse_module(x1);\n while (x2 != nil_sym) {\n\teval_sexp(car(x2));\n\tx2 = cdr(x2);\n };\n return nil_sym;\n};\n\neval_sexp: (p0) {\n allocate(2);\n x0 = p0[0]; (% node code %);\n if (x0 == NODE_CONS) { return eval_cons(p0); };\n if (x0 == NODE_SYMBOL) {\n x1 = deref(p0);\n if (sym_value(x1) != NULL) {\n return sym_value(x1);\n };\n return x1;\n };\n if (x0 == NODE_QUOTE) { return eval_quote(quote_sexp(p0)); };\n return p0;\n};\n\ninit_evaluator: () {\n symbol_map = mkmap(&symbol_hash, &symbol_equal, 100);\n imported = mkset(&strhash, &streq, 10);\n scopeid_stack = mkvec(0);\n scope_push(); (% global scope %);\n};\n\n","old_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: eval.rl 2010-05-29 10:58:35 nineties $\n %);\n\ninclude(stddef,code);\nexport(init_evaluator, assign, deref, check_arity, eval_sexp);\n\nsymbol_map: NULL; (% (symbol name, scope id) -> symbol object %);\n\nscopeid: 0;\nscopeid_stack: NULL;\n\n(% p0: (symbol name, scope id) %);\nsymbol_hash: (p0) {\n return strhash(p0[0])*3 + p0[1];\n};\n\nsymbol_equal: (p0, p1) {\n if (p0[1] != p1[1]) { return FALSE; };\n return streq(p0[0], p1[0]);\n};\n\nscope_push: () {\n scopeid = scopeid + 1;\n vec_pushback(scopeid_stack, scopeid);\n};\n\nscope_pop: () {\n vec_popback(scopeid_stack);\n};\n\n\n(% p0: symbol name, p1: value %);\nassign: (p0, p1) {\n allocate(1);\n x0 = vec_at(scopeid_stack, vec_size(scopeid_stack)-1);\n map_add(symbol_map, mktup2(p0, x0), p1);\n};\n\n(% p0: symbol object %);\nderef: (p0) {\n allocate(4);\n x0 = vec_size(scopeid_stack)-1;\n x3 = sym_name(p0);\n while (x0 >= 0) {\n x1 = vec_at(scopeid_stack, x0); (% scopeid-id %);\n x2 = map_find(symbol_map, mktup2(x3, x1));\n if (x2 != NULL) { return x2; };\n x0 = x0 - 1;\n };\n return p0;\n};\n\ncheck_arity: (p0, p1, p2) {\n if (length(p0) != p1) {\n fputs(stderr, \"ERROR '\");\n fputs(stderr, p2);\n fputs(stderr, \"': required \");\n fputi(stderr, p1);\n fputs(stderr, \" arguments\");\n exit(1);\n }\n};\n\neval_args: (p0) {\n if (p0 == nil_sym) { return nil_sym; };\n return mkcons(eval_sexp(car(p0)), eval_args(cdr(p0)));\n};\n\neval_cons: (p0) {\n allocate(2);\n x0 = car(p0);\n if (sym_p(x0) == nil_sym) { goto &eval_cons_error; };\n x1 = eval_sexp(x0);\n if (x1 == var_sym) { return eval_var(cdr(p0)); };\n if (x1 == set_sym) { return eval_set(cdr(p0)); };\n if (x1 == if_sym) { return eval_if(cdr(p0)); };\n if (x1 == cond_sym) { return eval_cond(cdr(p0)); };\n if (x1 == while_sym) { return eval_while(cdr(p0)); };\n if (x1 == do_sym) { return eval_do(cdr(p0)); };\n if (x1 == lambda_sym) { return eval_lambda(cdr(p0)); };\n if (x1 == macro_sym) { return eval_macro(cdr(p0)); };\n if (x1 == import_sym) { return eval_import(cdr(p0)); };\n if (prim_p(x1) != nil_sym) { return (prim_funptr(x1))(eval_args(cdr(p0))); };\n if (lambda_p(x1) != nil_sym) { return eval_applambda(x1, cdr(p0)); };\n if (macro_p(x1) != nil_sym) { return eval_appmacro(x1, cdr(p0)); };\nlabel eval_cons_error;\n fputs(stderr, \"ERROR: invalid application of '\");\n pp_sexp(stderr, car(p0));\n fputs(stderr, \"'\\n\");\n exit(1);\n};\n\n(% (var ) %);\neval_var: (p0) {\n allocate(2);\n check_arity(p0, 2, \"var\");\n x0 = car(p0);\n x1 = eval_sexp(cadr(p0));\n sym_set(x0, x1);\n assign(sym_name(x0), x0);\n return x0;\n};\n\neval_set: (p0) {\n allocate(2);\n check_arity(p0, 2, \"set\");\n x0 = deref(car(p0));\n x1 = eval_sexp(cadr(p0));\n if (sym_value(x0) == NULL) {\n fputs(stderr, \"ERROR 'eval_set': undefined variable '\");\n fputs(stderr, sym_name(x0));\n fputs(stderr, \"'\\n\");\n exit(1);\n };\n sym_set(x0, x1);\n return x0;\n};\n\neval_quote: (p0) {\n allocate(1);\n if (cons_p(p0) != nil_sym) {\n return mkcons(eval_quote(car(p0)), eval_quote(cdr(p0)));\n };\n if (unquote_p(p0) != nil_sym) {\n return eval_sexp(unquote_sexp(p0));\n };\n return p0;\n};\n\n(% p0 : (cond ifthen ifelse) %);\neval_if: (p0) {\n allocate(2);\n check_arity(p0, 3, \"if\");\n scope_push();\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n if (x0 != nil_sym) {\n x1 = eval_sexp(car(p0));\n scope_pop();\n return x1;\n };\n x1 = eval_sexp(cadr(p0));\n scope_pop();\n return x1;\n};\n\neval_cond: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = car(p0);\n check_arity(x0, 2, \"cond\");\n if (eval_sexp(car(x0)) != nil_sym) {\n scope_pop();\n return eval_sexp(cadr(x0));\n };\n p0 = cdr(p0);\n };\n fputs(stderr, \"ERROR 'eval_cond': any condition was not met\\n\");\n exit(1);\n};\n\n(% p0: (cond body) %);\neval_while: (p0) {\n allocate(3);\n check_arity(p0, 2, \"while\");\n scope_push();\n x0 = car(p0); (% condition %);\n x1 = cadr(p0); (% body %);\n x2 = eval_sexp(x0);\n while (x2 != nil_sym) {\n eval_sexp(x1);\n x2 = eval_sexp(x0);\n };\n scope_pop();\n if (x2 != nil_sym) {\n fputs(stderr, \"ERROR 'while': conditional expression could not evaluated to true\/false\\n\");\n exit(1);\n };\n return nil_sym;\n};\n\neval_do: (p0) {\n allocate(1);\n scope_push();\n while (p0 != nil_sym) {\n x0 = eval_sexp(car(p0));\n p0 = cdr(p0);\n };\n scope_pop();\n return x0;\n};\n\n(% (lambda (params) body) %);\neval_lambda: (p0) {\n allocate(2);\n check_arity(p0, 2, \"lambda\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mklambda(x0, x1);\n};\n\n(% (macro (params) body) %);\neval_macro: (p0) {\n allocate(2);\n check_arity(p0, 2, \"macro\");\n x0 = car(p0); (% params %);\n x1 = cadr(p0); (% body %);\n return mkmacro(x0, x1);\n};\n\n(% p0: argument pattern, p1:arguments %);\nmatch_args: (p0, p1) {\n allocate(1);\n if (sym_p(p0) != nil_sym) {\n x0 = mksym(sym_name(p0));\n sym_set(x0, p1);\n assign(sym_name(x0), x0);\n return;\n };\n if (cons_p(p0) != nil_sym) {\n match_args(car(p0), car(p1));\n match_args(cdr(p0), cdr(p1));\n return;\n };\n fputs(stderr, \"ERROR: invalid argument pattern\\n\");\n exit(1);\n};\n\n(% p0: lambda, p1: params %);\neval_applambda: (p0, p1) {\n allocate(1);\n scope_push();\n match_args(lambda_params(p0), eval_args(p1));\n x0 = eval_sexp(lambda_body(p0));\n scope_pop();\n return x0;\n};\n\n(% p0: macro, p1: params %);\neval_appmacro: (p0, p1) {\n allocate(3);\n scope_push();\n match_args(macro_params(p0), p1);\n x0 = eval_sexp(macro_body(p0));\n scope_pop();\n return eval_sexp(x0);\n (%\n x0 = macro_params(p0);\n if (length(x0) != length(p1)) {\n fputs(stderr, \"ERROR: invalid number of argument (must be \");\n fputi(stderr, length(x0));\n fputs(stderr, \")\\n\");\n exit(1);\n };\n\n scope_push();\n while (x0 != nil_sym) {\n x1 = mksym(sym_name(car(x0)));\n sym_set(x1, car(p1));\n assign(sym_name(x1), x1);\n x0 = cdr(x0);\n p1 = cdr(p1);\n };\n x2 = eval_sexp(macro_body(p0));\n scope_pop();\n return eval_sexp(x2);\n %);\n};\n\nimported : NULL;\n\neval_import: (p0) {\n allocate(2);\n check_arity(p0, 1, \"import\");\n x0 = eval_sexp(car(p0));\n if (string_p(x0) == nil_sym) {\n\tfputs(stderr, \"ERROR 'import': required string\\n\");\n\texit(1);\n };\n x1 = string_value(x0);\n if (set_contains(imported, x1)) {\n return nil_sym;\n };\n set_add(imported, x1);\n x2 = parse_module(x1);\n while (x2 != nil_sym) {\n\teval_sexp(car(x2));\n\tx2 = cdr(x2);\n };\n return nil_sym;\n};\n\neval_sexp: (p0) {\n allocate(2);\n x0 = p0[0]; (% node code %);\n if (x0 == NODE_CONS) { return eval_cons(p0); };\n if (x0 == NODE_SYMBOL) {\n x1 = deref(p0);\n if (sym_value(x1) != NULL) {\n return sym_value(x1);\n };\n return x1;\n };\n if (x0 == NODE_QUOTE) { return eval_quote(quote_sexp(p0)); };\n return p0;\n};\n\ninit_evaluator: () {\n symbol_map = mkmap(&symbol_hash, &symbol_equal, 100);\n imported = mkset(&strhash, &streq, 10);\n scopeid_stack = mkvec(0);\n scope_push(); (% global scope %);\n};\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"37a0ff8928fb0d83cec0d0d8909c5a4abcd221af","subject":"Initialize the on_fragment callback pointer","message":"Initialize the on_fragment callback pointer\n\nhttp_parser_init() did not initialize the http_parser.on_fragment.\n","repos":"TooTallNate\/http-parser,mopemope\/http-parser,OpenMusicKontrollers\/chimaerad,nikicat\/http-parser,tml\/http-parser,tjweir\/http-parser,OpenMusicKontrollers\/chimaerad,humbletim\/http-parser,apaprocki\/http-parser,ignacio\/http-parser,thomaslee\/http-parser,OpenMusicKontrollers\/chimaerad,OpenMusicKontrollers\/chimaerad,OpenMusicKontrollers\/chimaerad,tmm1\/http-parser,OpenMusicKontrollers\/chimaerad,arsane\/http-parser","old_file":"http_parser.rl","new_file":"http_parser.rl","new_contents":"\/* Copyright (c) 2008, 2009 Ryan Dahl (ry@tinyclouds.org)\n * Based on Zed Shaw's Mongrel, copyright (c) Zed A. Shaw\n *\n * All rights reserved.\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n *\/\n#include \"http_parser.h\"\n#include \n#include \n\nstatic int unhex[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n };\n#define TRUE 1\n#define FALSE 0\n#define MIN(a,b) (a < b ? a : b)\n#define NULL (void*)(0)\n\n#define MAX_FIELD_SIZE 80*1024\n\n#define REMAINING (unsigned long)(pe - p)\n#define CALLBACK(FOR) \\\ndo { \\\n if (parser->FOR##_mark) { \\\n parser->FOR##_size += p - parser->FOR##_mark; \\\n if (parser->FOR##_size > MAX_FIELD_SIZE) { \\\n parser->error = TRUE; \\\n return 0; \\\n } \\\n if (parser->on_##FOR) { \\\n callback_return_value = parser->on_##FOR(parser, \\\n parser->FOR##_mark, \\\n p - parser->FOR##_mark); \\\n } \\\n } \\\n} while(0)\n\n#define RESET_PARSER(parser) \\\n parser->chunk_size = 0; \\\n parser->eating = 0; \\\n parser->header_field_mark = NULL; \\\n parser->header_value_mark = NULL; \\\n parser->query_string_mark = NULL; \\\n parser->path_mark = NULL; \\\n parser->uri_mark = NULL; \\\n parser->fragment_mark = NULL; \\\n parser->status_code = 0; \\\n parser->method = 0; \\\n parser->transfer_encoding = HTTP_IDENTITY; \\\n parser->version_major = 0; \\\n parser->version_minor = 0; \\\n parser->keep_alive = -1; \\\n parser->content_length = 0; \\\n parser->body_read = 0; \n\n#define END_REQUEST \\\ndo { \\\n if (parser->on_message_complete) { \\\n callback_return_value = \\\n parser->on_message_complete(parser); \\\n } \\\n RESET_PARSER(parser); \\\n} while (0)\n\n#define SKIP_BODY(nskip) \\\ndo { \\\n tmp = (nskip); \\\n if (parser->on_body && tmp > 0) { \\\n callback_return_value = parser->on_body(parser, p, tmp); \\\n } \\\n if (callback_return_value == 0) { \\\n p += tmp; \\\n parser->body_read += tmp; \\\n parser->chunk_size -= tmp; \\\n if (0 == parser->chunk_size) { \\\n parser->eating = FALSE; \\\n if (parser->transfer_encoding == HTTP_IDENTITY) { \\\n END_REQUEST; \\\n } \\\n } else { \\\n parser->eating = TRUE; \\\n } \\\n } \\\n} while (0)\n\n%%{\n machine http_parser;\n\n action mark_header_field {\n parser->header_field_mark = p;\n parser->header_field_size = 0;\n }\n\n action mark_header_value {\n parser->header_value_mark = p;\n parser->header_value_size = 0;\n }\n\n action mark_fragment {\n parser->fragment_mark = p;\n parser->fragment_size = 0;\n }\n\n action mark_query_string {\n parser->query_string_mark = p;\n parser->query_string_size = 0;\n }\n\n action mark_request_path {\n parser->path_mark = p;\n parser->path_size = 0;\n }\n\n action mark_request_uri {\n parser->uri_mark = p;\n parser->uri_size = 0;\n }\n\n action header_field {\n CALLBACK(header_field);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->header_field_mark = NULL;\n parser->header_field_size = 0;\n }\n\n action header_value {\n CALLBACK(header_value);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->header_value_mark = NULL;\n parser->header_value_size = 0;\n }\n\n action request_uri { \n CALLBACK(uri);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->uri_mark = NULL;\n parser->uri_size = 0;\n }\n\n action fragment { \n CALLBACK(fragment);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->fragment_mark = NULL;\n parser->fragment_size = 0;\n }\n\n action query_string { \n CALLBACK(query_string);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->query_string_mark = NULL;\n parser->query_string_size = 0;\n }\n\n action request_path {\n CALLBACK(path);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->path_mark = NULL;\n parser->path_size = 0;\n }\n\n action headers_complete {\n if(parser->on_headers_complete) {\n callback_return_value = parser->on_headers_complete(parser);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n }\n }\n\n action begin_message {\n if(parser->on_message_begin) {\n callback_return_value = parser->on_message_begin(parser);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n }\n }\n\n action content_length {\n if (parser->content_length > INT_MAX) {\n parser->error = TRUE;\n return 0;\n }\n parser->content_length *= 10;\n parser->content_length += *p - '0';\n }\n\n action status_code {\n parser->status_code *= 10;\n parser->status_code += *p - '0';\n }\n\n action use_identity_encoding { parser->transfer_encoding = HTTP_IDENTITY; }\n action use_chunked_encoding { parser->transfer_encoding = HTTP_CHUNKED; }\n\n action set_keep_alive { parser->keep_alive = TRUE; }\n action set_not_keep_alive { parser->keep_alive = FALSE; }\n\n action version_major {\n parser->version_major *= 10;\n parser->version_major += *p - '0';\n }\n\n action version_minor {\n parser->version_minor *= 10;\n parser->version_minor += *p - '0';\n }\n\n action add_to_chunk_size {\n parser->chunk_size *= 16;\n parser->chunk_size += unhex[(int)*p];\n }\n\n action skip_chunk_data {\n SKIP_BODY(MIN(parser->chunk_size, REMAINING));\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n\n fhold; \n if (parser->chunk_size > REMAINING) {\n fbreak;\n } else {\n fgoto chunk_end; \n }\n }\n\n action end_chunked_body {\n END_REQUEST;\n if (parser->type == HTTP_REQUEST) {\n fnext Requests;\n } else {\n fnext Responses;\n }\n }\n\n action body_logic {\n if (parser->transfer_encoding == HTTP_CHUNKED) {\n fnext ChunkedBody;\n } else {\n \/* this is pretty stupid. i'd prefer to combine this with skip_chunk_data *\/\n parser->chunk_size = parser->content_length;\n p += 1; \n\n SKIP_BODY(MIN(REMAINING, parser->content_length));\n\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n\n fhold;\n if(parser->chunk_size > REMAINING) {\n fbreak;\n }\n }\n }\n\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" \n | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n quote = \"\\\"\";\n# qdtext = token -- \"\\\"\"; \n# quoted_pair = \"\\\" ascii;\n# quoted_string = \"\\\"\" (qdtext | quoted_pair )* \"\\\"\";\n\n# headers\n\n Method = ( \"COPY\" %{ parser->method = HTTP_COPY; }\n | \"DELETE\" %{ parser->method = HTTP_DELETE; }\n | \"GET\" %{ parser->method = HTTP_GET; }\n | \"HEAD\" %{ parser->method = HTTP_HEAD; }\n | \"LOCK\" %{ parser->method = HTTP_LOCK; }\n | \"MKCOL\" %{ parser->method = HTTP_MKCOL; }\n | \"MOVE\" %{ parser->method = HTTP_MOVE; }\n | \"OPTIONS\" %{ parser->method = HTTP_OPTIONS; }\n | \"POST\" %{ parser->method = HTTP_POST; }\n | \"PROPFIND\" %{ parser->method = HTTP_PROPFIND; }\n | \"PROPPATCH\" %{ parser->method = HTTP_PROPPATCH; }\n | \"PUT\" %{ parser->method = HTTP_PUT; }\n | \"TRACE\" %{ parser->method = HTTP_TRACE; }\n | \"UNLOCK\" %{ parser->method = HTTP_UNLOCK; }\n ); # Not allowing extension methods\n\n HTTP_Version = \"HTTP\/\" digit $version_major \".\" digit $version_minor;\n\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n path = ( pchar+ ( \"\/\" pchar* )* ) ;\n query = ( uchar | reserved )* >mark_query_string %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = ( param ( \";\" param )* ) ;\n rel_path = ( path? (\";\" params)? ) ;\n absolute_path = ( \"\/\"+ rel_path ) >mark_request_path %request_path (\"?\" query)?;\n Request_URI = ( \"*\" | absolute_uri | absolute_path ) >mark_request_uri %request_uri;\n Fragment = ( uchar | reserved )* >mark_fragment %fragment;\n\n field_name = ( token -- \":\" )+;\n Field_Name = field_name >mark_header_field %header_field;\n\n field_value = ((any - \" \") any*)?;\n Field_Value = field_value >mark_header_value %header_value;\n\n hsep = \":\" \" \"*;\n header = (field_name hsep field_value) :> CRLF;\n Header = ( (\"Content-Length\"i hsep digit+ $content_length)\n | (\"Connection\"i hsep \n ( \"Keep-Alive\"i %set_keep_alive\n | \"close\"i %set_not_keep_alive\n )\n )\n | (\"Transfer-Encoding\"i %use_chunked_encoding hsep \"identity\" %use_identity_encoding)\n | (Field_Name hsep Field_Value)\n ) :> CRLF;\n\n Headers = (Header)* :> CRLF @headers_complete;\n\n Request_Line = ( Method \" \" Request_URI (\"#\" Fragment)? \" \" HTTP_Version CRLF ) ;\n\n StatusCode = (digit digit digit) $status_code;\n ReasonPhrase = ascii* -- (\"\\r\" | \"\\n\");\n StatusLine = HTTP_Version \" \" StatusCode (\" \" ReasonPhrase)? CRLF;\n\n# chunked message\n trailing_headers = header*;\n #chunk_ext_val = token | quoted_string;\n chunk_ext_val = token*;\n chunk_ext_name = token*;\n chunk_extension = ( \";\" \" \"* chunk_ext_name (\"=\" chunk_ext_val)? )*;\n last_chunk = \"0\"+ chunk_extension CRLF;\n chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size;\n chunk_end = CRLF;\n chunk_body = any >skip_chunk_data;\n chunk_begin = chunk_size chunk_extension CRLF;\n chunk = chunk_begin chunk_body chunk_end;\n ChunkedBody := chunk* last_chunk trailing_headers CRLF @end_chunked_body;\n\n Request = (Request_Line Headers) >begin_message @body_logic;\n Response = (StatusLine Headers) >begin_message @body_logic;\n\n Requests := Request*;\n Responses := Response*;\n\n main := any >{\n fhold;\n if (parser->type == HTTP_REQUEST) {\n fgoto Requests;\n } else {\n fgoto Responses;\n }\n };\n\n}%%\n\n%% write data;\n\nvoid\nhttp_parser_init (http_parser *parser, enum http_parser_type type) \n{\n int cs = 0;\n %% write init;\n parser->cs = cs;\n parser->type = type;\n parser->error = 0;\n\n parser->on_message_begin = NULL;\n parser->on_path = NULL;\n parser->on_query_string = NULL;\n parser->on_uri = NULL;\n parser->on_fragment = NULL;\n parser->on_header_field = NULL;\n parser->on_header_value = NULL;\n parser->on_headers_complete = NULL;\n parser->on_body = NULL;\n parser->on_message_complete = NULL;\n\n RESET_PARSER(parser);\n}\n\n\/** exec **\/\nsize_t\nhttp_parser_execute (http_parser *parser, const char *buffer, size_t len)\n{\n size_t tmp; \/\/ REMOVE ME this is extremely hacky\n int callback_return_value = 0;\n const char *p, *pe;\n int cs = parser->cs;\n\n p = buffer;\n pe = buffer+len;\n\n if (0 < parser->chunk_size && parser->eating) {\n \/* eat body *\/\n SKIP_BODY(MIN(len, parser->chunk_size));\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n }\n\n if (parser->header_field_mark) parser->header_field_mark = buffer;\n if (parser->header_value_mark) parser->header_value_mark = buffer;\n if (parser->fragment_mark) parser->fragment_mark = buffer;\n if (parser->query_string_mark) parser->query_string_mark = buffer;\n if (parser->path_mark) parser->path_mark = buffer;\n if (parser->uri_mark) parser->uri_mark = buffer;\n\n %% write exec;\n\n parser->cs = cs;\n\n CALLBACK(header_field);\n CALLBACK(header_value);\n CALLBACK(fragment);\n CALLBACK(query_string);\n CALLBACK(path);\n CALLBACK(uri);\n\n assert(p <= pe && \"buffer overflow after parsing execute\");\n return(p - buffer);\n}\n\nint\nhttp_parser_has_error (http_parser *parser) \n{\n if (parser->error) return TRUE;\n return parser->cs == http_parser_error;\n}\n\nint\nhttp_parser_should_keep_alive (http_parser *parser)\n{\n if (parser->keep_alive == -1)\n if (parser->version_major == 1)\n return (parser->version_minor != 0);\n else if (parser->version_major == 0)\n return FALSE;\n else\n return TRUE;\n else\n return parser->keep_alive;\n}\n","old_contents":"\/* Copyright (c) 2008, 2009 Ryan Dahl (ry@tinyclouds.org)\n * Based on Zed Shaw's Mongrel, copyright (c) Zed A. Shaw\n *\n * All rights reserved.\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n *\/\n#include \"http_parser.h\"\n#include \n#include \n\nstatic int unhex[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n };\n#define TRUE 1\n#define FALSE 0\n#define MIN(a,b) (a < b ? a : b)\n#define NULL (void*)(0)\n\n#define MAX_FIELD_SIZE 80*1024\n\n#define REMAINING (unsigned long)(pe - p)\n#define CALLBACK(FOR) \\\ndo { \\\n if (parser->FOR##_mark) { \\\n parser->FOR##_size += p - parser->FOR##_mark; \\\n if (parser->FOR##_size > MAX_FIELD_SIZE) { \\\n parser->error = TRUE; \\\n return 0; \\\n } \\\n if (parser->on_##FOR) { \\\n callback_return_value = parser->on_##FOR(parser, \\\n parser->FOR##_mark, \\\n p - parser->FOR##_mark); \\\n } \\\n } \\\n} while(0)\n\n#define RESET_PARSER(parser) \\\n parser->chunk_size = 0; \\\n parser->eating = 0; \\\n parser->header_field_mark = NULL; \\\n parser->header_value_mark = NULL; \\\n parser->query_string_mark = NULL; \\\n parser->path_mark = NULL; \\\n parser->uri_mark = NULL; \\\n parser->fragment_mark = NULL; \\\n parser->status_code = 0; \\\n parser->method = 0; \\\n parser->transfer_encoding = HTTP_IDENTITY; \\\n parser->version_major = 0; \\\n parser->version_minor = 0; \\\n parser->keep_alive = -1; \\\n parser->content_length = 0; \\\n parser->body_read = 0; \n\n#define END_REQUEST \\\ndo { \\\n if (parser->on_message_complete) { \\\n callback_return_value = \\\n parser->on_message_complete(parser); \\\n } \\\n RESET_PARSER(parser); \\\n} while (0)\n\n#define SKIP_BODY(nskip) \\\ndo { \\\n tmp = (nskip); \\\n if (parser->on_body && tmp > 0) { \\\n callback_return_value = parser->on_body(parser, p, tmp); \\\n } \\\n if (callback_return_value == 0) { \\\n p += tmp; \\\n parser->body_read += tmp; \\\n parser->chunk_size -= tmp; \\\n if (0 == parser->chunk_size) { \\\n parser->eating = FALSE; \\\n if (parser->transfer_encoding == HTTP_IDENTITY) { \\\n END_REQUEST; \\\n } \\\n } else { \\\n parser->eating = TRUE; \\\n } \\\n } \\\n} while (0)\n\n%%{\n machine http_parser;\n\n action mark_header_field {\n parser->header_field_mark = p;\n parser->header_field_size = 0;\n }\n\n action mark_header_value {\n parser->header_value_mark = p;\n parser->header_value_size = 0;\n }\n\n action mark_fragment {\n parser->fragment_mark = p;\n parser->fragment_size = 0;\n }\n\n action mark_query_string {\n parser->query_string_mark = p;\n parser->query_string_size = 0;\n }\n\n action mark_request_path {\n parser->path_mark = p;\n parser->path_size = 0;\n }\n\n action mark_request_uri {\n parser->uri_mark = p;\n parser->uri_size = 0;\n }\n\n action header_field {\n CALLBACK(header_field);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->header_field_mark = NULL;\n parser->header_field_size = 0;\n }\n\n action header_value {\n CALLBACK(header_value);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->header_value_mark = NULL;\n parser->header_value_size = 0;\n }\n\n action request_uri { \n CALLBACK(uri);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->uri_mark = NULL;\n parser->uri_size = 0;\n }\n\n action fragment { \n CALLBACK(fragment);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->fragment_mark = NULL;\n parser->fragment_size = 0;\n }\n\n action query_string { \n CALLBACK(query_string);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->query_string_mark = NULL;\n parser->query_string_size = 0;\n }\n\n action request_path {\n CALLBACK(path);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n parser->path_mark = NULL;\n parser->path_size = 0;\n }\n\n action headers_complete {\n if(parser->on_headers_complete) {\n callback_return_value = parser->on_headers_complete(parser);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n }\n }\n\n action begin_message {\n if(parser->on_message_begin) {\n callback_return_value = parser->on_message_begin(parser);\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n }\n }\n\n action content_length {\n if (parser->content_length > INT_MAX) {\n parser->error = TRUE;\n return 0;\n }\n parser->content_length *= 10;\n parser->content_length += *p - '0';\n }\n\n action status_code {\n parser->status_code *= 10;\n parser->status_code += *p - '0';\n }\n\n action use_identity_encoding { parser->transfer_encoding = HTTP_IDENTITY; }\n action use_chunked_encoding { parser->transfer_encoding = HTTP_CHUNKED; }\n\n action set_keep_alive { parser->keep_alive = TRUE; }\n action set_not_keep_alive { parser->keep_alive = FALSE; }\n\n action version_major {\n parser->version_major *= 10;\n parser->version_major += *p - '0';\n }\n\n action version_minor {\n parser->version_minor *= 10;\n parser->version_minor += *p - '0';\n }\n\n action add_to_chunk_size {\n parser->chunk_size *= 16;\n parser->chunk_size += unhex[(int)*p];\n }\n\n action skip_chunk_data {\n SKIP_BODY(MIN(parser->chunk_size, REMAINING));\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n\n fhold; \n if (parser->chunk_size > REMAINING) {\n fbreak;\n } else {\n fgoto chunk_end; \n }\n }\n\n action end_chunked_body {\n END_REQUEST;\n if (parser->type == HTTP_REQUEST) {\n fnext Requests;\n } else {\n fnext Responses;\n }\n }\n\n action body_logic {\n if (parser->transfer_encoding == HTTP_CHUNKED) {\n fnext ChunkedBody;\n } else {\n \/* this is pretty stupid. i'd prefer to combine this with skip_chunk_data *\/\n parser->chunk_size = parser->content_length;\n p += 1; \n\n SKIP_BODY(MIN(REMAINING, parser->content_length));\n\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n\n fhold;\n if(parser->chunk_size > REMAINING) {\n fbreak;\n }\n }\n }\n\n CRLF = \"\\r\\n\";\n\n# character types\n CTL = (cntrl | 127);\n safe = (\"$\" | \"-\" | \"_\" | \".\");\n extra = (\"!\" | \"*\" | \"'\" | \"(\" | \")\" | \",\");\n reserved = (\";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n unsafe = (CTL | \" \" | \"\\\"\" | \"#\" | \"%\" | \"<\" | \">\");\n national = any -- (alpha | digit | reserved | extra | safe | unsafe);\n unreserved = (alpha | digit | safe | extra | national);\n escape = (\"%\" xdigit xdigit);\n uchar = (unreserved | escape);\n pchar = (uchar | \":\" | \"@\" | \"&\" | \"=\" | \"+\");\n tspecials = (\"(\" | \")\" | \"<\" | \">\" | \"@\" | \",\" | \";\" | \":\" | \"\\\\\" | \"\\\"\" \n | \"\/\" | \"[\" | \"]\" | \"?\" | \"=\" | \"{\" | \"}\" | \" \" | \"\\t\");\n\n# elements\n token = (ascii -- (CTL | tspecials));\n quote = \"\\\"\";\n# qdtext = token -- \"\\\"\"; \n# quoted_pair = \"\\\" ascii;\n# quoted_string = \"\\\"\" (qdtext | quoted_pair )* \"\\\"\";\n\n# headers\n\n Method = ( \"COPY\" %{ parser->method = HTTP_COPY; }\n | \"DELETE\" %{ parser->method = HTTP_DELETE; }\n | \"GET\" %{ parser->method = HTTP_GET; }\n | \"HEAD\" %{ parser->method = HTTP_HEAD; }\n | \"LOCK\" %{ parser->method = HTTP_LOCK; }\n | \"MKCOL\" %{ parser->method = HTTP_MKCOL; }\n | \"MOVE\" %{ parser->method = HTTP_MOVE; }\n | \"OPTIONS\" %{ parser->method = HTTP_OPTIONS; }\n | \"POST\" %{ parser->method = HTTP_POST; }\n | \"PROPFIND\" %{ parser->method = HTTP_PROPFIND; }\n | \"PROPPATCH\" %{ parser->method = HTTP_PROPPATCH; }\n | \"PUT\" %{ parser->method = HTTP_PUT; }\n | \"TRACE\" %{ parser->method = HTTP_TRACE; }\n | \"UNLOCK\" %{ parser->method = HTTP_UNLOCK; }\n ); # Not allowing extension methods\n\n HTTP_Version = \"HTTP\/\" digit $version_major \".\" digit $version_minor;\n\n scheme = ( alpha | digit | \"+\" | \"-\" | \".\" )* ;\n absolute_uri = (scheme \":\" (uchar | reserved )*);\n path = ( pchar+ ( \"\/\" pchar* )* ) ;\n query = ( uchar | reserved )* >mark_query_string %query_string ;\n param = ( pchar | \"\/\" )* ;\n params = ( param ( \";\" param )* ) ;\n rel_path = ( path? (\";\" params)? ) ;\n absolute_path = ( \"\/\"+ rel_path ) >mark_request_path %request_path (\"?\" query)?;\n Request_URI = ( \"*\" | absolute_uri | absolute_path ) >mark_request_uri %request_uri;\n Fragment = ( uchar | reserved )* >mark_fragment %fragment;\n\n field_name = ( token -- \":\" )+;\n Field_Name = field_name >mark_header_field %header_field;\n\n field_value = ((any - \" \") any*)?;\n Field_Value = field_value >mark_header_value %header_value;\n\n hsep = \":\" \" \"*;\n header = (field_name hsep field_value) :> CRLF;\n Header = ( (\"Content-Length\"i hsep digit+ $content_length)\n | (\"Connection\"i hsep \n ( \"Keep-Alive\"i %set_keep_alive\n | \"close\"i %set_not_keep_alive\n )\n )\n | (\"Transfer-Encoding\"i %use_chunked_encoding hsep \"identity\" %use_identity_encoding)\n | (Field_Name hsep Field_Value)\n ) :> CRLF;\n\n Headers = (Header)* :> CRLF @headers_complete;\n\n Request_Line = ( Method \" \" Request_URI (\"#\" Fragment)? \" \" HTTP_Version CRLF ) ;\n\n StatusCode = (digit digit digit) $status_code;\n ReasonPhrase = ascii* -- (\"\\r\" | \"\\n\");\n StatusLine = HTTP_Version \" \" StatusCode (\" \" ReasonPhrase)? CRLF;\n\n# chunked message\n trailing_headers = header*;\n #chunk_ext_val = token | quoted_string;\n chunk_ext_val = token*;\n chunk_ext_name = token*;\n chunk_extension = ( \";\" \" \"* chunk_ext_name (\"=\" chunk_ext_val)? )*;\n last_chunk = \"0\"+ chunk_extension CRLF;\n chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size;\n chunk_end = CRLF;\n chunk_body = any >skip_chunk_data;\n chunk_begin = chunk_size chunk_extension CRLF;\n chunk = chunk_begin chunk_body chunk_end;\n ChunkedBody := chunk* last_chunk trailing_headers CRLF @end_chunked_body;\n\n Request = (Request_Line Headers) >begin_message @body_logic;\n Response = (StatusLine Headers) >begin_message @body_logic;\n\n Requests := Request*;\n Responses := Response*;\n\n main := any >{\n fhold;\n if (parser->type == HTTP_REQUEST) {\n fgoto Requests;\n } else {\n fgoto Responses;\n }\n };\n\n}%%\n\n%% write data;\n\nvoid\nhttp_parser_init (http_parser *parser, enum http_parser_type type) \n{\n int cs = 0;\n %% write init;\n parser->cs = cs;\n parser->type = type;\n parser->error = 0;\n\n parser->on_message_begin = NULL;\n parser->on_path = NULL;\n parser->on_query_string = NULL;\n parser->on_uri = NULL;\n parser->on_header_field = NULL;\n parser->on_header_value = NULL;\n parser->on_headers_complete = NULL;\n parser->on_body = NULL;\n parser->on_message_complete = NULL;\n\n RESET_PARSER(parser);\n}\n\n\/** exec **\/\nsize_t\nhttp_parser_execute (http_parser *parser, const char *buffer, size_t len)\n{\n size_t tmp; \/\/ REMOVE ME this is extremely hacky\n int callback_return_value = 0;\n const char *p, *pe;\n int cs = parser->cs;\n\n p = buffer;\n pe = buffer+len;\n\n if (0 < parser->chunk_size && parser->eating) {\n \/* eat body *\/\n SKIP_BODY(MIN(len, parser->chunk_size));\n if (callback_return_value != 0) {\n parser->error = TRUE;\n return 0;\n }\n }\n\n if (parser->header_field_mark) parser->header_field_mark = buffer;\n if (parser->header_value_mark) parser->header_value_mark = buffer;\n if (parser->fragment_mark) parser->fragment_mark = buffer;\n if (parser->query_string_mark) parser->query_string_mark = buffer;\n if (parser->path_mark) parser->path_mark = buffer;\n if (parser->uri_mark) parser->uri_mark = buffer;\n\n %% write exec;\n\n parser->cs = cs;\n\n CALLBACK(header_field);\n CALLBACK(header_value);\n CALLBACK(fragment);\n CALLBACK(query_string);\n CALLBACK(path);\n CALLBACK(uri);\n\n assert(p <= pe && \"buffer overflow after parsing execute\");\n return(p - buffer);\n}\n\nint\nhttp_parser_has_error (http_parser *parser) \n{\n if (parser->error) return TRUE;\n return parser->cs == http_parser_error;\n}\n\nint\nhttp_parser_should_keep_alive (http_parser *parser)\n{\n if (parser->keep_alive == -1)\n if (parser->version_major == 1)\n return (parser->version_minor != 0);\n else if (parser->version_major == 0)\n return FALSE;\n else\n return TRUE;\n else\n return parser->keep_alive;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"efae4c9e2a664f8198a411a5f3d46ce17feaa93f","subject":"support named constants in assembler, add some new integer and string ops","message":"support named constants in assembler, add some new integer and string ops\n","repos":"wahern\/dns,wahern\/dns","old_file":"src\/spf.rl","new_file":"src\/spf.rl","new_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (SPF_DEBUG > 0) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (!(cond)) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic int vm_indexof(struct spf_vm *vm, int p) {\n\tif (p < 0)\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puti, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (SPF_DEBUG >= 2) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tcontinue;\n\t\t\t\tsub_emit(&sub, code);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t}\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","old_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf setjmp(3) longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (SPF_DEBUG > 0) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-1) == S(-2) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\tlongjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (!(cond)) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic int vm_indexof(struct spf_vm *vm, int p) {\n\tif (p < 0)\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, t & vm_typeof(vm, p), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tfor (i = 0; i < n; i++) {\n\t\tvm_assert(vm, ++vm->pc < vm->end, EFAULT);\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tvm_assert(vm, fgets(sbuf, sizeof sbuf, stdin), ((ferror(stdin))? errno : EINVAL));\n\tspf_rtrim(sbuf, \"\\r\\n\");\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puti, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (SPF_DEBUG >= 2) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto strcode;\n\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nstrcode:\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t}\n\t\t}\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"622f51a40479a2e9cc5d08dfb135455c3004bae4","subject":"[jnc_test] added async\/await tokens to jancy highlighter","message":"[jnc_test] added async\/await tokens to jancy highlighter\n","repos":"vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy","old_file":"test\/jnc_test_qt\/jancyhighlighter.rl","new_file":"test\/jnc_test_qt\/jancyhighlighter.rl","new_contents":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n%%{\n\nmachine jancy_lexer;\nwrite data;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n';\nlc_nl = '\\\\' '\\r'? nl;\nesc = '\\\\' [^\\n];\n\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* ([\"\\\\] | nl);\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* (['\\\\] | nl);\nraw_lit_dq = '\"' [^\"\\n]* ('\"' | nl);\nraw_lit_sq = \"'\" [^'\\n]* (\"'\" | nl);\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n(\n'import' |\n'namespace' |\n'extension' |\n'dynamiclib' |\n'using' |\n'friend' |\n'public' |\n'protected' |\n'alignment' |\n'setas' |\n\n'typedef' |\n'alias' |\n'static' |\n'threadlocal' |\n'stack' |\n'heap' |\n'abstract' |\n'virtual' |\n'override' |\n'mutable' |\n'disposable' |\n\n'signed' |\n'unsigned' |\n'bigendian' |\n'const' |\n'cmut' |\n'readonly' |\n'volatile' |\n'safe' |\n'unsafe' |\n'weak' |\n'thin' |\n'errorcode' |\n'cdecl' |\n'stdcall' |\n'thiscall' |\n'jnccall' |\n'array' |\n'function' |\n'property' |\n'bindable' |\n'autoget' |\n'indexed' |\n'multicast' |\n'event' |\n'reactor' |\n'async' |\n\n'anydata' |\n'void' |\n'variant' |\n'bool' |\n'int' |\n'intptr' |\n'char' |\n'short' |\n'long' |\n'float' |\n'double' |\n'enum' |\n'struct' |\n'union' |\n'class' |\n'opaque' |\n'exposed' |\n'bitflag' |\n\n'get' |\n'set' |\n'preconstruct' |\n'construct' |\n'destruct' |\n'operator' |\n'postfix' |\n\n'if' |\n'else' |\n'for' |\n'while' |\n'do' |\n'break' |\n'break' [1-9]? |\n'continue' [1-9]? |\n'return' |\n'switch' |\n'reswitch' |\n'case' |\n'default' |\n'once' |\n'onevent' |\n'try' |\n'throw' |\n'catch' |\n'finally' |\n'nestedscope' |\n'assert' |\n'await' |\n\n'basetype' [1-9]? |\n'this' |\n'true' |\n'false' |\n'null' |\n\n'new' |\n'delete' |\n'sizeof' |\n'countof' |\n'offsetof' |\n'typeof' |\n'bindingof' |\n'dynamic'\n\n) { colorize (ts, te, Qt::blue); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\nid ;\n\n(\nlit_sq |\nlit_dq |\n[rR] raw_lit_sq |\n[rR] raw_lit_dq |\ndec+ |\n'0' oct+ |\n'0' [xX] hex+ |\n'0' [oO] oct+ |\n'0' [bB] bin+ |\n'0' [nNdD] dec+ |\n'0' [xXoObBnNdD] raw_lit_dq |\ndec+ (('.' dec*) | ([eE] [+\\-]? dec+)) |\n[$fF] lit_dq\n)\t\t\t\t\t{ colorize (ts, te, Qt::darkRed); };\n\n('0' [xXoObBnNdD])? '\"\"\"'\n\t\t\t\t\t{ colorize (ts, te, Qt::darkRed); fgoto lit_ml; };\n\n'\/\/' any* { colorize (ts, te, Qt::darkGray); };\n'\/*' { colorize (ts, te, Qt::darkGray); fgoto comment; };\n\nws | nl ;\nany ;\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# comment machine\n#\n\ncomment := |*\n\n'*\/' { colorize (ts, te, Qt::darkGray); fgoto main; };\nany { colorize (ts, te, Qt::darkGray); };\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\n'\"\"\"' { colorize (ts, te, Qt::darkRed); fgoto main; };\nany { colorize (ts, te, Qt::darkRed); };\n\n*|;\n\n}%%\n\n\/\/..............................................................................\n\n#define BLOCK_STATE_NONE\t0\n#define BLOCK_STATE_COMMENT 1\n#define BLOCK_STATE_LIT_ML 2\n\nvoid JancyHighlighter::ragelInit ()\n{\n\t%% write init;\n}\n\nvoid JancyHighlighter::ragelExec ()\n{\n\t%% write exec;\n}\n\nvoid JancyHighlighter::ragelExecPreEvent (int &ragelState)\n{\n\tsetCurrentBlockState (BLOCK_STATE_NONE);\n\n\tint prevBlockState = previousBlockState ();\n\tswitch (prevBlockState)\n\t{\n\tcase BLOCK_STATE_COMMENT:\n\t\tragelState = jancy_lexer_en_comment;\n\t\tbreak;\n\n\tcase BLOCK_STATE_LIT_ML:\n\t\tragelState = jancy_lexer_en_lit_ml;\n\t\tbreak;\n\t}\n}\n\nvoid JancyHighlighter::ragelExecPostEvent (int ragelState)\n{\n\tswitch (ragelState)\n\t{\n\tcase jancy_lexer_en_comment:\n\t\tsetCurrentBlockState (BLOCK_STATE_COMMENT);\n\t\tbreak;\n\n\tcase jancy_lexer_en_lit_ml:\n\t\tsetCurrentBlockState (BLOCK_STATE_LIT_ML);\n\t\tbreak;\n\t}\n}\n\n\/\/..............................................................................\n","old_contents":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n%%{\n\nmachine jancy_lexer;\nwrite data;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n';\nlc_nl = '\\\\' '\\r'? nl;\nesc = '\\\\' [^\\n];\n\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* ([\"\\\\] | nl);\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* (['\\\\] | nl);\nraw_lit_dq = '\"' [^\"\\n]* ('\"' | nl);\nraw_lit_sq = \"'\" [^'\\n]* (\"'\" | nl);\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n(\n'import' |\n'namespace' |\n'extension' |\n'dynamiclib' |\n'using' |\n'friend' |\n'public' |\n'protected' |\n'alignment' |\n'setas' |\n\n'typedef' |\n'alias' |\n'static' |\n'threadlocal' |\n'stack' |\n'heap' |\n'abstract' |\n'virtual' |\n'override' |\n'mutable' |\n'disposable' |\n\n'signed' |\n'unsigned' |\n'bigendian' |\n'const' |\n'cmut' |\n'readonly' |\n'volatile' |\n'safe' |\n'unsafe' |\n'weak' |\n'thin' |\n'errorcode' |\n'cdecl' |\n'stdcall' |\n'thiscall' |\n'jnccall' |\n'array' |\n'function' |\n'property' |\n'bindable' |\n'autoget' |\n'indexed' |\n'multicast' |\n'event' |\n'reactor' |\n\n'auto' |\n'anydata' |\n'void' |\n'variant' |\n'bool' |\n'int' |\n'intptr' |\n'char' |\n'short' |\n'long' |\n'float' |\n'double' |\n'enum' |\n'struct' |\n'union' |\n'class' |\n'opaque' |\n'exposed' |\n'bitflag' |\n\n'get' |\n'set' |\n'preconstruct' |\n'construct' |\n'destruct' |\n'operator' |\n'postfix' |\n\n'if' |\n'else' |\n'for' |\n'while' |\n'do' |\n'break' |\n'break' [1-9]? |\n'continue' [1-9]? |\n'return' |\n'switch' |\n'reswitch' |\n'case' |\n'default' |\n'once' |\n'onevent' |\n'try' |\n'throw' |\n'catch' |\n'finally' |\n'nestedscope' |\n'assert' |\n\n'basetype' [1-9]? |\n'this' |\n'true' |\n'false' |\n'null' |\n\n'new' |\n'delete' |\n'sizeof' |\n'countof' |\n'offsetof' |\n'typeof' |\n'bindingof' |\n'dynamic'\n\n) { colorize (ts, te, Qt::blue); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\nid ;\n\n(\nlit_sq |\nlit_dq |\n[rR] raw_lit_sq |\n[rR] raw_lit_dq |\ndec+ |\n'0' oct+ |\n'0' [xX] hex+ |\n'0' [oO] oct+ |\n'0' [bB] bin+ |\n'0' [nNdD] dec+ |\n'0' [xXoObBnNdD] raw_lit_dq |\ndec+ (('.' dec*) | ([eE] [+\\-]? dec+)) |\n[$fF] lit_dq\n)\t\t\t\t\t{ colorize (ts, te, Qt::darkRed); };\n\n('0' [xXoObBnNdD])? '\"\"\"'\n\t\t\t\t\t{ colorize (ts, te, Qt::darkRed); fgoto lit_ml; };\n\n'\/\/' any* { colorize (ts, te, Qt::darkGray); };\n'\/*' { colorize (ts, te, Qt::darkGray); fgoto comment; };\n\nws | nl ;\nany ;\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# comment machine\n#\n\ncomment := |*\n\n'*\/' { colorize (ts, te, Qt::darkGray); fgoto main; };\nany { colorize (ts, te, Qt::darkGray); };\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\n'\"\"\"' { colorize (ts, te, Qt::darkRed); fgoto main; };\nany { colorize (ts, te, Qt::darkRed); };\n\n*|;\n\n}%%\n\n\/\/..............................................................................\n\n#define BLOCK_STATE_NONE\t0\n#define BLOCK_STATE_COMMENT 1\n#define BLOCK_STATE_LIT_ML 2\n\nvoid JancyHighlighter::ragelInit ()\n{\n\t%% write init;\n}\n\nvoid JancyHighlighter::ragelExec ()\n{\n\t%% write exec;\n}\n\nvoid JancyHighlighter::ragelExecPreEvent (int &ragelState)\n{\n\tsetCurrentBlockState (BLOCK_STATE_NONE);\n\n\tint prevBlockState = previousBlockState ();\n\tswitch (prevBlockState)\n\t{\n\tcase BLOCK_STATE_COMMENT:\n\t\tragelState = jancy_lexer_en_comment;\n\t\tbreak;\n\n\tcase BLOCK_STATE_LIT_ML:\n\t\tragelState = jancy_lexer_en_lit_ml;\n\t\tbreak;\n\t}\n}\n\nvoid JancyHighlighter::ragelExecPostEvent (int ragelState)\n{\n\tswitch (ragelState)\n\t{\n\tcase jancy_lexer_en_comment:\n\t\tsetCurrentBlockState (BLOCK_STATE_COMMENT);\n\t\tbreak;\n\n\tcase jancy_lexer_en_lit_ml:\n\t\tsetCurrentBlockState (BLOCK_STATE_LIT_ML);\n\t\tbreak;\n\t}\n}\n\n\/\/..............................................................................\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"74de0c78ac24b87693cbeb1e924678770f1290c3","subject":"Don't split srt into individual lines. (fixes lines drawn out of order)","message":"Don't split srt into individual lines. (fixes lines drawn out of order)\n\ngit-svn-id: d8f21eb7283bfb39ebab2f8f9b4a259b233f9348@326 621663c8-3916-0410-8f58-edc14a8543d5\n","repos":"mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian,mrvacbob\/perian","old_file":"SSATagParsing.m.rl","new_file":"SSATagParsing.m.rl","new_contents":"\/\/\n\/\/ SSATagParsing.m\n\/\/ SSAView\n\/\/\n\/\/ Created by Alexander Strange on 1\/21\/07.\n\/\/ Copyright 2007 Perian Project. All rights reserved.\n\/\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nstatic void SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\nstatic void PruneEmptyStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\tsize_t style_count_new = 0;\n\tint i;\n\t\n\tfor (i = 0; i < re->style_count; i++) {\n\t\tif (re->styles[i]->range.length == 0) {\n\t\t\t[re->styles[i] release];\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea;\n\tint i, j, pcount; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tif (plaintext) {\n\t\tlinea = [NSArray arrayWithObject:str];\n\t\tpcount = 1;\n\t} else {\n\t\tlinea = [str componentsSeparatedByString:@\"\\n\"];\n\t\tpcount = [linea count];\n\t}\n\t\n\tfor (i = 0; i < pcount; i++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:i] componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = NULL;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!re->style) {\t\t\t\n\t\t\t\tre->style = ssa->defaultstyle;\n\t\t\t}\n\t\t\t\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipleruns=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\t[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin, *strbegin = p, *skipbegin = p, *intbegin, *pb = p, *posbegin, *strparambegin;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx, cur_posy;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\t\n\t\t\tunsigned long inum;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineRotationTag, sizeof(Fixed), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fn_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tif (ssa->version == S_SSA) inum = SSA2ASSAlignment(inum);\n\t\t\t\t\t\n\t\t\t\t\tswitch (inum) \n\t\t\t\t\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\t\t\t\t\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\t\t\t\t\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\t\t\t\t\n\t\t\t\t\tswitch (inum)\n\t\t\t\t\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\t\t\t\t\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\t\t\t\t\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\t\t\t\t\n\t\t\t\t\tFract alignment;\n\n\t\t\t\t\tif (cur_posx != -1) {\n\t\t\t\t\t\tswitch(cur_halign) {\n\t\t\t\t\t\t\tcase S_LeftAlign:\n\t\t\t\t\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase S_CenterAlign: default:\n\t\t\t\t\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase S_RightAlign: \n\t\t\t\t\t\t\t\talignment = FloatToFract(1.);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t\t\n\t\t\t\t\tFract alignment = FloatToFract(0);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\t[output appendString:@\"\\n\"];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\t[re increasestyles];\n\t\t\t\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n\t\t\t\t\tre->styles[re->style_count-1]->outline = cur_outline;\n\t\t\t\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\n\t\t\t\t\tre->styles[re->style_count-1]->astyle = cur_style;\n\t\t\t\t\tre->styles[re->style_count-1]->range = cur_range;\n\t\t\t\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\n\t\t\t\t\tre->styles[re->style_count-1]->color = cur_color;\n\t\t\t\t\tATSUCreateAndCopyStyle(cur_style,&cur_style);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[SSARenderEntity alloc] init];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipleruns = NO;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (flag == '0' || flag == '1') flag = fl - '0';})? > {flag = 1;};\n\t\t\t\tnum_ = digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = digit* > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = \"&H\" xdigit* > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" :> flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fad\" [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > fn_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"1\"? \"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" cmd_specific ;\n\t\t\t\t\n\t\t\t\ttag = \"{\" ((cmd*) | ([^\\\\}]*)) \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nn];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | \n\t\t\t\t\t\t (tag > enter_tag % exit_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text :> special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (re->text[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\n\t\t\tPruneEmptyStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\t\n\treturn rentities;\n}","old_contents":"\/\/\n\/\/ SSATagParsing.m\n\/\/ SSAView\n\/\/\n\/\/ Created by Alexander Strange on 1\/21\/07.\n\/\/ Copyright 2007 Perian Project. All rights reserved.\n\/\/\n\n#import \"SSATagParsing.h\"\n#import \"Categories.h\"\n\n@implementation SSAStyleSpan\n-(void)dealloc\n{\n\tATSUDisposeStyle(astyle);\n\t[super dealloc];\n}\n@end\n\n@implementation SSARenderEntity\n-(void)dealloc\n{\n\tint i;\n\tfor (i=0; i < style_count; i++) [styles[i] release];\n\tif (disposelayout) ATSUDisposeTextLayout(layout);\n\tfree(text);\n\tfree(styles);\n\t[nstext release];\n\t[super dealloc];\n}\n\n-(void)increasestyles\n{\n\tstyle_count++;\n\tstyles = realloc(styles, sizeof(SSAStyleSpan*[style_count]));\n}\n@end\n\n%% machine SSAtag;\n%% write data;\n\nstatic void SetATSUStyleFlag(ATSUStyle style, ATSUAttributeTag t, Boolean v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {sizeof(v)};\n\tATSUAttributeValuePtr vals[] = {&v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSUStyleOther(ATSUStyle style, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetAttributes(style,1,tags,sizes,vals);\n}\n\nstatic void SetATSULayoutOther(ATSUTextLayout l, ATSUAttributeTag t, ByteCount s, ATSUAttributeValuePtr v)\n{\n\tATSUAttributeTag tags[] = {t};\n\tByteCount\t\t sizes[] = {s};\n\tATSUAttributeValuePtr vals[] = {v};\n\t\n\tATSUSetLayoutControls(l,1,tags,sizes,vals);\n}\n\nstatic ATSURGBAlphaColor ParseColorTag(unsigned long c, float a)\n{\n\tunsigned char r,g,b;\n\tr = c & 0xff;\n\tg = (c >> 8) & 0xff;\n\tb = (c >> 16) & 0xff;\n\t\n\treturn (ATSURGBAlphaColor){r\/255.,g\/255.,b\/255.,a};\n}\n\nstatic void PruneEmptyStyleSpans(SSARenderEntity *re)\n{\n\tSSAStyleSpan *styles_new[re->style_count];\n\tsize_t style_count_new = 0;\n\tint i;\n\t\n\tfor (i = 0; i < re->style_count; i++) {\n\t\tif (re->styles[i]->range.length == 0) {\n\t\t\t[re->styles[i] release];\n\t\t} else {\n\t\t\tstyles_new[style_count_new++] = re->styles[i];\n\t\t}\n\t}\n\t\n\tif (style_count_new != re->style_count) {\n\t\tre->styles = realloc(re->styles, sizeof(SSAStyleSpan*) * style_count_new); \n\t\tmemcpy(re->styles, styles_new, sizeof(SSAStyleSpan*) * style_count_new);\n\t\t\n\t\tre->style_count = style_count_new;\n\t}\n}\n\nNSArray *ParseSubPacket(NSString *str, SSADocument *ssa, Boolean plaintext)\n{\n\tNSArray *linea = [str componentsSeparatedByString:@\"\\n\"];\n\tint i, j, pcount = [linea count]; unsigned len;\n\tNSMutableArray *rentities = [NSMutableArray array];\n\t\n\tfor (i = 0; i < pcount; i++) {\n\t\tSSARenderEntity *re = [[[SSARenderEntity alloc] init] autorelease];\n\t\tBOOL ldirty = NO;\n\t\t\n\t\tif (plaintext) {\n\t\t\tre->style = ssa->defaultstyle;\n\t\t\tre->layout = re->style->layout;\n\t\t\tre->layer = 0;\n\t\t\tre->marginl = re->style->marginl;\n\t\t\tre->marginr = re->style->marginl;\n\t\t\tre->marginv = re->style->marginl;\n\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\tre->halign = 1;\n\t\t\tre->valign = 0;\n\t\t\tre->nstext = [linea objectAtIndex:i];\n\t\t\tre->styles = NULL;\n\t\t\tre->disposelayout = NO;\n\t\t} else {\n\t\t\tNSArray *ar = [[linea objectAtIndex:i] componentsSeparatedByString:@\",\" count:9];\n\n\t\t\tif ([ar count] < 9) continue;\n\t\t\t\n\t\t\tre->layer = [[ar objectAtIndex:1] intValue];\n\t\t\tNSString *sn = [ar objectAtIndex:2];\n\t\t\t\n\t\t\tre->style = NULL;\n\t\t\t\n\t\t\tfor (j=0; j < ssa->stylecount; j++) {\n\t\t\t\tif ([sn isEqualToString:ssa->styles[j].name]) {\n\t\t\t\t\tre->style = &ssa->styles[j]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!re->style) {\t\t\t\n\t\t\t\tre->style = ssa->defaultstyle;\n\t\t\t}\n\t\t\t\n\t\t\tre->marginl = [[ar objectAtIndex:5] intValue];\n\t\t\tre->marginr = [[ar objectAtIndex:6] intValue];\n\t\t\tre->marginv = [[ar objectAtIndex:7] intValue];\n\t\t\t\n\t\t\tif (re->marginl == 0) re->marginl = re->style->marginl; else ldirty = TRUE;\n\t\t\tif (re->marginr == 0) re->marginr = re->style->marginr; else ldirty = TRUE;\n\t\t\tif (re->marginv == 0) re->marginv = re->style->marginv; else ldirty = TRUE;\n\t\t\t\n\t\t\tif (ldirty) {\n\t\t\t\tATSUTextMeasurement width;\n\t\t\t\tATSUAttributeTag tag[] = {kATSULineWidthTag};\n\t\t\t\tByteCount\t\t size[] = {sizeof(ATSUTextMeasurement)};\n\t\t\t\tATSUAttributeValuePtr val[] = {&width};\n\t\t\t\t\n\t\t\t\tre->usablewidth = ssa->resX - re->marginl - re->marginr; \n\t\t\t\tATSUCreateAndCopyTextLayout(re->style->layout,&re->layout);\n\t\t\t\twidth = IntToFixed(re->usablewidth);\n\t\t\t\t\n\t\t\t\tATSUSetLayoutControls(re->layout,1,tag,size,val);\n\t\t\t\tre->disposelayout = YES;\n\t\t\t} else {\n\t\t\t\tre->usablewidth = re->style->usablewidth;\n\t\t\t\tre->layout = re->style->layout;\n\t\t\t\tre->disposelayout = NO;\n\t\t\t}\n\t\t\t\n\t\t\tre->nstext = [ar objectAtIndex:8];\n\t\t}\n\t\tlen = [re->nstext length];\n\t\tre->text = malloc(sizeof(unichar[len]));\n\t\t\n\t\t[re->nstext getCharacters:re->text];\n\t\tre->style_count = 0;\n\t\tre->posx = re->posy = -1;\n\t\tre->halign = re->style->halign;\n\t\tre->valign = re->style->valign;\n\t\tre->multipleruns=NO;\n\t\t\n#define end_re \\\n\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\\\n\t\tcur_range.location -= outputoffset;\\\n\t\tcur_range.length -= lengthreduce;\\\n\t\t[re increasestyles];\\\n\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\\\n\t\tre->styles[re->style_count-1]->outline = cur_outline;\\\n\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\\\n\t\tre->styles[re->style_count-1]->astyle = cur_style;\\\n\t\tre->styles[re->style_count-1]->range = cur_range;\\\n\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\\\n\t\tre->styles[re->style_count-1]->color = cur_color;\\\n\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\\\n\t\t[output appendString:parsetmp]; \\\n\t\tre->nstext = dtmp = output;\\\n\t\tre->text = malloc(sizeof(unichar[[re->nstext length]]));\\\n\t\t[re->nstext getCharacters:re->text];\\\n\t\t[re->nstext retain];\n\t\t\n\t\t{\n\t\t\tNSRange cur_range = {0,0};\n\t\t\tATSUStyle cur_style;\n\t\t\tATSUTextLayout cur_layout;\n\t\t\tNSMutableString *output = [NSMutableString string], *dtmp;\n\t\t\tunichar *p = re->text, *pe = &re->text[len], *numbegin, *strbegin = p, *skipbegin = p, *intbegin, *pb = p, *posbegin, *strparambegin;\n\t\t\tfloat num, cur_outline = re->style->outline, cur_shadow = re->style->shadow;\n\t\t\tNSString *parsetmp;\n\t\t\tint cs, cur_valign=re->valign, cur_halign=re->halign, cur_posx, cur_posy;\n\t\t\tssacolors cur_color = re->style->color;\n\t\t\t\n\t\t\tunsigned long inum;\n\t\t\tunsigned outputoffset=0, lengthreduce=0;\n\t\t\tBOOL flag, newLayout=FALSE, cur_be = FALSE;\n\t\t\tFixed fixv;\n\t\t\t\n\t\t\tATSUCreateAndCopyStyle(re->style->atsustyle,&cur_style);\n\t\t\t\n\t\t\t%%{\n\t\t\t\talphtype unsigned short;\n\t\t\t\t\n\t\t\t\taction bold {SetATSUStyleFlag(cur_style, kATSUQDBoldfaceTag, flag);}\n\t\t\t\t\n\t\t\t\taction italic {SetATSUStyleFlag(cur_style, kATSUQDItalicTag, flag);}\n\t\t\t\t\n\t\t\t\taction uline {SetATSUStyleFlag(cur_style, kATSUQDUnderlineTag, flag);}\n\t\t\t\t\n\t\t\t\taction strike {SetATSUStyleFlag(cur_style, kATSUStyleStrikeThroughTag, flag);}\n\t\t\t\t\n\t\t\t\taction bordersize {cur_outline = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction shadowsize {cur_shadow = num; re->multipleruns = YES;}\n\t\t\t\t\n\t\t\t\taction bluredge {cur_be = flag;}\n\t\t\t\t\n\t\t\t\taction frot {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineRotationTag, sizeof(Fixed), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fsize {\n\t\t\t\t\tfixv = FloatToFixed(num);\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUSizeTag, sizeof(fixv), &fixv);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction fn_begin {\n\t\t\t\t\tstrparambegin = p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\taction fontname {\n\t\t\t\t\tATSUFontID\tfont;\n\t\t\t\t\tfont = FMGetFontFromATSFontRef(ATSFontFindFromName((CFStringRef)[NSString stringWithCharacters:strparambegin length:p-strparambegin],kATSOptionFlagsDefault));\n\t\t\t\t\tSetATSUStyleOther(cur_style, kATSUFontTag, sizeof(ATSUFontID), &font);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction alignment {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tif (ssa->version == S_SSA) inum = SSA2ASSAlignment(inum);\n\t\t\t\t\t\n\t\t\t\t\tswitch (inum) \n\t\t\t\t\t{case 1: case 4: case 7: cur_halign = S_LeftAlign; break;\n\t\t\t\t\tcase 2: case 5: case 8: default: cur_halign = S_CenterAlign; break;\n\t\t\t\t\tcase 3: case 6: case 9: cur_halign = S_RightAlign;}\n\t\t\t\t\t\n\t\t\t\t\tswitch (inum)\n\t\t\t\t\t{case 1: case 2: case 3: default: cur_valign = S_BottomAlign; break; \n\t\t\t\t\tcase 4: case 5: case 6: cur_valign = S_MiddleAlign; break; \n\t\t\t\t\tcase 7: case 8: case 9: cur_valign = S_TopAlign;}\n\t\t\t\t\t\n\t\t\t\t\tFract alignment;\n\n\t\t\t\t\tif (cur_posx != -1) {\n\t\t\t\t\t\tswitch(cur_halign) {\n\t\t\t\t\t\t\tcase S_LeftAlign:\n\t\t\t\t\t\t\t\talignment = FloatToFract(0.);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase S_CenterAlign: default:\n\t\t\t\t\t\t\t\talignment = kATSUCenterAlignment; \n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase S_RightAlign: \n\t\t\t\t\t\t\t\talignment = FloatToFract(1.);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_begin {\n\t\t\t\t\tposbegin=p;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction pos_end {\n\t\t\t\t\tif (!newLayout) {\n\t\t\t\t\t\tnewLayout = TRUE;\n\t\t\t\t\t\tATSUCreateAndCopyTextLayout(re->layout,&cur_layout);\n\t\t\t\t\t}\n\t\t\t\t\tNSArray *coo = [[NSString stringWithCharacters:posbegin length:p-posbegin] componentsSeparatedByString:@\",\"];\n\t\t\t\t\tcur_posx = [[coo objectAtIndex:0] intValue];\n\t\t\t\t\tcur_posy = [[coo objectAtIndex:1] intValue];\n\t\t\t\t\t\n\t\t\t\t\tFract alignment = FloatToFract(0);\n\t\t\t\t\t\n\t\t\t\t\tSetATSULayoutOther(cur_layout, kATSULineFlushFactorTag, sizeof(Fract), &alignment);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction primarycolor {\n\t\t\t\t\tcur_color.primary = ParseColorTag(inum,cur_color.primary.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction outlinecolor {\n\t\t\t\t\tcur_color.outline = ParseColorTag(inum,cur_color.outline.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction shadowcolor {\n\t\t\t\t\tcur_color.shadow = ParseColorTag(inum,cur_color.shadow.alpha);\n\t\t\t\t\tre->multipleruns = YES;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction nl_handler {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:(p-2)-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\t[output appendString:@\"\\n\"];\n\t\t\t\t\t\n\t\t\t\t\tlengthreduce++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction enter_tag {\n\t\t\t\t\tparsetmp = [NSString stringWithCharacters:skipbegin length:p-skipbegin];\n\t\t\t\t\t[output appendString:parsetmp];\n\t\t\t\t\t\n\t\t\t\t\tcur_range = (NSRange){strbegin - pb, p - strbegin};\n\t\t\t\t\tcur_range.location -= outputoffset;\n\t\t\t\t\tcur_range.length -= lengthreduce;\n\t\t\t\t\t\n\t\t\t\t\toutputoffset += lengthreduce;\n\t\t\t\t\tlengthreduce = 0;\n\t\t\t\t\t\n\t\t\t\t\tskipbegin = p;\n\n\t\t\t\t\t[re increasestyles];\n\t\t\t\t\tre->styles[re->style_count-1] = [[SSAStyleSpan alloc] init];\n\t\t\t\t\tre->styles[re->style_count-1]->outline = cur_outline;\n\t\t\t\t\tre->styles[re->style_count-1]->shadow = cur_shadow;\n\t\t\t\t\tre->styles[re->style_count-1]->astyle = cur_style;\n\t\t\t\t\tre->styles[re->style_count-1]->range = cur_range;\n\t\t\t\t\tre->styles[re->style_count-1]->outlineblur = cur_be;\n\t\t\t\t\tre->styles[re->style_count-1]->color = cur_color;\n\t\t\t\t\tATSUCreateAndCopyStyle(cur_style,&cur_style);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction exit_tag {\n\t\t\t\t\toutputoffset += p - skipbegin;\n\t\t\t\t\tskipbegin = p;\n\t\t\t\t\tstrbegin = p;\n\n\t\t\t\t\tif (newLayout) {\n\t\t\t\t\t\tnewLayout = FALSE;\n\t\t\t\t\t\tend_re;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t\t\t\t\t\n\t\t\t\t\t\tSSARenderEntity *nre = [[SSARenderEntity alloc] init];\n\t\t\t\t\t\tnre->layer = re->layer;\n\t\t\t\t\t\tnre->style = re->style;\n\t\t\t\t\t\tnre->marginl = re->marginl; nre->marginr = re->marginr; nre->marginv = re->marginv; nre->usablewidth = re->usablewidth;\n\t\t\t\t\t\tnre->posx = cur_posx; nre->posy = cur_posy; nre->halign = cur_halign; nre->valign = cur_valign;\n\t\t\t\t\t\tnre->nstext = nil;\n\t\t\t\t\t\tnre->text = nil;\n\t\t\t\t\t\tnre->layout = cur_layout;\n\t\t\t\t\t\tnre->styles = malloc(0);\n\t\t\t\t\t\tnre->style_count = 0;\n\t\t\t\t\t\tnre->disposelayout = YES;\n\t\t\t\t\t\tnre->multipleruns = NO;\n\t\t\t\t\t\tre = nre;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taction color_end {\n\t\t\t\t\tNSString *hexn = [NSString stringWithCharacters:intbegin length:p-intbegin];\n\t\t\t\t\tinum = strtoul([hexn UTF8String], NULL, 16);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tflag = ([01] % {unichar fl = *(p-1); if (flag == '0' || flag == '1') flag = fl - '0';})? > {flag = 1;};\n\t\t\t\tnum_ = digit+ ('.' digit*)?;\n\t\t\t\tnum = num_ > {numbegin = p;} % {num = [[NSString stringWithCharacters:numbegin length:p-numbegin] doubleValue];};\n\t\t\t\t\n\t\t\t\tintnum = digit* > {intbegin = p;} % {inum = [[NSString stringWithCharacters:intbegin length:p-intbegin] intValue];};\n\t\t\t\t\n\t\t\t\tcolor = \"&H\" xdigit* > {intbegin = p;} % color_end \"&\";\n\n\t\t\t\tcmd_specific = ((\"pos(\" [^)]+ > pos_begin \")\" % pos_end)\n\t\t\t\t\t\t\t\t|\"bord\" num %bordersize\n\t\t\t\t\t\t\t\t|\"b\" :> flag %bold \n\t\t\t\t\t\t\t\t|\"be\" flag %bluredge\n\t\t\t\t\t\t\t\t|\"i\" flag %italic \n\t\t\t\t\t\t\t\t|\"u\" flag %uline\n\t\t\t\t\t\t\t\t|\"s\" flag %strike\n\t\t\t\t\t\t\t\t|\"fad\" [^\\\\}]*\n\t\t\t\t\t\t\t\t|\"fs\" num %fsize \n\t\t\t\t\t\t\t\t|(\"fr\" \"z\"? num %frot) \n\t\t\t\t\t\t\t\t|(\"fn\" [^\\\\}]* > fn_begin %fontname) \n\t\t\t\t\t\t\t\t|\"shad\" num %shadowsize\n\t\t\t\t\t\t\t\t|\"an\" intnum %alignment\n\t\t\t\t\t\t\t\t|\"1\"? \"c\" color %primarycolor\n\t\t\t\t\t\t\t\t|\"3c\" color %outlinecolor\n\t\t\t\t\t\t\t\t|\"4c\" color %shadowcolor\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\n\t\t\t\tcmd = \"\\\\\" cmd_specific ;\n\t\t\t\t\n\t\t\t\ttag = \"{\" ((cmd*) | ([^\\\\}]*)) \"}\";\n\t\t\t\t\n\t\t\t\tnl = \"\\\\\" [Nn];\n\t\t\t\t\n\t\t\t\tspecial = nl % nl_handler | \n\t\t\t\t\t\t (tag > enter_tag % exit_tag);\n\t\t\t\t\t\t\t\t\n\t\t\t\ttext = any*;\n\t\t\t\tmain := (text :> special?)*;\n\t\t\t}%%\n\t\t\t\t\n\t\t\t%%write init;\n\t\t\t%%write exec;\n\t\t\t%%write eof;\n\t\t\t\n\t\t\tif (re->text[len-1] == '}') skipbegin = p; \/\/ make up for how exit_tag isn't called if the } is the last char in the line\n\n\t\t\tend_re;\n\n\t\t\tPruneEmptyStyleSpans(re);\n\n\t\t\tfree(pb);\n\t\t\tif ([re->nstext length] != 0) [rentities addObject:re];\n\t\t}\n\t\t\n\t}\n\t\n\treturn rentities;\n}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"Ragel in Ruby Host"} {"commit":"b757ff0377883b6cfab18393714d7a2b513c94e8","subject":"* lexer.rl: use Regexp to match string.","message":"* lexer.rl: use Regexp to match string.\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = Regexp.union(*\"\\\\$()*+.<>?[]^{|}\".chars).freeze\n UNDERSCORE_STRING = '_'.freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && REGEXP_META_CHARACTERS.match(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n REGEXP_META_CHARACTERS = \"\\\\$()*+.<>?[]^{|}\".freeze\n UNDERSCORE_STRING = '_'.freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && REGEXP_META_CHARACTERS.include?(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? UNDERSCORE_STRING\n diagnostic :error, :trailing_in_number, { :character => UNDERSCORE_STRING },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"77b40d2e817af84c0666b4ea2eb54fcf93066368","subject":"Use a separate machine for closing tags.","message":"Use a separate machine for closing tags.\n\nThis makes it easier to advance column numbers for whitespace as well as\ncaptuing and emitting tokens for the closing tag.\n","repos":"YorickPeterse\/oga,jeffreybaird\/oga,ttasanen\/oga,jeffreybaird\/oga,dfockler\/oga,jeffreybaird\/oga,dfockler\/oga,ttasanen\/oga,altmetric\/oga,ttasanen\/oga,altmetric\/oga,YorickPeterse\/oga,dfockler\/oga,YorickPeterse\/oga,altmetric\/oga,dfockler\/oga,YorickPeterse\/oga,altmetric\/oga,ttasanen\/oga,dfockler\/oga,ttasanen\/oga,jeffreybaird\/oga,YorickPeterse\/oga,altmetric\/oga,jeffreybaird\/oga","old_file":"lib\/oga\/lexer.rl","new_file":"lib\/oga\/lexer.rl","new_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n private\n\n def advance_line\n @line += 1\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length) if value\n\n @tokens << token\n end\n\n def emit_text_buffer\n return if @text_buffer.empty?\n\n add_token(:T_TEXT, @text_buffer)\n\n @text_buffer = ''\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n action emit_newline {\n t(:T_TEXT)\n advance_line\n }\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n fcall string_dquote;\n }\n\n action string_squote {\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n t(:T_CDATA_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the end\n # tag.\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences\n # would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n comment := |*\n comment_end => {\n emit_text_buffer\n t(:T_COMMENT_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and namespace\n # (if any). Remaining work is delegated to a dedicated machine.\n action open_element {\n add_token(:T_ELEM_OPEN, nil)\n advance_column\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(@ts + 1)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n\n # Advance the column for the colon (:) that separates the namespace\n # and element name.\n advance_column\n end\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element;\n }\n\n element_name = [a-zA-Z0-9\\-_:]+;\n element_start = '<' element_name;\n\n element_text := |*\n ^'<' => buffer_text;\n\n '<' => {\n emit_text_buffer\n fhold;\n fret;\n };\n *|;\n\n element_closing_tag := |*\n whitespace => { advance_column };\n\n element_name => {\n emit_text_buffer\n add_token(:T_ELEM_CLOSE, nil)\n\n # Advance the column for the <\/\n advance_column(2)\n\n # Advance the column for the closing name.\n advance_column(@te - p)\n fret;\n };\n\n '>' => { fret; };\n *|;\n\n element := |*\n whitespace => { advance_column };\n\n element_start => open_element;\n\n # Consume the text inside the element.\n '>' => {\n advance_column\n fcall element_text;\n };\n\n # Attributes and their values.\n element_name\n %{\n t(:T_ATTR, @ts, p)\n advance_column\n }\n '=' (dquote @string_dquote | squote @string_squote);\n\n # Non self-closing elements.\n '<\/' => {\n fcall element_closing_tag;\n fret;\n };\n\n # self-closing \/ void elements.\n '\/>' => {\n advance_column\n add_token(:T_ELEM_CLOSE, nil)\n fret;\n };\n *|;\n\n main := |*\n newline => emit_newline;\n\n doctype_start => {\n t(:T_DOCTYPE_START)\n fcall doctype;\n };\n\n cdata_start => {\n t(:T_CDATA_START)\n fcall cdata;\n };\n\n comment_start => {\n t(:T_COMMENT_START)\n fcall comment;\n };\n\n element_start => open_element;\n *|;\n }%%\n end # Lexer\nend # Oga\n","old_contents":"%%machine lexer; # %\n\nmodule Oga\n ##\n #\n class Lexer\n %% write data; # %\n\n # Lazy way of forwarding instance method calls used internally by Ragel to\n # their corresponding class methods.\n private_methods.grep(\/^_lexer_\/).each do |name|\n define_method(name) do\n return self.class.send(name)\n end\n\n private(name)\n end\n\n def initialize\n reset\n end\n\n def reset\n @line = 1\n @column = 1\n @data = nil\n @ts = nil\n @te = nil\n @tokens = []\n @stack = []\n @top = 0\n\n @string_buffer = ''\n @text_buffer = ''\n end\n\n def lex(data)\n @data = data\n lexer_start = self.class.lexer_start\n eof = data.length\n\n %% write init;\n %% write exec;\n\n tokens = @tokens\n\n reset\n\n return tokens\n end\n\n private\n\n def advance_line\n @line += 1\n @column = 1\n end\n\n def advance_column(length = 1)\n @column += length\n end\n\n def t(type, start = @ts, stop = @te)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n def text(start = @ts, stop = @te)\n return @data[start...stop]\n end\n\n def add_token(type, value)\n token = [type, value, @line, @column]\n\n advance_column(value.length) if value\n\n @tokens << token\n end\n\n def emit_text_buffer\n return if @text_buffer.empty?\n\n add_token(:T_TEXT, @text_buffer)\n\n @text_buffer = ''\n end\n\n def emit_string_buffer\n add_token(:T_STRING, @string_buffer)\n advance_column\n\n @string_buffer = ''\n end\n\n %%{\n # Use instance variables for `ts` and friends.\n access @;\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n\n action emit_newline {\n t(:T_TEXT)\n advance_line\n }\n\n # String processing\n #\n # These actions\/definitions can be used to process single and\/or double\n # quoted strings (e.g. for tag attribute values).\n #\n # The string_dquote and string_squote machines should not be used\n # directly, instead the corresponding actions should be used.\n #\n dquote = '\"';\n squote = \"'\";\n\n action buffer_text {\n @text_buffer << text\n }\n\n action buffer_string {\n @string_buffer << text\n }\n\n action string_dquote {\n fcall string_dquote;\n }\n\n action string_squote {\n fcall string_squote;\n }\n\n string_dquote := |*\n ^dquote => buffer_string;\n dquote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n string_squote := |*\n ^squote => buffer_string;\n squote => {\n emit_string_buffer\n advance_column\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { t(:T_DOCTYPE_TYPE) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => string_dquote;\n squote => string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace => { advance_column };\n\n '>' => {\n t(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n cdata := |*\n cdata_end => {\n emit_text_buffer\n t(:T_CDATA_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the end\n # tag.\n #\n # Unlike the W3 specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences\n # would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n comment := |*\n comment_end => {\n emit_text_buffer\n t(:T_COMMENT_END)\n fret;\n };\n\n any => buffer_text;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and namespace\n # (if any). Remaining work is delegated to a dedicated machine.\n action open_element {\n add_token(:T_ELEM_OPEN, nil)\n advance_column\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(@ts + 1)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n\n # Advance the column for the colon (:) that separates the namespace\n # and element name.\n advance_column\n end\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element;\n }\n\n element_name = [a-zA-Z0-9\\-_:]+;\n element_start = '<' element_name;\n\n element_text := |*\n ^'<' => buffer_text;\n\n '<' => {\n emit_text_buffer\n fhold;\n fret;\n };\n *|;\n\n element := |*\n whitespace => { advance_column };\n\n element_start => open_element;\n\n # Consume the text inside the element.\n '>' => {\n advance_column\n fcall element_text;\n };\n\n # Attributes and their values.\n element_name\n %{\n t(:T_ATTR, @ts, p)\n advance_column\n }\n '=' (dquote @string_dquote | squote @string_squote);\n\n # Non self-closing elements.\n '<\/' element_name {\n emit_text_buffer\n add_token(:T_ELEM_CLOSE, nil)\n\n # Advance the column for the <\/\n advance_column(2)\n\n # Advance the column for the closing name.\n advance_column(@te - p)\n fret;\n };\n\n # self-closing \/ void elements.\n '\/>' => {\n advance_column\n add_token(:T_ELEM_CLOSE, nil)\n fret;\n };\n *|;\n\n main := |*\n newline => emit_newline;\n\n doctype_start => {\n t(:T_DOCTYPE_START)\n fcall doctype;\n };\n\n cdata_start => {\n t(:T_CDATA_START)\n fcall cdata;\n };\n\n comment_start => {\n t(:T_COMMENT_START)\n fcall comment;\n };\n\n element_start => open_element;\n *|;\n }%%\n end # Lexer\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"e73030569bea860fcc9e12e4c2278ac001a8170b","subject":"added missing include ","message":"added missing include \n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/lexer.h.rl","new_file":"src\/hext\/lexer.h.rl","new_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/lexer-util.h\"\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\nclass lexer\n{\npublic:\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg);\n };\n\n lexer(const char * begin, const char * end);\n\n std::vector lex();\n\n void throw_error() const;\n\nprivate:\n const char * p_begin;\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","old_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/lexer-util.h\"\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\nclass lexer\n{\npublic:\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg);\n };\n\n lexer(const char * begin, const char * end);\n\n std::vector lex();\n\n void throw_error() const;\n\nprivate:\n const char * p_begin;\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"96234e4157085d57be3d24e0b3830cb6af9d2157","subject":"Simplify definition of tokenizer.","message":"Simplify definition of tokenizer.\n","repos":"twtiger\/gosecco","old_file":"parser\/tokenizer.rl","new_file":"parser\/tokenizer.rl","new_contents":"package parser\n\nimport \"fmt\"\n\n%%{\n machine gosecco_tokenizer;\n\n BIN_DIGIT = [01] ;\n OCT_DIGIT = [0-7] ;\n\n INTBIN = \"0b\"i BIN_DIGIT+ ;\n INTHEX = \"0x\"i xdigit+ ;\n INTOCT = \"0\" OCT_DIGIT+ ;\n INTDEC = ( \"0\" | ( [1-9] digit* ) ) ;\n\n SPACES = [ \\t] ;\n\n IDENT_CHAR = \"_\" | alnum ;\n\n ARG = \"arg\" [HL]? [0-5] ;\n\n IDENT = [_a-zA-Z] IDENT_CHAR* ;\n\n main := |*\n ARG => {f(ARG, data[ts:te])};\n\n \"in\"i => {f(IN, nil)};\n \"notIn\"i => {f(NOTIN, nil)};\n\n \"true\"i => {f(TRUE, nil)};\n \"false\"i => {f(FALSE, nil)};\n\n IDENT => {f(IDENT, data[ts:te])};\n\n INTHEX => {f(INT, data[ts:te])};\n INTOCT => {f(INT, data[ts:te])};\n INTBIN => {f(INT, data[ts:te])};\n INTDEC => {f(INT, data[ts:te])};\n\n \"+\" => {f(ADD, nil)};\n \"-\" => {f(SUB, nil)};\n \"*\" => {f(MUL, nil)};\n \"\/\" => {f(DIV, nil)};\n \"%\" => {f(MOD, nil)};\n\n \"&&\" => {f(LAND, nil)};\n \"||\" => {f(LOR, nil)};\n\n \"&\" => {f(AND, nil)};\n \"|\" => {f(OR, nil)};\n \"^\" => {f(XOR, nil)};\n \"<<\" => {f(LSH, nil)};\n \">>\" => {f(RSH, nil)};\n \"~\" => {f(INV, nil)};\n\n \"==\" => {f(EQL, nil)};\n \"<=\" => {f(LTE, nil)};\n \">=\" => {f(GTE, nil)};\n \"<\" => {f(LT, nil)};\n \">\" => {f(GT, nil)};\n \"!=\" => {f(NEQ, nil)};\n \"!\" => {f(NOT, nil)};\n\n \"(\" => {f(LPAREN, nil)};\n \"[\" => {f(LBRACK, nil)};\n \")\" => {f(RPAREN, nil)};\n \"]\" => {f(RBRACK, nil)};\n\n \",\" => {f(COMMA, nil)};\n\n SPACES+;\n\n any => {return tokenError(ts, te, data)};\n *|;\n}%%\n\n%% write data;\n\nfunc tokenizeRaw(data []byte, f func(token, []byte), tokenError func(int, int, []byte) error) error {\n var cs, act int\n p, pe := 0, len(data)\n ts, te := 0, 0\n eof := pe\n\n %% write init;\n %% write exec;\n\n return nil\n}\n","old_contents":"package parser\n\nimport \"fmt\"\n\n%%{\n machine gosecco_tokenizer;\n\n BIN_DIGIT = [0-1] ;\n OCT_DIGIT = [0-7] ;\n\n INTBIN = \"0b\"i BIN_DIGIT+ ;\n INTHEX = \"0x\"i xdigit+ ;\n INTOCT = \"0\" OCT_DIGIT+ ;\n INTDEC = ( \"0\" | ( [1-9] digit* ) ) ;\n\n SPACES = [ \\t] ;\n\n IDENT_CHAR = \"_\" | alnum ;\n\n ARG = \"arg\" [HL]? [0-5] ;\n\n IDENT = [_a-zA-Z] IDENT_CHAR* ;\n\n main := |*\n ARG => {f(ARG, data[ts:te])};\n\n \"in\"i => {f(IN, nil)};\n \"notIn\"i => {f(NOTIN, nil)};\n\n \"true\"i => {f(TRUE, nil)};\n \"false\"i => {f(FALSE, nil)};\n\n IDENT => {f(IDENT, data[ts:te])};\n\n INTHEX => {f(INT, data[ts:te])};\n INTOCT => {f(INT, data[ts:te])};\n INTBIN => {f(INT, data[ts:te])};\n INTDEC => {f(INT, data[ts:te])};\n\n \"+\" => {f(ADD, nil)};\n \"-\" => {f(SUB, nil)};\n \"*\" => {f(MUL, nil)};\n \"\/\" => {f(DIV, nil)};\n \"%\" => {f(MOD, nil)};\n\n \"&&\" => {f(LAND, nil)};\n \"||\" => {f(LOR, nil)};\n\n \"&\" => {f(AND, nil)};\n \"|\" => {f(OR, nil)};\n \"^\" => {f(XOR, nil)};\n \"<<\" => {f(LSH, nil)};\n \">>\" => {f(RSH, nil)};\n \"~\" => {f(INV, nil)};\n\n \"==\" => {f(EQL, nil)};\n \"<=\" => {f(LTE, nil)};\n \">=\" => {f(GTE, nil)};\n \"<\" => {f(LT, nil)};\n \">\" => {f(GT, nil)};\n \"!=\" => {f(NEQ, nil)};\n \"!\" => {f(NOT, nil)};\n\n \"(\" => {f(LPAREN, nil)};\n \"[\" => {f(LBRACK, nil)};\n \")\" => {f(RPAREN, nil)};\n \"]\" => {f(RBRACK, nil)};\n\n \",\" => {f(COMMA, nil)};\n\n SPACES+;\n\n any => {return tokenError(ts, te, data)};\n *|;\n}%%\n\n%% write data;\n\nfunc tokenizeRaw(data []byte, f func(token, []byte), tokenError func(int, int, []byte) error) error {\n var cs, act int\n p, pe := 0, len(data)\n ts, te := 0, 0\n eof := pe\n\n %% write init;\n %% write exec;\n\n return nil\n}\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Ragel in Ruby Host"} {"commit":"aafc93a0b2acc4620d7678d36c5763415e89264b","subject":"* lexer.rl: reduce Stirng.length method call on #advance","message":"* lexer.rl: reduce Stirng.length method call on #advance\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @source.respond_to?(:encode)) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_key_spans = self.class.send :_lex_key_spans\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n _lex_eof_trans = self.class.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == self.class.lex_en_expr_value ||\n @cs == self.class.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if lookahead.respond_to?(:encode)\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && \"\\\\$()*+.<>?[]^{|}\".include?(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(\"\\\\\\n\", ''), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, '')\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, '')\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? '_'\n diagnostic :error, :trailing_in_number, { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @source.respond_to?(:encode)) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n _lex_trans_keys = self.class.send :_lex_trans_keys\n _lex_key_spans = self.class.send :_lex_key_spans\n _lex_index_offsets = self.class.send :_lex_index_offsets\n _lex_indicies = self.class.send :_lex_indicies\n _lex_trans_targs = self.class.send :_lex_trans_targs\n _lex_trans_actions = self.class.send :_lex_trans_actions\n _lex_to_state_actions = self.class.send :_lex_to_state_actions\n _lex_from_state_actions = self.class.send :_lex_from_state_actions\n _lex_eof_trans = self.class.send :_lex_eof_trans\n\n p, pe, eof = @p, @source.length + 1, @source.length + 1\n\n @command_state = (@cs == self.class.lex_en_expr_value ||\n @cs == self.class.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == self.class.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if lookahead.respond_to?(:encode)\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && \"\\\\$()*+.<>?[]^{|}\".include?(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(\"\\\\\\n\", ''), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, '')\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, '')\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? '_'\n diagnostic :error, :trailing_in_number, { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"a8007b96034a1e6f95843226a9769e95dc30f5bc","subject":"small bugfix in mfilescanner.rl","message":"small bugfix in mfilescanner.rl\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner.rl","new_file":"src\/mfilescanner.rl","new_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ([ \\t]*\n# @{ buffer_.append(*p); }\n )\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n# ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else if(returnlist_.size() == 1)\n fout_ << \"ret::substitutestart::\" << returnlist_[0] << \"::retsubstituteend \";\n else\n {\n fout_ << \"rets::substitutestart::\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n fout_ << returnlist_[i] << \"::\";\n }\n fout_ << \"retssubstituteend \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n fout_ << typen << \" \" << paramlist_[i];\n }\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const DocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n \/\/ block is empty?\n if(block.empty())\n {\n \/\/ then look for alternative documentation block form global\n \/\/ configuration file ...\n list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << s << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const DocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : DocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen)\n{\n typedef DocuList :: iterator DLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = cscan_.param_list_.find(paramname);\n if(it != cscan_.param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = cscan_.return_list_.find(paramname);\n if(it != cscan_.return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n typen=\"matlabtypesubstitute\";\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0;\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","old_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT)\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( IDENT > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n IDENT\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ([ \\t]*\n# @{ buffer_.append(*p); }\n )\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n# ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else if(returnlist_.size() == 1)\n fout_ << \"ret::substitutestart::\" << returnlist_[0] << \"::retsubstituteend \";\n else\n {\n fout_ << \"rets::substitutestart::\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n fout_ << returnlist_[i] << \"::\";\n }\n fout_ << \"retssubstituteend \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n fout_ << typen << \" \" << paramlist_[i];\n }\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const DocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << (*lit).first << separator << \" \";\n const DocuBlock & block = (*lit).second;\n \/\/ block is empty?\n if(block.empty())\n {\n \/\/ then look for alternative documentation block form global\n \/\/ configuration file ...\n list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty())\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << s << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const DocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : DocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams && docuheader_.empty())\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"Warning: No definition for function \" << cfuncname_ << \" found!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen)\n{\n typedef DocuList :: iterator DLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = cscan_.param_list_.find(paramname);\n if(it != cscan_.param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = cscan_.return_list_.find(paramname);\n if(it != cscan_.return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n typen=\"matlabtypesubstitute\";\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0;\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n typenstart=line.find_first_not_of( \" \\t\", typenstart );\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ line.replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n line.erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"053132409cf623775e83be09098026f012ba1c49","subject":"Cosmetic cleanup + fixed bug in all-alpha codepoints","message":"Cosmetic cleanup + fixed bug in all-alpha codepoints\n\n\ngit-svn-id: 26a6d2a58b162bc133329b2f36847a121ee54040@975 06fd6eb0-0002-0410-a719-e5602cce40bc\n","repos":"jkraemer\/ferret,dbalmain\/ferret,jkraemer\/ferret,dimelo\/ferret-dimelo,dbalmain\/ferret,dustin\/ferret,jkraemer\/ferret,Bira\/ferret,dbalmain\/ferret,dustin\/ferret,jkraemer\/ferret,dustin\/ferret,dimelo\/ferret-dimelo,dbalmain\/ferret,Bira\/ferret,Bira\/ferret,Bira\/ferret,jkraemer\/ferret,dimelo\/ferret-dimelo,dustin\/ferret,dimelo\/ferret-dimelo,dbalmain\/ferret","old_file":"c\/src\/scanner_mb.rl","new_file":"c\/src\/scanner_mb.rl","new_contents":"\/* scanner.rl -*-C-*- *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"global.h\"\n#include \"internal.h\"\n\nstatic char *position_in_mb( const unsigned long *orig_wc,\n const char *orig_mb,\n const unsigned long *curr_wc )\n{\n char *mb = (char *)orig_mb;\n unsigned long *wc = (char *)orig_wc;\n\n while (wc < curr_wc)\n {\n char buf[MB_LEN_MAX];\n mb += wctomb(buf, *wc);\n ++wc;\n }\n\n return mb;\n}\n\n#define RET do { \\\n *start = position_in_mb(buf, in, ts); \\\n *end = position_in_mb(buf, in, te); \\\n size_t __len = *end - *start - skip - trunc; \\\n *len = __len; \\\n if (__len > out_size) \\\n __len = out_size; \\\n memcpy(out, *start + skip, __len); \\\n out[__len] = 0; \\\n return; \\\n} while(0)\n\n#define STRIP(c) do { \\\n unsigned long *__p = ts; \\\n unsigned long *__o = out; \\\n unsigned long *__max = __p + out_size; \\\n for (; __p <= te && __p < __max; ++__p) { \\\n if (*__p != c) \\\n *__o++ = *__p; \\\n } \\\n *__o = 0; \\\n \\\n *start = position_in_mb(buf, in, ts); \\\n *end = position_in_mb(buf, in, te); \\\n *len = (char *)__o - (char *)out; \\\n return; \\\n} while(0)\n\n%%{\n machine StdTokMb;\n alphtype unsigned long;\n include \"src\/wchar.rl\";\n\n wdigit = '0' .. '9';\n\n u0 =\n 0x041 .. 0x05a | 0x061 .. 0x07a | 0x0aa | 0x0b5 | 0x0ba |\n 0x0c0 .. 0x0d6 | 0x0d8 .. 0x0f6 | 0x0f8 .. 0x0ff;\n u2 =\n 0x200 .. 0x220 | 0x222 .. 0x233 | 0x250 .. 0x2ad | 0x2b0 .. 0x2b8 |\n 0x2bb .. 0x2c1 | 0x2d0 .. 0x2d1 | 0x2e0 .. 0x2e4 | 0x2ee;\n u3 =\n 0x345 | 0x37a | 0x386 | 0x388 .. 0x38a | 0x38c | 0x38e .. 0x3a1 |\n 0x3a3 .. 0x3ce | 0x3d0 .. 0x3f5;\n u4 =\n 0x400 .. 0x481 | 0x48a .. 0x4ce | 0x4d0 .. 0x4f5 | 0x4f8 .. 0x4f9;\n u5 =\n 0x500 .. 0x50f | 0x531 .. 0x556 | 0x559 | 0x561 .. 0x587 |\n 0x5d0 .. 0x5ea | 0x5f0 .. 0x5f2;\n u6 =\n 0x621 .. 0x63a | 0x640 .. 0x64a | 0x660 .. 0x669 | 0x66e .. 0x66f |\n 0x671 .. 0x6d3 | 0x6d5 | 0x6e5 .. 0x6e6 | 0x6f0 .. 0x6fc;\n u7 =\n 0x710 | 0x712 .. 0x72c | 0x780 .. 0x7a5 | 0x7b1;\n u9 =\n 0x905 .. 0x939 | 0x93d | 0x950 | 0x958 .. 0x961 | 0x966 .. 0x96f |\n 0x985 .. 0x98c | 0x98f .. 0x990 | 0x993 .. 0x9a8 | 0x9aa .. 0x9b0 |\n 0x9b2 | 0x9b6 .. 0x9b9 | 0x9dc .. 0x9dd | 0x9df .. 0x9e1 |\n 0x9e6 .. 0x9f1;\n ua =\n 0xa05 .. 0xa0a | 0xa0f .. 0xa10 | 0xa13 .. 0xa28 | 0xa2a .. 0xa30 |\n 0xa32 .. 0xa33 | 0xa35 .. 0xa36 | 0xa38 .. 0xa39 | 0xa59 .. 0xa5c |\n 0xa5e | 0xa66 .. 0xa6f | 0xa72 .. 0xa74 | 0xa85 .. 0xa8b | 0xa8d |\n 0xa8f .. 0xa91 | 0xa93 .. 0xaa8 | 0xaaa .. 0xab0 | 0xab2 .. 0xab3 |\n 0xab5 .. 0xab9 | 0xabd | 0xad0 | 0xae0 | 0xae6 .. 0xaef;\n ub =\n 0xb05 .. 0xb0c | 0xb0f .. 0xb10 | 0xb13 .. 0xb28 | 0xb2a .. 0xb30 |\n 0xb32 .. 0xb33 | 0xb36 .. 0xb39 | 0xb3d | 0xb5c .. 0xb5d |\n 0xb5f .. 0xb61 | 0xb66 .. 0xb6f | 0xb83 | 0xb85 .. 0xb8a |\n 0xb8e .. 0xb90 | 0xb92 .. 0xb95 | 0xb99 .. 0xb9a | 0xb9c |\n 0xb9e .. 0xb9f | 0xba3 .. 0xba4 | 0xba8 .. 0xbaa |\n 0xbae .. 0xbb5 | 0xbb7 .. 0xbb9 | 0xbe7 .. 0xbef;\n uc =\n 0xc05 .. 0xc0c | 0xc0e .. 0xc10 | 0xc12 .. 0xc28 | 0xc2a .. 0xc33 |\n 0xc35 .. 0xc39 | 0xc60 .. 0xc61 | 0xc66 .. 0xc6f | 0xc85 .. 0xc8c |\n 0xc8e .. 0xc90 | 0xc92 .. 0xca8 | 0xcaa .. 0xcb3 | 0xcb5 .. 0xcb9 |\n 0xcde | 0xce0 .. 0xce1 | 0xce6 .. 0xcef;\n ud =\n 0xd05 .. 0xd0c | 0xd0e .. 0xd10 | 0xd12 .. 0xd28 | 0xd2a .. 0xd39 |\n 0xd60 .. 0xd61 | 0xd66 .. 0xd6f | 0xd85 .. 0xd96 | 0xd9a .. 0xdb1 |\n 0xdb3 .. 0xdbb | 0xdbd | 0xdc0 .. 0xdc6;\n ue =\n 0xe01 .. 0xe2e | 0xe30 .. 0xe3a | 0xe40 .. 0xe45 | 0xe47 .. 0xe4e |\n 0xe50 .. 0xe59 | 0xe81 .. 0xe82 | 0xe84 | 0xe87 .. 0xe88 | 0xe8a |\n 0xe8d | 0xe94 .. 0xe97 | 0xe99 .. 0xe9f | 0xea1 .. 0xea3 | 0xea5 |\n 0xea7 | 0xeaa .. 0xeab | 0xead .. 0xeb0 | 0xeb2 .. 0xeb3 | 0xebd |\n 0xec0 .. 0xec4 | 0xec6 | 0xed0 .. 0xed9 | 0xedc .. 0xedd;\n uf =\n 0xf00 | 0xf20 .. 0xf29 | 0xf40 .. 0xf47 | 0xf49 .. 0xf6a |\n 0xf88 .. 0xf8b;\n u10 =\n 0x1000 .. 0x1021 | 0x1023 .. 0x1027 | 0x1029 .. 0x102a |\n 0x1040 .. 0x1049 | 0x1050 .. 0x1055 | 0x10a0 .. 0x10c5 |\n 0x10d0 .. 0x10f8;\n u11 =\n 0x1100 .. 0x1159 | 0x115f .. 0x11a2 | 0x11a8 .. 0x11f9;\n u12 =\n 0x1200 .. 0x1206 | 0x1208 .. 0x1246 | 0x1248 | 0x124a .. 0x124d |\n 0x1250 .. 0x1256 | 0x1258 | 0x125a .. 0x125d | 0x1260 .. 0x1286 |\n 0x1288 | 0x128a .. 0x128d | 0x1290 .. 0x12ae | 0x12b0 |\n 0x12b2 .. 0x12b5 | 0x12b8 .. 0x12be | 0x12c0 | 0x12c2 .. 0x12c5 |\n 0x12c8 .. 0x12ce | 0x12d0 .. 0x12d6 | 0x12d8 .. 0x12ee |\n 0x12f0 .. 0x12ff;\n u13 =\n 0x1300 .. 0x130e | 0x1310 | 0x1312 .. 0x1315 | 0x1318 .. 0x131e |\n 0x1320 .. 0x1346 | 0x1348 .. 0x135a | 0x1369 .. 0x1371 |\n 0x13a0 .. 0x13f4;\n u14 =\n 0x1401 .. 0x14ff;\n u16 =\n 0x1600 .. 0x166c | 0x166f .. 0x1676 | 0x1681 .. 0x169a |\n 0x16a0 .. 0x16ea | 0x16ee .. 0x16f0;\n u17 =\n 0x1700 .. 0x170c | 0x170e .. 0x1711 | 0x1720 .. 0x1731 |\n 0x1740 .. 0x1751 | 0x1760 .. 0x176c | 0x176e .. 0x1770 |\n 0x1780 .. 0x17b3 | 0x17d7 | 0x17dc | 0x17e0 .. 0x17e9;\n u18 =\n 0x1810 .. 0x1819 | 0x1820 .. 0x1877 | 0x1880 .. 0x18a8;\n u1e =\n 0x1e00 .. 0x1e9b | 0x1ea0 .. 0x1ef9;\n u1f =\n 0x1f00 .. 0x1f15 | 0x1f18 .. 0x1f1d | 0x1f20 .. 0x1f45 |\n 0x1f48 .. 0x1f4d | 0x1f50 .. 0x1f57 | 0x1f59 | 0x1f5b | 0x1f5d |\n 0x1f5f .. 0x1f7d | 0x1f80 .. 0x1fb4 | 0x1fb6 .. 0x1fbc | 0x1fbe |\n 0x1fc2 .. 0x1fc4 | 0x1fc6 .. 0x1fcc | 0x1fd0 .. 0x1fd3 |\n 0x1fd6 .. 0x1fdb | 0x1fe0 .. 0x1fec | 0x1ff2 .. 0x1ff4 |\n 0x1ff6 .. 0x1ffc;\n u20 =\n 0x2071 | 0x207f;\n u21 =\n 0x2102 | 0x2107 | 0x210a .. 0x2113 | 0x2115 | 0x2119 .. 0x211d |\n 0x2124 | 0x2126 | 0x2128 .. 0x212d | 0x212f .. 0x2131 |\n 0x2133 .. 0x2139 | 0x213d .. 0x213f | 0x2145 .. 0x2149 |\n 0x2160 .. 0x2183;\n u24 =\n 0x249c .. 0x24e9;\n u30 =\n 0x3005 .. 0x3007 | 0x3021 .. 0x3029 | 0x3031 .. 0x3035 |\n 0x3038 .. 0x303c | 0x3041 .. 0x3096 | 0x309d .. 0x309f |\n 0x30a1 .. 0x30fa | 0x30fc .. 0x30ff;\n u31 =\n 0x3105 .. 0x312c | 0x3131 .. 0x318e | 0x31a0 .. 0x31b7 |\n 0x31f0 .. 0x31ff;\n u4d =\n 0x4d00 .. 0x4db5;\n u9f =\n 0x9f00 .. 0x9fa5;\n ua4 =\n 0xa400 .. 0xa48c;\n ud7 =\n 0xd7a3;\n ufa =\n 0xfa00 .. 0xfa2d | 0xfa30 .. 0xfa6a;\n ufb =\n 0xfb00 .. 0xfb06 | 0xfb13 .. 0xfb17 | 0xfb1d | 0xfb1f .. 0xfb28 |\n 0xfb2a .. 0xfb36 | 0xfb38 .. 0xfb3c | 0xfb3e | 0xfb40 .. 0xfb41 |\n 0xfb43 .. 0xfb44 | 0xfb46 .. 0xfbb1 | 0xfbd3 .. 0xfbff;\n ufd =\n 0xfd00 .. 0xfd3d | 0xfd50 .. 0xfd8f | 0xfd92 .. 0xfdc7 |\n 0xfdf0 .. 0xfdfb;\n ufe =\n 0xfe70 .. 0xfe74 | 0xfe76 .. 0xfefc;\n uff =\n 0xff10 .. 0xff19 | 0xff21 .. 0xff3a | 0xff41 .. 0xff5a |\n 0xff66 .. 0xffbe | 0xffc2 .. 0xffc7 | 0xffca .. 0xffcf |\n 0xffd2 .. 0xffd7 | 0xffda .. 0xffdc;\n u103 =\n 0x10300 .. 0x1031e | 0x10330 .. 0x1034a;\n u104 =\n 0x10400 .. 0x10425 | 0x10428 .. 0x1044d;\n u1d4 =\n 0x1d400 .. 0x1d454 | 0x1d456 .. 0x1d49c | 0x1d49e .. 0x1d49f |\n 0x1d4a2 | 0x1d4a5 .. 0x1d4a6 | 0x1d4a9 .. 0x1d4ac |\n 0x1d4ae .. 0x1d4b9 | 0x1d4bb | 0x1d4bd .. 0x1d4c0 |\n 0x1d4c2 .. 0x1d4c3 | 0x1d4c5 .. 0x1d4ff;\n u1d5 =\n 0x1d500 .. 0x1d505 | 0x1d507 .. 0x1d50a | 0x1d50d .. 0x1d514 |\n 0x1d516 .. 0x1d51c | 0x1d51e .. 0x1d539 | 0x1d53b .. 0x1d53e |\n 0x1d540 .. 0x1d544 | 0x1d546 | 0x1d54a .. 0x1d550 |\n 0x1d552 .. 0x1d5ff;\n u1d6 =\n 0x1d600 .. 0x1d6a3 | 0x1d6a8 .. 0x1d6c0 | 0x1d6c2 .. 0x1d6da |\n 0x1d6dc .. 0x1d6fa | 0x1d6fc .. 0x1d6ff;\n u1d7 =\n 0x1d700 .. 0x1d714 | 0x1d716 .. 0x1d734 | 0x1d736 .. 0x1d74e |\n 0x1d750 .. 0x1d76e | 0x1d770 .. 0x1d788 | 0x1d78a .. 0x1d7a8 |\n 0x1d7aa .. 0x1d7c2 | 0x1d7c4 .. 0x1d7c9 | 0x1d7ce .. 0x1d7ff;\n u2a6 =\n 0x2a600 .. 0x2a6d6;\n u2fa =\n 0x2fa00 .. 0x2fa1d;\n\n walpha =\n 'a' .. 'z' |\n 'A' .. 'Z' |\n\n 0x0100 .. 0x01ff |\n 0x1500 .. 0x15ff |\n 0x3400 .. 0x4cff |\n 0x4e00 .. 0x9eff |\n 0xa000 .. 0xa3ff |\n 0xac00 .. 0xd6ff |\n 0xf900 .. 0xf9ff |\n 0xfc00 .. 0xfcff |\n 0x20000 .. 0x2a5ff |\n 0x2f800 .. 0x2f9ff |\n\n u0 | u2 | u3 | u4 | u5 | u6 | u7 |\n u9 | ua | ub | uc | ud | ue | uf |\n u10 | u11 | u12 | u13 | u14 | u16 |\n u17 | u18 | u1e | u1f | u20 | u21 |\n u24 | u30 | u31 | u4d | u9f | ua4 |\n ud7 | ufa | ufb | ufd | ufe | uff |\n u103 | u104 | u1d4 | u1d5 |\n u1d6 | u1d7 | u2a6 | u2fa;\n\n\n walnum = wdigit | walpha;\n\n delim = space;\n token = walpha walnum*;\n punc = [.,\\\/_\\-];\n proto = 'http'[s]? | 'ftp' | 'file';\n urlc = walnum | punc | [\\@\\:];\n\n main := |*\n\n #\/\/ Token, or token with possessive\n token { RET; };\n token [\\'] { trunc = 1; RET; };\n token [\\'][sS]? { trunc = 2; RET; };\n\n #\/\/ Token with hyphens\n walnum+ ('-' walnum+)* { RET; };\n\n #\/\/ Company name\n token [\\&\\@] token* { RET; };\n\n #\/\/ URL\n proto [:][\/]+ %{ skip = p - ts; } urlc+ [\/] { trunc = 1; RET; };\n proto [:][\/]+ %{ skip = p - ts; } urlc+ { RET; };\n walnum+[:][\/]+ urlc+ [\/] { trunc = 1; RET; };\n walnum+[:][\/]+ urlc+ { RET; };\n\n #\/\/ Email\n walnum+ '@' walnum+ '.' walpha+ { RET; };\n\n #\/\/ Acronym\n (walpha '.')+ walpha { STRIP('.'); };\n\n #\/\/ Int+float\n [\\-\\+]?wdigit+ { RET; };\n [\\-\\+]?wdigit+ '.' wdigit+ { RET; };\n\n #\/\/ Ignore whitespace and other crap\n 0 { return; };\n (any - walnum);\n\n *|;\n}%%\n\n%% write data nofinal;\n\nstatic int mb_next_char(wchar_t *wchr, const char *s, mbstate_t *state)\n{\n int num_bytes;\n if ((num_bytes = (int)mbrtowc(wchr, s, MB_CUR_MAX, state)) < 0) {\n const char *t = s;\n do {\n t++;\n ZEROSET(state, mbstate_t);\n num_bytes = (int)mbrtowc(wchr, t, MB_CUR_MAX, state);\n } while ((num_bytes < 0) && (*t != 0));\n num_bytes = t - s;\n if (*t == 0) *wchr = 0;\n }\n return num_bytes;\n}\n\n\/* Function takes in a multibyte string, converts it to wide-chars and\n then tokenizes that. *\/\nvoid frt_std_scan_mb(const char *in, size_t in_size,\n char *out, size_t out_size,\n char **start, char **end,\n int *len)\n{\n int cs, act;\n unsigned long *ts, *te = 0;\n\n %% write init;\n\n unsigned long buf[4096] = {0};\n unsigned long *bufp = buf;\n char *inp = (char *)in;\n mbstate_t state;\n ZEROSET(&state, mbstate_t);\n printf (\"TRYING TO PARSE: '%s'\\n\", in);\n while (inp < (in + in_size) && bufp < (buf + sizeof(buf)\/sizeof(*buf)))\n {\n if (!*inp)\n break;\n\n int n = mb_next_char((wchar_t *)bufp, inp, &state);\n if (n < 0)\n {\n printf (\"Error parsing input\\n\");\n ++inp;\n continue;\n }\n\n \/* We can break out early here on, say, a space XXX *\/\n inp += n;\n ++bufp;\n }\n\n printf (\"parsed: %d\\n\", inp - in);\n wprintf (L\"%ls\\n\", buf);\n printf (\"%04x\\n\", buf[5]);\n\n unsigned long *p = (unsigned long *)buf;\n unsigned long *pe = 0;\n unsigned long *eof = pe;\n *len = 0;\n int skip = 0;\n int trunc = 0;\n\n %% write exec;\n\n if ( cs == StdTokMb_error )\n {\n fprintf(stderr, \"PARSE ERROR\\n\" );\n return;\n }\n\n if ( ts )\n {\n fwprintf(stderr, L\"STUFF LEFT: '%ls'\\n\", ts);\n }\n}\n","old_contents":"\/* scanner.rl -*-C-*- *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"global.h\"\n#include \"internal.h\"\n\nstatic char *position_in_mb( const unsigned long *orig_wc,\n const char *orig_mb,\n const unsigned long *curr_wc )\n{\n char *mb = (char *)orig_mb;\n unsigned long *wc = (char *)orig_wc;\n\n while (wc < curr_wc)\n {\n char buf[MB_LEN_MAX];\n mb += wctomb(buf, *wc);\n ++wc;\n }\n\n return mb;\n}\n\n#define RET do { \\\n *start = position_in_mb(buf, in, ts); \\\n *end = position_in_mb(buf, in, te); \\\n size_t __len = *end - *start - skip - trunc; \\\n *len = __len; \\\n if (__len > out_size) \\\n __len = out_size; \\\n memcpy(out, *start + skip, __len); \\\n out[__len] = 0; \\\n return; \\\n} while(0)\n\n#define STRIP(c) do { \\\n unsigned long *__p = ts; \\\n unsigned long *__o = out; \\\n unsigned long *__max = __p + out_size; \\\n for (; __p <= te && __p < __max; ++__p) { \\\n if (*__p != c) \\\n *__o++ = *__p; \\\n } \\\n *__o = 0; \\\n \\\n *start = position_in_mb(buf, in, ts); \\\n *end = position_in_mb(buf, in, te); \\\n *len = (char *)__o - (char *)out; \\\n return; \\\n} while(0)\n\n%%{\n machine StdTokMb;\n alphtype unsigned long;\n include \"src\/wchar.rl\";\n\n wdigit = '0' .. '9';\n\n u0 = (0x041 .. 0x05a | 0x061 .. 0x07a | 0x0aa | 0x0b5 | 0x0ba | 0x0c0 .. 0x0d6 | 0x0d8 .. 0x0f6 | 0x0f8 .. 0x0ff);\n u2 = (0x200 .. 0x220 | 0x222 .. 0x233 | 0x250 .. 0x2ad | 0x2b0 .. 0x2b8 | 0x2bb .. 0x2c1 | 0x2d0 .. 0x2d1 | 0x2e0 .. 0x2e4 | 0x2ee);\n u3 = (0x345 | 0x37a | 0x386 | 0x388 .. 0x38a | 0x38c | 0x38e .. 0x3a1 | 0x3a3 .. 0x3ce | 0x3d0 .. 0x3f5);\n u4 = (0x400 .. 0x481 | 0x48a .. 0x4ce | 0x4d0 .. 0x4f5 | 0x4f8 .. 0x4f9);\n u5 = (0x500 .. 0x50f | 0x531 .. 0x556 | 0x559 | 0x561 .. 0x587 | 0x5d0 .. 0x5ea | 0x5f0 .. 0x5f2);\n u6 = (0x621 .. 0x63a | 0x640 .. 0x64a | 0x660 .. 0x669 | 0x66e .. 0x66f | 0x671 .. 0x6d3 | 0x6d5 | 0x6e5 .. 0x6e6 | 0x6f0 .. 0x6fc);\n u7 = (0x710 | 0x712 .. 0x72c | 0x780 .. 0x7a5 | 0x7b1);\n u9 = (0x905 .. 0x939 | 0x93d | 0x950 | 0x958 .. 0x961 | 0x966 .. 0x96f | 0x985 .. 0x98c | 0x98f .. 0x990 | 0x993 .. 0x9a8 | 0x9aa .. 0x9b0 | 0x9b2 | 0x9b6 .. 0x9b9 | 0x9dc .. 0x9dd | 0x9df .. 0x9e1 | 0x9e6 .. 0x9f1);\n ua = (0xa05 .. 0xa0a | 0xa0f .. 0xa10 | 0xa13 .. 0xa28 | 0xa2a .. 0xa30 | 0xa32 .. 0xa33 | 0xa35 .. 0xa36 | 0xa38 .. 0xa39 | 0xa59 .. 0xa5c | 0xa5e | 0xa66 .. 0xa6f | 0xa72 .. 0xa74 | 0xa85 .. 0xa8b | 0xa8d | 0xa8f .. 0xa91 | 0xa93 .. 0xaa8 | 0xaaa .. 0xab0 | 0xab2 .. 0xab3 | 0xab5 .. 0xab9 | 0xabd | 0xad0 | 0xae0 | 0xae6 .. 0xaef);\n ub = (0xb05 .. 0xb0c | 0xb0f .. 0xb10 | 0xb13 .. 0xb28 | 0xb2a .. 0xb30 | 0xb32 .. 0xb33 | 0xb36 .. 0xb39 | 0xb3d | 0xb5c .. 0xb5d | 0xb5f .. 0xb61 | 0xb66 .. 0xb6f | 0xb83 | 0xb85 .. 0xb8a | 0xb8e .. 0xb90 | 0xb92 .. 0xb95 | 0xb99 .. 0xb9a | 0xb9c | 0xb9e .. 0xb9f | 0xba3 .. 0xba4 | 0xba8 .. 0xbaa | 0xbae .. 0xbb5 | 0xbb7 .. 0xbb9 | 0xbe7 .. 0xbef);\n uc = (0xc05 .. 0xc0c | 0xc0e .. 0xc10 | 0xc12 .. 0xc28 | 0xc2a .. 0xc33 | 0xc35 .. 0xc39 | 0xc60 .. 0xc61 | 0xc66 .. 0xc6f | 0xc85 .. 0xc8c | 0xc8e .. 0xc90 | 0xc92 .. 0xca8 | 0xcaa .. 0xcb3 | 0xcb5 .. 0xcb9 | 0xcde | 0xce0 .. 0xce1 | 0xce6 .. 0xcef);\n ud = (0xd05 .. 0xd0c | 0xd0e .. 0xd10 | 0xd12 .. 0xd28 | 0xd2a .. 0xd39 | 0xd60 .. 0xd61 | 0xd66 .. 0xd6f | 0xd85 .. 0xd96 | 0xd9a .. 0xdb1 | 0xdb3 .. 0xdbb | 0xdbd | 0xdc0 .. 0xdc6);\n ue = (0xe01 .. 0xe2e | 0xe30 .. 0xe3a | 0xe40 .. 0xe45 | 0xe47 .. 0xe4e | 0xe50 .. 0xe59 | 0xe81 .. 0xe82 | 0xe84 | 0xe87 .. 0xe88 | 0xe8a | 0xe8d | 0xe94 .. 0xe97 | 0xe99 .. 0xe9f | 0xea1 .. 0xea3 | 0xea5 | 0xea7 | 0xeaa .. 0xeab | 0xead .. 0xeb0 | 0xeb2 .. 0xeb3 | 0xebd | 0xec0 .. 0xec4 | 0xec6 | 0xed0 .. 0xed9 | 0xedc .. 0xedd);\n uf = (0xf00 | 0xf20 .. 0xf29 | 0xf40 .. 0xf47 | 0xf49 .. 0xf6a | 0xf88 .. 0xf8b);\n u10 = (0x1000 .. 0x1021 | 0x1023 .. 0x1027 | 0x1029 .. 0x102a | 0x1040 .. 0x1049 | 0x1050 .. 0x1055 | 0x10a0 .. 0x10c5 | 0x10d0 .. 0x10f8);\n u11 = (0x1100 .. 0x1159 | 0x115f .. 0x11a2 | 0x11a8 .. 0x11f9);\n u12 = (0x1200 .. 0x1206 | 0x1208 .. 0x1246 | 0x1248 | 0x124a .. 0x124d | 0x1250 .. 0x1256 | 0x1258 | 0x125a .. 0x125d | 0x1260 .. 0x1286 | 0x1288 | 0x128a .. 0x128d | 0x1290 .. 0x12ae | 0x12b0 | 0x12b2 .. 0x12b5 | 0x12b8 .. 0x12be | 0x12c0 | 0x12c2 .. 0x12c5 | 0x12c8 .. 0x12ce | 0x12d0 .. 0x12d6 | 0x12d8 .. 0x12ee | 0x12f0 .. 0x12ff);\n u13 = (0x1300 .. 0x130e | 0x1310 | 0x1312 .. 0x1315 | 0x1318 .. 0x131e | 0x1320 .. 0x1346 | 0x1348 .. 0x135a | 0x1369 .. 0x1371 | 0x13a0 .. 0x13f4);\n u14 = (0x1401 .. 0x14ff);\n u16 = (0x1600 .. 0x166c | 0x166f .. 0x1676 | 0x1681 .. 0x169a | 0x16a0 .. 0x16ea | 0x16ee .. 0x16f0);\n u17 = (0x1700 .. 0x170c | 0x170e .. 0x1711 | 0x1720 .. 0x1731 | 0x1740 .. 0x1751 | 0x1760 .. 0x176c | 0x176e .. 0x1770 | 0x1780 .. 0x17b3 | 0x17d7 | 0x17dc | 0x17e0 .. 0x17e9);\n u18 = (0x1810 .. 0x1819 | 0x1820 .. 0x1877 | 0x1880 .. 0x18a8);\n u1e = (0x1e00 .. 0x1e9b | 0x1ea0 .. 0x1ef9);\n u1f = (0x1f00 .. 0x1f15 | 0x1f18 .. 0x1f1d | 0x1f20 .. 0x1f45 | 0x1f48 .. 0x1f4d | 0x1f50 .. 0x1f57 | 0x1f59 | 0x1f5b | 0x1f5d | 0x1f5f .. 0x1f7d | 0x1f80 .. 0x1fb4 | 0x1fb6 .. 0x1fbc | 0x1fbe | 0x1fc2 .. 0x1fc4 | 0x1fc6 .. 0x1fcc | 0x1fd0 .. 0x1fd3 | 0x1fd6 .. 0x1fdb | 0x1fe0 .. 0x1fec | 0x1ff2 .. 0x1ff4 | 0x1ff6 .. 0x1ffc);\n u20 = (0x2071 | 0x207f);\n u21 = (0x2102 | 0x2107 | 0x210a .. 0x2113 | 0x2115 | 0x2119 .. 0x211d | 0x2124 | 0x2126 | 0x2128 .. 0x212d | 0x212f .. 0x2131 | 0x2133 .. 0x2139 | 0x213d .. 0x213f | 0x2145 .. 0x2149 | 0x2160 .. 0x2183);\n u24 = (0x249c .. 0x24e9);\n u30 = (0x3005 .. 0x3007 | 0x3021 .. 0x3029 | 0x3031 .. 0x3035 | 0x3038 .. 0x303c | 0x3041 .. 0x3096 | 0x309d .. 0x309f | 0x30a1 .. 0x30fa | 0x30fc .. 0x30ff);\n u31 = (0x3105 .. 0x312c | 0x3131 .. 0x318e | 0x31a0 .. 0x31b7 | 0x31f0 .. 0x31ff);\n u4d = (0x4d00 .. 0x4db5);\n u9f = (0x9f00 .. 0x9fa5);\n ua4 = (0xa400 .. 0xa48c);\n ud7 = (0xd7a3);\n ufa = (0xfa00 .. 0xfa2d | 0xfa30 .. 0xfa6a);\n ufb = (0xfb00 .. 0xfb06 | 0xfb13 .. 0xfb17 | 0xfb1d | 0xfb1f .. 0xfb28 | 0xfb2a .. 0xfb36 | 0xfb38 .. 0xfb3c | 0xfb3e | 0xfb40 .. 0xfb41 | 0xfb43 .. 0xfb44 | 0xfb46 .. 0xfbb1 | 0xfbd3 .. 0xfbff);\n ufd = (0xfd00 .. 0xfd3d | 0xfd50 .. 0xfd8f | 0xfd92 .. 0xfdc7 | 0xfdf0 .. 0xfdfb);\n ufe = (0xfe70 .. 0xfe74 | 0xfe76 .. 0xfefc);\n uff = (0xff10 .. 0xff19 | 0xff21 .. 0xff3a | 0xff41 .. 0xff5a | 0xff66 .. 0xffbe | 0xffc2 .. 0xffc7 | 0xffca .. 0xffcf | 0xffd2 .. 0xffd7 | 0xffda .. 0xffdc);\n u103 = (0x10300 .. 0x1031e | 0x10330 .. 0x1034a);\n u104 = (0x10400 .. 0x10425 | 0x10428 .. 0x1044d);\n u1d4 = (0x1d400 .. 0x1d454 | 0x1d456 .. 0x1d49c | 0x1d49e .. 0x1d49f | 0x1d4a2 | 0x1d4a5 .. 0x1d4a6 | 0x1d4a9 .. 0x1d4ac | 0x1d4ae .. 0x1d4b9 | 0x1d4bb | 0x1d4bd .. 0x1d4c0 | 0x1d4c2 .. 0x1d4c3 | 0x1d4c5 .. 0x1d4ff);\n u1d5 = (0x1d500 .. 0x1d505 | 0x1d507 .. 0x1d50a | 0x1d50d .. 0x1d514 | 0x1d516 .. 0x1d51c | 0x1d51e .. 0x1d539 | 0x1d53b .. 0x1d53e | 0x1d540 .. 0x1d544 | 0x1d546 | 0x1d54a .. 0x1d550 | 0x1d552 .. 0x1d5ff);\n u1d6 = (0x1d600 .. 0x1d6a3 | 0x1d6a8 .. 0x1d6c0 | 0x1d6c2 .. 0x1d6da | 0x1d6dc .. 0x1d6fa | 0x1d6fc .. 0x1d6ff);\n u1d7 = (0x1d700 .. 0x1d714 | 0x1d716 .. 0x1d734 | 0x1d736 .. 0x1d74e | 0x1d750 .. 0x1d76e | 0x1d770 .. 0x1d788 | 0x1d78a .. 0x1d7a8 | 0x1d7aa .. 0x1d7c2 | 0x1d7c4 .. 0x1d7c9 | 0x1d7ce .. 0x1d7ff);\n u2a6 = (0x2a600 .. 0x2a6d6);\n u2fa = (0x2fa00 .. 0x2fa1d);\n\n walpha =\n 'a' .. 'z' |\n 'A' .. 'Z' |\n\n 0x0010 .. 0x001f |\n 0x0150 .. 0x015f |\n 0x0340 .. 0x04cf |\n 0x04e0 .. 0x09ef |\n 0x0a00 .. 0x0a3f |\n 0x0ac0 .. 0x0d6f |\n 0x0f90 .. 0x0f9f |\n 0x0fc0 .. 0x0fcf |\n 0x02000 .. 0x02a5f |\n 0x02f80 .. 0x02f9f |\n\n u0 | u2 | u3 | u4 | u5 | u6 | u7 |\n u9 | ua | ub | uc | ud | ue | uf |\n u10 | u11 | u12 | u13 | u14 | u16 |\n u17 | u18 | u1e | u1f | u20 | u21 |\n u24 | u30 | u31 | u4d | u9f | ua4 |\n ud7 | ufa | ufb | ufd | ufe | uff |\n u103 | u104 | u1d4 | u1d5 |\n u1d6 | u1d7 | u2a6 | u2fa;\n\n\n walnum = wdigit | walpha;\n\n delim = space;\n token = walpha walnum*;\n punc = [.,\\\/_\\-];\n proto = 'http'[s]? | 'ftp' | 'file';\n urlc = walnum | punc | [\\@\\:];\n\n main := |*\n\n #\/\/ Token, or token with possessive\n token { RET; };\n token [\\'] { trunc = 1; RET; };\n token [\\'][sS]? { trunc = 2; RET; };\n\n #\/\/ Token with hyphens\n walnum+ ('-' walnum+)* { RET; };\n\n #\/\/ Company name\n token [\\&\\@] token* { RET; };\n\n #\/\/ URL\n proto [:][\/]+ %{ skip = p - ts; } urlc+ [\/] { trunc = 1; RET; };\n proto [:][\/]+ %{ skip = p - ts; } urlc+ { RET; };\n walnum+[:][\/]+ urlc+ [\/] { trunc = 1; RET; };\n walnum+[:][\/]+ urlc+ { RET; };\n\n #\/\/ Email\n walnum+ '@' walnum+ '.' walpha+ { RET; };\n\n #\/\/ Acronym\n (walpha '.')+ walpha { STRIP('.'); };\n\n #\/\/ Int+float\n [\\-\\+]?wdigit+ { RET; };\n [\\-\\+]?wdigit+ '.' wdigit+ { RET; };\n\n #\/\/ Ignore whitespace and other crap\n 0 { return; };\n (any - walnum);\n\n *|;\n}%%\n\n%% write data nofinal;\n\nstatic int mb_next_char(wchar_t *wchr, const char *s, mbstate_t *state)\n{\n int num_bytes;\n if ((num_bytes = (int)mbrtowc(wchr, s, MB_CUR_MAX, state)) < 0) {\n const char *t = s;\n do {\n t++;\n ZEROSET(state, mbstate_t);\n num_bytes = (int)mbrtowc(wchr, t, MB_CUR_MAX, state);\n } while ((num_bytes < 0) && (*t != 0));\n num_bytes = t - s;\n if (*t == 0) *wchr = 0;\n }\n return num_bytes;\n}\n\n\/* Function takes in a multibyte string, converts it to wide-chars and\n then tokenizes that. *\/\nvoid frt_std_scan_mb(const char *in, size_t in_size,\n char *out, size_t out_size,\n char **start, char **end,\n int *len)\n{\n int cs, act;\n unsigned long *ts, *te = 0;\n\n %% write init;\n\n unsigned long buf[4096] = {0};\n unsigned long *bufp = buf;\n char *inp = (char *)in;\n mbstate_t state;\n ZEROSET(&state, mbstate_t);\n printf (\"TRYING TO PARSE: '%s'\\n\", in);\n while (inp < (in + in_size) && bufp < (buf + sizeof(buf)\/sizeof(*buf)))\n {\n if (!*inp)\n break;\n\n int n = mb_next_char((wchar_t *)bufp, inp, &state);\n if (n < 0)\n {\n printf (\"Error parsing input\\n\");\n ++inp;\n continue;\n }\n\n \/* We can break out early here on, say, a space XXX *\/\n inp += n;\n ++bufp;\n }\n\n printf (\"parsed: %d\\n\", inp - in);\n wprintf (L\"%ls\\n\", buf);\n printf (\"%04x\\n\", buf[5]);\n\n unsigned long *p = (unsigned long *)buf;\n unsigned long *pe = 0;\n unsigned long *eof = pe;\n *len = 0;\n int skip = 0;\n int trunc = 0;\n\n %% write exec;\n\n if ( cs == StdTokMb_error )\n {\n fprintf(stderr, \"PARSE ERROR\\n\" );\n return;\n }\n\n if ( ts )\n {\n fwprintf(stderr, L\"STUFF LEFT: '%ls'\\n\", ts);\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"2e9cda515a4f03952d7f444407d617d747bb3c5e","subject":"Fixing UnicodeBlock tests.","message":"Fixing UnicodeBlock tests.\n","repos":"ammar\/regexp_parser,jhart-r7\/regexp_parser,ammar\/regexp_parser","old_file":"lib\/regexp_parser\/scanner\/property.rl","new_file":"lib\/regexp_parser\/scanner\/property.rl","new_contents":"%%{\n machine re_property;\n\n property_char = [pP];\n\n # Property names are being treated as case-insensitive, but it is not clear\n # yet if this applies to all flavors and in all encodings. A bug has just\n # been filed against ruby regarding this issue, see:\n # http:\/\/redmine.ruby-lang.org\/issues\/show\/4014\n property_name_unicode = 'alnum'i | 'alpha'i | 'any'i | 'ascii'i | 'blank'i |\n 'cntrl'i | 'digit'i | 'graph'i | 'lower'i | 'print'i |\n 'punct'i | 'space'i | 'upper'i | 'word'i | 'xdigit'i;\n\n property_name_posix = 'any'i | 'assigned'i | 'newline'i;\n\n property_name = property_name_unicode | property_name_posix;\n\n category_letter = [Ll] . [ultmo]?;\n category_mark = [Mm] . [nce]?;\n category_number = [Nn] . [dlo]?;\n category_punctuation = [Pp] . [cdseifo]?;\n category_symbol = [Ss] . [mcko]?;\n category_separator = [Zz] . [slp]?;\n category_codepoint = [Cc] . [cfson]?;\n\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n property_derived = 'math'i | 'alphabetic'i |\n 'lowercase'i | 'uppercase'i |\n 'id_start'i | 'id_continue'i |\n 'xid_start'i | 'xid_continue'i |\n 'grapheme_base'i | 'grapheme_extend'i |\n 'default_ignorable_code_point'i;\n\n property_age = 'age=1.1'i | 'age=2.0'i | 'age=2.1'i |\n 'age=3.0'i | 'age=3.1'i | 'age=3.2'i |\n 'age=4.0'i | 'age=4.1'i | 'age=5.0'i |\n 'age=5.1'i | 'age=5.2'i | 'age=6.0'i |\n 'age=6.1'i | 'age=6.2'i | 'age=6.3'i |\n 'age=7.0'i;\n\n property_script = (alnum | space | '_' | '-')+; # everything else\n\n property_sequence = property_char . '{' . '^'? (\n property_name | general_category |\n property_age | property_derived |\n property_script\n ) . '}';\n\n action premature_property_end {\n raise PrematureEndError.new('unicode property')\n }\n\n # Unicode properties scanner\n # --------------------------------------------------------------------------\n unicode_property := |*\n\n property_sequence < eof(premature_property_end) {\n text = text(data, ts, te, 1).first\n if in_set\n type = :set\n else\n type = text[1,1] == 'p' ? :property : :nonproperty\n end\n\n name = data[ts+2..te-2].pack('c*').gsub(\/[\\s_]\/,'').downcase\n if name[0].chr == '^'\n name = name[1..-1]\n type = :nonproperty\n end\n\n case name\n # Named\n when 'alnum'\n self.emit(type, :alnum, text, ts-1, te)\n when 'alpha'\n self.emit(type, :alpha, text, ts-1, te)\n when 'ascii'\n self.emit(type, :ascii, text, ts-1, te)\n when 'blank'\n self.emit(type, :blank, text, ts-1, te)\n when 'cntrl'\n self.emit(type, :cntrl, text, ts-1, te)\n when 'digit'\n self.emit(type, :digit, text, ts-1, te)\n when 'graph'\n self.emit(type, :graph, text, ts-1, te)\n when 'lower'\n self.emit(type, :lower, text, ts-1, te)\n when 'print'\n self.emit(type, :print, text, ts-1, te)\n when 'punct'\n self.emit(type, :punct, text, ts-1, te)\n when 'space'\n self.emit(type, :space, text, ts-1, te)\n when 'upper'\n self.emit(type, :upper, text, ts-1, te)\n when 'xdigit'\n self.emit(type, :xdigit, text, ts-1, te)\n\n when 'any'\n self.emit(type, :any, text, ts-1, te)\n when 'assigned'\n self.emit(type, :assigned, text, ts-1, te)\n when 'newline'\n self.emit(type, :newline, text, ts-1, te)\n when 'word'\n self.emit(type, :word, text, ts-1, te)\n\n # Letters\n when 'l', 'letter'\n self.emit(type, :letter_any, text, ts-1, te)\n when 'lu', 'uppercaseletter'\n self.emit(type, :letter_uppercase, text, ts-1, te)\n when 'll', 'lowercaseletter'\n self.emit(type, :letter_lowercase, text, ts-1, te)\n when 'lt', 'titlecaseletter'\n self.emit(type, :letter_titlecase, text, ts-1, te)\n when 'lm', 'modifierletter'\n self.emit(type, :letter_modifier, text, ts-1, te)\n when 'lo', 'otherletter'\n self.emit(type, :letter_other, text, ts-1, te)\n\n # Marks\n when 'm', 'mark'\n self.emit(type, :mark_any, text, ts-1, te)\n when 'mn', 'nonspacingmark'\n self.emit(type, :mark_nonspacing, text, ts-1, te)\n when 'mc', 'spacingmark'\n self.emit(type, :mark_spacing, text, ts-1, te)\n when 'me', 'enclosingmark'\n self.emit(type, :mark_enclosing, text, ts-1, te)\n\n # Numbers\n when 'n', 'number'\n self.emit(type, :number_any, text, ts-1, te)\n when 'nd', 'decimalnumber'\n self.emit(type, :number_decimal, text, ts-1, te)\n when 'nl', 'letternumber'\n self.emit(type, :number_letter, text, ts-1, te)\n when 'no', 'othernumber'\n self.emit(type, :number_other, text, ts-1, te)\n\n # Punctuation\n when 'p', 'punctuation'\n self.emit(type, :punct_any, text, ts-1, te)\n when 'pc', 'connectorpunctuation'\n self.emit(type, :punct_connector, text, ts-1, te)\n when 'pd', 'dashpunctuation'\n self.emit(type, :punct_dash, text, ts-1, te)\n when 'ps', 'openpunctuation'\n self.emit(type, :punct_open, text, ts-1, te)\n when 'pe', 'closepunctuation'\n self.emit(type, :punct_close, text, ts-1, te)\n when 'pi', 'initialpunctuation'\n self.emit(type, :punct_initial, text, ts-1, te)\n when 'pf', 'finalpunctuation'\n self.emit(type, :punct_final, text, ts-1, te)\n when 'po', 'otherpunctuation'\n self.emit(type, :punct_other, text, ts-1, te)\n\n # Symbols\n when 's', 'symbol'\n self.emit(type, :symbol_any, text, ts-1, te)\n when 'sm', 'mathsymbol'\n self.emit(type, :symbol_math, text, ts-1, te)\n when 'sc', 'currencysymbol'\n self.emit(type, :symbol_currency, text, ts-1, te)\n when 'sk', 'modifiersymbol'\n self.emit(type, :symbol_modifier, text, ts-1, te)\n when 'so', 'othersymbol'\n self.emit(type, :symbol_other, text, ts-1, te)\n\n # Separators\n when 'z', 'separator'\n self.emit(type, :separator_any, text, ts-1, te)\n when 'zs', 'spaceseparator'\n self.emit(type, :separator_space, text, ts-1, te)\n when 'zl', 'lineseparator'\n self.emit(type, :separator_line, text, ts-1, te)\n when 'zp', 'paragraphseparator'\n self.emit(type, :separator_para, text, ts-1, te)\n\n # Codepoints\n when 'c', 'other'\n self.emit(type, :other, text, ts-1, te)\n when 'cc', 'control'\n self.emit(type, :control, text, ts-1, te)\n when 'cf', 'format'\n self.emit(type, :format, text, ts-1, te)\n when 'cs', 'surrogate'\n self.emit(type, :surrogate, text, ts-1, te)\n when 'co', 'privateuse'\n self.emit(type, :private_use, text, ts-1, te)\n when 'cn', 'unassigned'\n self.emit(type, :unassigned, text, ts-1, te)\n\n # Age\n when 'age=1.1'\n self.emit(type, :age_1_1, text, ts-1, te)\n when 'age=2.0'\n self.emit(type, :age_2_0, text, ts-1, te)\n when 'age=2.1'\n self.emit(type, :age_2_1, text, ts-1, te)\n when 'age=3.0'\n self.emit(type, :age_3_0, text, ts-1, te)\n when 'age=3.1'\n self.emit(type, :age_3_1, text, ts-1, te)\n when 'age=3.2'\n self.emit(type, :age_3_2, text, ts-1, te)\n when 'age=4.0'\n self.emit(type, :age_4_0, text, ts-1, te)\n when 'age=4.1'\n self.emit(type, :age_4_1, text, ts-1, te)\n when 'age=5.0'\n self.emit(type, :age_5_0, text, ts-1, te)\n when 'age=5.1'\n self.emit(type, :age_5_1, text, ts-1, te)\n when 'age=5.2'\n self.emit(type, :age_5_2, text, ts-1, te)\n when 'age=6.0'\n self.emit(type, :age_6_0, text, ts-1, te)\n when 'age=6.1'\n self.emit(type, :age_6_1, text, ts-1, te)\n when 'age=6.2'\n self.emit(type, :age_6_2, text, ts-1, te)\n when 'age=6.3'\n self.emit(type, :age_6_3, text, ts-1, te)\n when 'age=7.0'\n self.emit(type, :age_7_0, text, ts-1, te)\n\n # Derived Properties\n when 'ahex', 'asciihexdigit'\n self.emit(type, :ascii_hex, text, ts-1, te)\n when 'alphabetic'\n self.emit(type, :alphabetic, text, ts-1, te)\n when 'cased'\n self.emit(type, :cased, text, ts-1, te)\n when 'cwcf', 'changeswhencasefolded'\n self.emit(type, :changes_when_casefolded, text, ts-1, te)\n when 'cwcm', 'changeswhencasemapped'\n self.emit(type, :changes_when_casemapped, text, ts-1, te)\n when 'cwl', 'changeswhenlowercased'\n self.emit(type, :changes_when_lowercased, text, ts-1, te)\n when 'cwt', 'changeswhentitlecased'\n self.emit(type, :changes_when_titlecased, text, ts-1, te)\n when 'cwu', 'changeswhenuppercased'\n self.emit(type, :changes_when_uppercased, text, ts-1, te)\n when 'ci', 'caseignorable'\n self.emit(type, :case_ignorable, text, ts-1, te)\n when 'bidic', 'bidicontrol'\n self.emit(type, :bidi_control, text, ts-1, te)\n when 'dash'\n self.emit(type, :dash, text, ts-1, te)\n when 'dep', 'deprecated'\n self.emit(type, :deprecated, text, ts-1, te)\n when 'di', 'defaultignorablecodepoint'\n self.emit(type, :default_ignorable_cp, text, ts-1, te)\n when 'dia', 'diacritic'\n self.emit(type, :diacritic, text, ts-1, te)\n when 'ext', 'extender'\n self.emit(type, :extender, text, ts-1, te)\n when 'grbase', 'graphemebase'\n self.emit(type, :grapheme_base, text, ts-1, te)\n when 'grext', 'graphemeextend'\n self.emit(type, :grapheme_extend, text, ts-1, te)\n when 'grlink', 'graphemelink' # NOTE: deprecated as of Unicode 5.0\n self.emit(type, :grapheme_link, text, ts-1, te)\n when 'hex', 'hexdigit'\n self.emit(type, :hex_digit, text, ts-1, te)\n when 'hyphen' # NOTE: deprecated as of Unicode 6.0\n self.emit(type, :hyphen, text, ts-1, te)\n when 'idc', 'idcontinue'\n self.emit(type, :id_continue, text, ts-1, te)\n when 'ideo', 'ideographic'\n self.emit(type, :ideographic, text, ts-1, te)\n when 'ids', 'idstart'\n self.emit(type, :id_start, text, ts-1, te)\n when 'idsb', 'idsbinaryoperator'\n self.emit(type, :ids_binary_op, text, ts-1, te)\n when 'idst', 'idstrinaryoperator'\n self.emit(type, :ids_trinary_op, text, ts-1, te)\n when 'joinc', 'joincontrol'\n self.emit(type, :join_control, text, ts-1, te)\n when 'loe', 'logicalorderexception'\n self.emit(type, :logical_order_exception, text, ts-1, te)\n when 'lowercase'\n self.emit(type, :lowercase, text, ts-1, te)\n when 'math'\n self.emit(type, :math, text, ts-1, te)\n when 'nchar', 'noncharactercodepoint'\n self.emit(type, :non_character_cp, text, ts-1, te)\n when 'oalpha', 'otheralphabetic'\n self.emit(type, :other_alphabetic, text, ts-1, te)\n when 'odi', 'otherdefaultignorablecodepoint'\n self.emit(type, :other_default_ignorable_cp, text, ts-1, te)\n when 'ogrext', 'othergraphemeextend'\n self.emit(type, :other_grapheme_extended, text, ts-1, te)\n when 'oidc', 'otheridcontinue'\n self.emit(type, :other_id_continue, text, ts-1, te)\n when 'oids', 'otheridstart'\n self.emit(type, :other_id_start, text, ts-1, te)\n when 'olower', 'otherlowercase'\n self.emit(type, :other_lowercase, text, ts-1, te)\n when 'omath', 'othermath'\n self.emit(type, :other_math, text, ts-1, te)\n when 'oupper', 'otheruppercase'\n self.emit(type, :other_uppercase, text, ts-1, te)\n when 'patsyn', 'patternsyntax'\n self.emit(type, :pattern_syntax, text, ts-1, te)\n when 'patws', 'patternwhitespace'\n self.emit(type, :pattern_whitespace, text, ts-1, te)\n when 'qmark', 'quotationmark'\n self.emit(type, :quotation_mark, text, ts-1, te)\n when 'radical'\n self.emit(type, :radical, text, ts-1, te)\n when 'sd', 'softdotted'\n self.emit(type, :soft_dotted, text, ts-1, te)\n when 'sterm'\n self.emit(type, :sentence_terminal, text, ts-1, te)\n when 'term', 'terminalpunctuation'\n self.emit(type, :terminal_punctuation, text, ts-1, te)\n when 'uideo', 'unifiedideograph'\n self.emit(type, :unified_ideograph, text, ts-1, te)\n when 'uppercase'\n self.emit(type, :uppercase, text, ts-1, te)\n when 'vs', 'variationselector'\n self.emit(type, :variation_selector, text, ts-1, te)\n when 'wspace', 'whitespace'\n self.emit(type, :whitespace, text, ts-1, te)\n when 'xids', 'xidstart'\n self.emit(type, :xid_start, text, ts-1, te)\n when 'xidc', 'xidcontinue'\n self.emit(type, :xid_continue, text, ts-1, te)\n\n # Scripts\n when 'aghb', 'caucasianalbanian'\n self.emit(type, :script_caucasian_albanian, text, ts-1, te)\n when 'arab', 'arabic'\n self.emit(type, :script_arabic, text, ts-1, te)\n when 'armi', 'imperialaramaic'\n self.emit(type, :script_imperial_aramaic, text, ts-1, te)\n when 'armn', 'armenian'\n self.emit(type, :script_armenian, text, ts-1, te)\n when 'avst', 'avestan'\n self.emit(type, :script_avestan, text, ts-1, te)\n when 'bali', 'balinese'\n self.emit(type, :script_balinese, text, ts-1, te)\n when 'bamu', 'bamum'\n self.emit(type, :script_bamum, text, ts-1, te)\n when 'bass', 'bassavah'\n self.emit(type, :script_bassa_vah, text, ts-1, te)\n when 'batk', 'batak'\n self.emit(type, :script_batak, text, ts-1, te)\n when 'beng', 'bengali'\n self.emit(type, :script_bengali, text, ts-1, te)\n when 'bopo', 'bopomofo'\n self.emit(type, :script_bopomofo, text, ts-1, te)\n when 'brah', 'brahmi'\n self.emit(type, :script_brahmi, text, ts-1, te)\n when 'brai', 'braille'\n self.emit(type, :script_braille, text, ts-1, te)\n when 'bugi', 'buginese'\n self.emit(type, :script_buginese, text, ts-1, te)\n when 'buhd', 'buhid'\n self.emit(type, :script_buhid, text, ts-1, te)\n when 'cans', 'canadianaboriginal'\n self.emit(type, :script_canadian_aboriginal, text, ts-1, te)\n when 'cari', 'carian'\n self.emit(type, :script_carian, text, ts-1, te)\n when 'cham'\n self.emit(type, :script_cham, text, ts-1, te)\n when 'cher', 'cherokee'\n self.emit(type, :script_cherokee, text, ts-1, te)\n when 'copt', 'coptic', 'qaac'\n self.emit(type, :script_coptic, text, ts-1, te)\n when 'cprt', 'cypriot'\n self.emit(type, :script_cypriot, text, ts-1, te)\n when 'cyrl', 'cyrillic'\n self.emit(type, :script_cyrillic, text, ts-1, te)\n when 'deva', 'devanagari'\n self.emit(type, :script_devanagari, text, ts-1, te)\n when 'dsrt', 'deseret'\n self.emit(type, :script_deseret, text, ts-1, te)\n when 'dupl', 'duployan'\n self.emit(type, :script_duployan, text, ts-1, te)\n when 'egyp', 'egyptianhieroglyphs'\n self.emit(type, :script_egyptian_hieroglyphs, text, ts-1, te)\n when 'elba', 'elbasan'\n self.emit(type, :script_elbasan, text, ts-1, te)\n when 'ethi', 'ethiopic'\n self.emit(type, :script_ethiopic, text, ts-1, te)\n when 'geor', 'georgian'\n self.emit(type, :script_georgian, text, ts-1, te)\n when 'glag', 'glagolitic'\n self.emit(type, :script_glagolitic, text, ts-1, te)\n when 'goth', 'gothic'\n self.emit(type, :script_gothic, text, ts-1, te)\n when 'gran', 'grantha'\n self.emit(type, :script_grantha, text, ts-1, te)\n when 'grek', 'greek'\n self.emit(type, :script_greek, text, ts-1, te)\n when 'gujr', 'gujarati'\n self.emit(type, :script_gujarati, text, ts-1, te)\n when 'guru', 'gurmukhi'\n self.emit(type, :script_gurmukhi, text, ts-1, te)\n when 'hang', 'hangul'\n self.emit(type, :script_hangul, text, ts-1, te)\n when 'hani', 'han'\n self.emit(type, :script_han, text, ts-1, te)\n when 'hano', 'hanunoo'\n self.emit(type, :script_hanunoo, text, ts-1, te)\n when 'hebr', 'hebrew'\n self.emit(type, :script_hebrew, text, ts-1, te)\n when 'hira', 'hiragana'\n self.emit(type, :script_hiragana, text, ts-1, te)\n when 'hmng', 'pahawhhmong'\n self.emit(type, :script_pahawh_hmong, text, ts-1, te)\n when 'hrkt', 'katakanaorhiragana'\n self.emit(type, :script_katakana_or_hiragana, text, ts-1, te)\n when 'ital', 'olditalic'\n self.emit(type, :script_old_italic, text, ts-1, te)\n when 'java', 'javanese'\n self.emit(type, :script_javanese, text, ts-1, te)\n when 'kali', 'kayahli'\n self.emit(type, :script_kayah_li, text, ts-1, te)\n when 'kana', 'katakana'\n self.emit(type, :script_katakana, text, ts-1, te)\n when 'khar', 'kharoshthi'\n self.emit(type, :script_kharoshthi, text, ts-1, te)\n when 'khmr', 'khmer'\n self.emit(type, :script_khmer, text, ts-1, te)\n when 'khoj', 'khojki'\n self.emit(type, :script_khojki, text, ts-1, te)\n when 'knda', 'kannada'\n self.emit(type, :script_kannada, text, ts-1, te)\n when 'kthi', 'kaithi'\n self.emit(type, :script_kaithi, text, ts-1, te)\n when 'lana', 'taitham'\n self.emit(type, :script_tai_tham, text, ts-1, te)\n when 'laoo', 'lao'\n self.emit(type, :script_lao, text, ts-1, te)\n when 'latn', 'latin'\n self.emit(type, :script_latin, text, ts-1, te)\n when 'lepc', 'lepcha'\n self.emit(type, :script_lepcha, text, ts-1, te)\n when 'limb', 'limbu'\n self.emit(type, :script_limbu, text, ts-1, te)\n when 'lina', 'lineara'\n self.emit(type, :script_linear_a, text, ts-1, te)\n when 'linb', 'linearb'\n self.emit(type, :script_linear_b, text, ts-1, te)\n when 'lisu'\n self.emit(type, :script_lisu, text, ts-1, te)\n when 'lyci', 'lycian'\n self.emit(type, :script_lycian, text, ts-1, te)\n when 'lydi', 'lydian'\n self.emit(type, :script_lydian, text, ts-1, te)\n when 'mlym', 'malayalam'\n self.emit(type, :script_malayalam, text, ts-1, te)\n when 'mahj', 'mahajani'\n self.emit(type, :script_mahajani, text, ts-1, te)\n when 'mand', 'mandaic'\n self.emit(type, :script_mandaic, text, ts-1, te)\n when 'mani', 'manichaean'\n self.emit(type, :script_manichaean, text, ts-1, te)\n when 'mend', 'mendekikakui'\n self.emit(type, :script_mende_kikakui, text, ts-1, te)\n when 'modi'\n self.emit(type, :script_modi, text, ts-1, te)\n when 'mong', 'mongolian'\n self.emit(type, :script_mongolian, text, ts-1, te)\n when 'mroo', 'mro'\n self.emit(type, :script_mro, text, ts-1, te)\n when 'mtei', 'meeteimayek'\n self.emit(type, :script_meetei_mayek, text, ts-1, te)\n when 'mymr', 'myanmar'\n self.emit(type, :script_myanmar, text, ts-1, te)\n when 'narb', 'oldnortharabian'\n self.emit(type, :script_old_north_arabian, text, ts-1, te)\n when 'nbat', 'nabataean'\n self.emit(type, :script_nabataean, text, ts-1, te)\n when 'nkoo', 'nko'\n self.emit(type, :script_nko, text, ts-1, te)\n when 'ogam', 'ogham'\n self.emit(type, :script_ogham, text, ts-1, te)\n when 'olck', 'olchiki'\n self.emit(type, :script_ol_chiki, text, ts-1, te)\n when 'orkh', 'oldturkic'\n self.emit(type, :script_old_turkic, text, ts-1, te)\n when 'orya', 'oriya'\n self.emit(type, :script_oriya, text, ts-1, te)\n when 'osma', 'osmanya'\n self.emit(type, :script_osmanya, text, ts-1, te)\n when 'palm', 'palmyrene'\n self.emit(type, :script_palmyrene, text, ts-1, te)\n when 'pauc', 'paucinhau'\n self.emit(type, :script_pau_cin_hau, text, ts-1, te)\n when 'perm', 'oldpermic'\n self.emit(type, :script_old_permic, text, ts-1, te)\n when 'phag', 'phagspa'\n self.emit(type, :script_phags_pa, text, ts-1, te)\n when 'phli', 'inscriptionalpahlavi'\n self.emit(type, :script_inscriptional_pahlavi, text, ts-1, te)\n when 'phlp', 'psalterpahlavi'\n self.emit(type, :script_psalter_pahlavi, text, ts-1, te)\n when 'phnx', 'phoenician'\n self.emit(type, :script_phoenician, text, ts-1, te)\n when 'prti', 'inscriptionalparthian'\n self.emit(type, :script_inscriptional_parthian, text, ts-1, te)\n when 'rjng', 'rejang'\n self.emit(type, :script_rejang, text, ts-1, te)\n when 'runr', 'runic'\n self.emit(type, :script_runic, text, ts-1, te)\n when 'samr', 'samaritan'\n self.emit(type, :script_samaritan, text, ts-1, te)\n when 'sarb', 'oldsoutharabian'\n self.emit(type, :script_old_south_arabian, text, ts-1, te)\n when 'saur', 'saurashtra'\n self.emit(type, :script_saurashtra, text, ts-1, te)\n when 'shaw', 'shavian'\n self.emit(type, :script_shavian, text, ts-1, te)\n when 'sidd', 'siddham'\n self.emit(type, :script_siddham, text, ts-1, te)\n when 'sind', 'khudawadi'\n self.emit(type, :script_khudawadi, text, ts-1, te)\n when 'sinh', 'sinhala'\n self.emit(type, :script_sinhala, text, ts-1, te)\n when 'sund', 'sundanese'\n self.emit(type, :script_sundanese, text, ts-1, te)\n when 'sylo', 'sylotinagri'\n self.emit(type, :script_syloti_nagri, text, ts-1, te)\n when 'syrc', 'syriac'\n self.emit(type, :script_syriac, text, ts-1, te)\n when 'tagb', 'tagbanwa'\n self.emit(type, :script_tagbanwa, text, ts-1, te)\n when 'tale', 'taile'\n self.emit(type, :script_tai_le, text, ts-1, te)\n when 'talu', 'newtailue'\n self.emit(type, :script_new_tai_lue, text, ts-1, te)\n when 'taml', 'tamil'\n self.emit(type, :script_tamil, text, ts-1, te)\n when 'tavt', 'taiviet'\n self.emit(type, :script_tai_viet, text, ts-1, te)\n when 'telu', 'telugu'\n self.emit(type, :script_telugu, text, ts-1, te)\n when 'tfng', 'tifinagh'\n self.emit(type, :script_tifinagh, text, ts-1, te)\n when 'tglg', 'tagalog'\n self.emit(type, :script_tagalog, text, ts-1, te)\n when 'thaa', 'thaana'\n self.emit(type, :script_thaana, text, ts-1, te)\n when 'thai'\n self.emit(type, :script_thai, text, ts-1, te)\n when 'tibt', 'tibetan'\n self.emit(type, :script_tibetan, text, ts-1, te)\n when 'tirh', 'tirhuta'\n self.emit(type, :script_tirhuta, text, ts-1, te)\n when 'ugar', 'ugaritic'\n self.emit(type, :script_ugaritic, text, ts-1, te)\n when 'vaii', 'vai'\n self.emit(type, :script_vai, text, ts-1, te)\n when 'wara', 'warangciti'\n self.emit(type, :script_warang_citi, text, ts-1, te)\n when 'xpeo', 'oldpersian'\n self.emit(type, :script_old_persian, text, ts-1, te)\n when 'xsux', 'cuneiform'\n self.emit(type, :script_cuneiform, text, ts-1, te)\n when 'yiii', 'yi'\n self.emit(type, :script_yi, text, ts-1, te)\n when 'zinh', 'inherited', 'qaai'\n self.emit(type, :script_inherited, text, ts-1, te)\n when 'zyyy', 'common'\n self.emit(type, :script_common, text, ts-1, te)\n when 'zzzz', 'unknown'\n self.emit(type, :script_unknown, text, ts-1, te)\n\n # Unicode blocks\n when 'inalphabeticpresentationforms'\n self.emit(type, :block_inalphabetic_presentation_forms, text, ts-1, te)\n when 'inalphabeticpresentationforms'\n self.emit(type, :block_inalphabetic_presentation_forms, text, ts-1, te)\n when 'inarabicpresentationforms-a'\n self.emit(type, :block_inarabic_presentation_forms_a, text, ts-1, te)\n when 'inarabicpresentationforms-b'\n self.emit(type, :block_inarabic_presentation_forms_b, text, ts-1, te)\n when 'inarabic'\n self.emit(type, :block_inarabic, text, ts-1, te)\n when 'inarmenian'\n self.emit(type, :block_inarmenian, text, ts-1, te)\n when 'inarrows'\n self.emit(type, :block_inarrows, text, ts-1, te)\n when 'inbasiclatin'\n self.emit(type, :block_inbasic_latin, text, ts-1, te)\n when 'inbengali'\n self.emit(type, :block_inbengali, text, ts-1, te)\n when 'inblockelements'\n self.emit(type, :block_inblock_elements, text, ts-1, te)\n when 'inbopomofoextended'\n self.emit(type, :block_inbopomofo_extended, text, ts-1, te)\n when 'inbopomofo'\n self.emit(type, :block_inbopomofo, text, ts-1, te)\n when 'inboxdrawing'\n self.emit(type, :block_inbox_drawing, text, ts-1, te)\n when 'inbraillepatterns'\n self.emit(type, :block_inbraille_patterns, text, ts-1, te)\n when 'inbuhid'\n self.emit(type, :block_inbuhid, text, ts-1, te)\n when 'incjkcompatibilityforms'\n self.emit(type, :block_incjk_compatibility_forms, text, ts-1, te)\n when 'incjkcompatibilityideographs'\n self.emit(type, :block_incjk_compatibility_ideographs, text, ts-1, te)\n when 'incjkcompatibility'\n self.emit(type, :block_incjk_compatibility, text, ts-1, te)\n when 'incjkradicalssupplement'\n self.emit(type, :block_incjk_radicals_supplement, text, ts-1, te)\n when 'incjksymbolsandpunctuation'\n self.emit(type, :block_incjk_symbols_and_punctuation, text, ts-1, te)\n when 'incjkunifiedideographsextensiona'\n self.emit(type, :block_incjk_unified_ideographs_extension_a, text, ts-1, te)\n when 'incjkunifiedideographs'\n self.emit(type, :block_incjk_unified_ideographs, text, ts-1, te)\n when 'incherokee'\n self.emit(type, :block_incherokee, text, ts-1, te)\n when 'incombiningdiacriticalmarksforsymbols'\n self.emit(type, :block_incombining_diacritical_marks_for_symbols, text, ts-1, te)\n when 'incombiningdiacriticalmarks'\n self.emit(type, :block_incombining_diacritical_marks, text, ts-1, te)\n when 'incombininghalfmarks'\n self.emit(type, :block_incombining_half_marks, text, ts-1, te)\n when 'incontrolpictures'\n self.emit(type, :block_incontrol_pictures, text, ts-1, te)\n when 'incurrencysymbols'\n self.emit(type, :block_incurrency_symbols, text, ts-1, te)\n when 'incyrillicsupplementary'\n self.emit(type, :block_incyrillic_supplementary, text, ts-1, te)\n when 'incyrillic'\n self.emit(type, :block_incyrillic, text, ts-1, te)\n when 'indevanagari'\n self.emit(type, :block_indevanagari, text, ts-1, te)\n when 'indingbats'\n self.emit(type, :block_indingbats, text, ts-1, te)\n when 'inenclosedalphanumerics'\n self.emit(type, :block_inenclosed_alphanumerics, text, ts-1, te)\n when 'inenclosedcjklettersandmonths'\n self.emit(type, :block_inenclosed_cjk_letters_and_months, text, ts-1, te)\n when 'inethiopic'\n self.emit(type, :block_inethiopic, text, ts-1, te)\n when 'ingeneralpunctuation'\n self.emit(type, :block_ingeneral_punctuation, text, ts-1, te)\n when 'ingeometricshapes'\n self.emit(type, :block_ingeometric_shapes, text, ts-1, te)\n when 'ingeorgian'\n self.emit(type, :block_ingeorgian, text, ts-1, te)\n when 'ingreekextended'\n self.emit(type, :block_ingreek_extended, text, ts-1, te)\n when 'ingreekandcoptic'\n self.emit(type, :block_ingreek_and_coptic, text, ts-1, te)\n when 'ingujarati'\n self.emit(type, :block_ingujarati, text, ts-1, te)\n when 'ingurmukhi'\n self.emit(type, :block_ingurmukhi, text, ts-1, te)\n when 'inhalfwidthandfullwidthforms'\n self.emit(type, :block_inhalfwidth_and_fullwidth_forms, text, ts-1, te)\n when 'inhangulcompatibilityjamo'\n self.emit(type, :block_inhangul_compatibility_jamo, text, ts-1, te)\n when 'inhanguljamo'\n self.emit(type, :block_inhangul_jamo, text, ts-1, te)\n when 'inhangulsyllables'\n self.emit(type, :block_inhangul_syllables, text, ts-1, te)\n when 'inhanunoo'\n self.emit(type, :block_inhanunoo, text, ts-1, te)\n when 'inhebrew'\n self.emit(type, :block_inhebrew, text, ts-1, te)\n when 'inhighprivateusesurrogates'\n self.emit(type, :block_inhigh_private_use_surrogates, text, ts-1, te)\n when 'inhighsurrogates'\n self.emit(type, :block_inhigh_surrogates, text, ts-1, te)\n when 'inhiragana'\n self.emit(type, :block_inhiragana, text, ts-1, te)\n when 'inipaextensions'\n self.emit(type, :block_inipa_extensions, text, ts-1, te)\n when 'inideographicdescriptioncharacters'\n self.emit(type, :block_inideographic_description_characters, text, ts-1, te)\n when 'inkanbun'\n self.emit(type, :block_inkanbun, text, ts-1, te)\n when 'inkangxiradicals'\n self.emit(type, :block_inkangxi_radicals, text, ts-1, te)\n when 'inkannada'\n self.emit(type, :block_inkannada, text, ts-1, te)\n when 'inkatakanaphoneticextensions'\n self.emit(type, :block_inkatakana_phonetic_extensions, text, ts-1, te)\n when 'inkatakana'\n self.emit(type, :block_inkatakana, text, ts-1, te)\n when 'inkhmersymbols'\n self.emit(type, :block_inkhmer_symbols, text, ts-1, te)\n when 'inkhmer'\n self.emit(type, :block_inkhmer, text, ts-1, te)\n when 'inlao'\n self.emit(type, :block_inlao, text, ts-1, te)\n when 'inlatin-1supplement'\n self.emit(type, :block_inlatin_1_supplement, text, ts-1, te)\n when 'inlatinextended-a'\n self.emit(type, :block_inlatin_extended_a, text, ts-1, te)\n when 'inlatinextended-b'\n self.emit(type, :block_inlatin_extended_b, text, ts-1, te)\n when 'inlatinextendedadditional'\n self.emit(type, :block_inlatin_extended_additional, text, ts-1, te)\n when 'inletterlikesymbols'\n self.emit(type, :block_inletterlike_symbols, text, ts-1, te)\n when 'inlimbu'\n self.emit(type, :block_inlimbu, text, ts-1, te)\n when 'inlowsurrogates'\n self.emit(type, :block_inlow_surrogates, text, ts-1, te)\n when 'inmalayalam'\n self.emit(type, :block_inmalayalam, text, ts-1, te)\n when 'inmathematicaloperators'\n self.emit(type, :block_inmathematical_operators, text, ts-1, te)\n when 'inmiscellaneousmathematicalsymbols-a'\n self.emit(type, :block_inmiscellaneous_mathematical_symbols_a, text, ts-1, te)\n when 'inmiscellaneousmathematicalsymbols-b'\n self.emit(type, :block_inmiscellaneous_mathematical_symbols_b, text, ts-1, te)\n when 'inmiscellaneoussymbolsandarrows'\n self.emit(type, :block_inmiscellaneous_symbols_and_arrows, text, ts-1, te)\n when 'inmiscellaneoussymbols'\n self.emit(type, :block_inmiscellaneous_symbols, text, ts-1, te)\n when 'inmiscellaneoustechnical'\n self.emit(type, :block_inmiscellaneous_technical, text, ts-1, te)\n when 'inmongolian'\n self.emit(type, :block_inmongolian, text, ts-1, te)\n when 'inmyanmar'\n self.emit(type, :block_inmyanmar, text, ts-1, te)\n when 'innumberforms'\n self.emit(type, :block_innumber_forms, text, ts-1, te)\n when 'inogham'\n self.emit(type, :block_inogham, text, ts-1, te)\n when 'inopticalcharacterrecognition'\n self.emit(type, :block_inoptical_character_recognition, text, ts-1, te)\n when 'inoriya'\n self.emit(type, :block_inoriya, text, ts-1, te)\n when 'inphoneticextensions'\n self.emit(type, :block_inphonetic_extensions, text, ts-1, te)\n when 'inprivateusearea'\n self.emit(type, :block_inprivate_use_area, text, ts-1, te)\n when 'inrunic'\n self.emit(type, :block_inrunic, text, ts-1, te)\n when 'insinhala'\n self.emit(type, :block_insinhala, text, ts-1, te)\n when 'insmallformvariants'\n self.emit(type, :block_insmall_form_variants, text, ts-1, te)\n when 'inspacingmodifierletters'\n self.emit(type, :block_inspacing_modifier_letters, text, ts-1, te)\n when 'inspecials'\n self.emit(type, :block_inspecials, text, ts-1, te)\n when 'insuperscriptsandsubscripts'\n self.emit(type, :block_insuperscripts_and_subscripts, text, ts-1, te)\n when 'insupplementalarrows-a'\n self.emit(type, :block_insupplemental_arrows_a, text, ts-1, te)\n when 'insupplementalarrows-b'\n self.emit(type, :block_insupplemental_arrows_b, text, ts-1, te)\n when 'insupplementalmathematicaloperators'\n self.emit(type, :block_insupplemental_mathematical_operators, text, ts-1, te)\n when 'insyriac'\n self.emit(type, :block_insyriac, text, ts-1, te)\n when 'intagalog'\n self.emit(type, :block_intagalog, text, ts-1, te)\n when 'intagbanwa'\n self.emit(type, :block_intagbanwa, text, ts-1, te)\n when 'intaile'\n self.emit(type, :block_intai_le, text, ts-1, te)\n when 'intamil'\n self.emit(type, :block_intamil, text, ts-1, te)\n when 'intelugu'\n self.emit(type, :block_intelugu, text, ts-1, te)\n when 'inthaana'\n self.emit(type, :block_inthaana, text, ts-1, te)\n when 'inthai'\n self.emit(type, :block_inthai, text, ts-1, te)\n when 'intibetan'\n self.emit(type, :block_intibetan, text, ts-1, te)\n when 'inunifiedcanadianaboriginalsyllabics'\n self.emit(type, :block_inunified_canadian_aboriginal_syllabics, text, ts-1, te)\n when 'invariationselectors'\n self.emit(type, :block_invariation_selectors, text, ts-1, te)\n when 'inyiradicals'\n self.emit(type, :block_inyi_radicals, text, ts-1, te)\n when 'inyisyllables'\n self.emit(type, :block_inyi_syllables, text, ts-1, te)\n when 'inyijinghexagramsymbols'\n self.emit(type, :block_inyijing_hexagram_symbols, text, ts-1, te)\n\n else\n # Should this really be an error? Or would emitting\n # an :unknown for the property be better?\n #\n # self.emit(type, :unknown, text, ts-1, te)\n\n raise UnknownUnicodePropertyError.new(name)\n end\n\n fret;\n };\n *|;\n}%%\n","old_contents":"%%{\n machine re_property;\n\n property_char = [pP];\n\n # Property names are being treated as case-insensitive, but it is not clear\n # yet if this applies to all flavors and in all encodings. A bug has just\n # been filed against ruby regarding this issue, see:\n # http:\/\/redmine.ruby-lang.org\/issues\/show\/4014\n property_name_unicode = 'alnum'i | 'alpha'i | 'any'i | 'ascii'i | 'blank'i |\n 'cntrl'i | 'digit'i | 'graph'i | 'lower'i | 'print'i |\n 'punct'i | 'space'i | 'upper'i | 'word'i | 'xdigit'i;\n\n property_name_posix = 'any'i | 'assigned'i | 'newline'i;\n\n property_name = property_name_unicode | property_name_posix;\n\n category_letter = [Ll] . [ultmo]?;\n category_mark = [Mm] . [nce]?;\n category_number = [Nn] . [dlo]?;\n category_punctuation = [Pp] . [cdseifo]?;\n category_symbol = [Ss] . [mcko]?;\n category_separator = [Zz] . [slp]?;\n category_codepoint = [Cc] . [cfson]?;\n\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n property_derived = 'math'i | 'alphabetic'i |\n 'lowercase'i | 'uppercase'i |\n 'id_start'i | 'id_continue'i |\n 'xid_start'i | 'xid_continue'i |\n 'grapheme_base'i | 'grapheme_extend'i |\n 'default_ignorable_code_point'i;\n\n property_age = 'age=1.1'i | 'age=2.0'i | 'age=2.1'i |\n 'age=3.0'i | 'age=3.1'i | 'age=3.2'i |\n 'age=4.0'i | 'age=4.1'i | 'age=5.0'i |\n 'age=5.1'i | 'age=5.2'i | 'age=6.0'i |\n 'age=6.1'i | 'age=6.2'i | 'age=6.3'i |\n 'age=7.0'i;\n\n property_script = (alpha | space | '_')+; # everything else\n\n property_sequence = property_char . '{' . '^'? (\n property_name | general_category |\n property_age | property_derived |\n property_script\n ) . '}';\n\n action premature_property_end {\n raise PrematureEndError.new('unicode property')\n }\n\n # Unicode properties scanner\n # --------------------------------------------------------------------------\n unicode_property := |*\n\n property_sequence < eof(premature_property_end) {\n text = text(data, ts, te, 1).first\n if in_set\n type = :set\n else\n type = text[1,1] == 'p' ? :property : :nonproperty\n end\n\n name = data[ts+2..te-2].pack('c*').gsub(\/[\\s_]\/,'').downcase\n if name[0].chr == '^'\n name = name[1..-1]\n type = :nonproperty\n end\n\n case name\n # Named\n when 'alnum'\n self.emit(type, :alnum, text, ts-1, te)\n when 'alpha'\n self.emit(type, :alpha, text, ts-1, te)\n when 'ascii'\n self.emit(type, :ascii, text, ts-1, te)\n when 'blank'\n self.emit(type, :blank, text, ts-1, te)\n when 'cntrl'\n self.emit(type, :cntrl, text, ts-1, te)\n when 'digit'\n self.emit(type, :digit, text, ts-1, te)\n when 'graph'\n self.emit(type, :graph, text, ts-1, te)\n when 'lower'\n self.emit(type, :lower, text, ts-1, te)\n when 'print'\n self.emit(type, :print, text, ts-1, te)\n when 'punct'\n self.emit(type, :punct, text, ts-1, te)\n when 'space'\n self.emit(type, :space, text, ts-1, te)\n when 'upper'\n self.emit(type, :upper, text, ts-1, te)\n when 'xdigit'\n self.emit(type, :xdigit, text, ts-1, te)\n\n when 'any'\n self.emit(type, :any, text, ts-1, te)\n when 'assigned'\n self.emit(type, :assigned, text, ts-1, te)\n when 'newline'\n self.emit(type, :newline, text, ts-1, te)\n when 'word'\n self.emit(type, :word, text, ts-1, te)\n\n # Letters\n when 'l', 'letter'\n self.emit(type, :letter_any, text, ts-1, te)\n when 'lu', 'uppercaseletter'\n self.emit(type, :letter_uppercase, text, ts-1, te)\n when 'll', 'lowercaseletter'\n self.emit(type, :letter_lowercase, text, ts-1, te)\n when 'lt', 'titlecaseletter'\n self.emit(type, :letter_titlecase, text, ts-1, te)\n when 'lm', 'modifierletter'\n self.emit(type, :letter_modifier, text, ts-1, te)\n when 'lo', 'otherletter'\n self.emit(type, :letter_other, text, ts-1, te)\n\n # Marks\n when 'm', 'mark'\n self.emit(type, :mark_any, text, ts-1, te)\n when 'mn', 'nonspacingmark'\n self.emit(type, :mark_nonspacing, text, ts-1, te)\n when 'mc', 'spacingmark'\n self.emit(type, :mark_spacing, text, ts-1, te)\n when 'me', 'enclosingmark'\n self.emit(type, :mark_enclosing, text, ts-1, te)\n\n # Numbers\n when 'n', 'number'\n self.emit(type, :number_any, text, ts-1, te)\n when 'nd', 'decimalnumber'\n self.emit(type, :number_decimal, text, ts-1, te)\n when 'nl', 'letternumber'\n self.emit(type, :number_letter, text, ts-1, te)\n when 'no', 'othernumber'\n self.emit(type, :number_other, text, ts-1, te)\n\n # Punctuation\n when 'p', 'punctuation'\n self.emit(type, :punct_any, text, ts-1, te)\n when 'pc', 'connectorpunctuation'\n self.emit(type, :punct_connector, text, ts-1, te)\n when 'pd', 'dashpunctuation'\n self.emit(type, :punct_dash, text, ts-1, te)\n when 'ps', 'openpunctuation'\n self.emit(type, :punct_open, text, ts-1, te)\n when 'pe', 'closepunctuation'\n self.emit(type, :punct_close, text, ts-1, te)\n when 'pi', 'initialpunctuation'\n self.emit(type, :punct_initial, text, ts-1, te)\n when 'pf', 'finalpunctuation'\n self.emit(type, :punct_final, text, ts-1, te)\n when 'po', 'otherpunctuation'\n self.emit(type, :punct_other, text, ts-1, te)\n\n # Symbols\n when 's', 'symbol'\n self.emit(type, :symbol_any, text, ts-1, te)\n when 'sm', 'mathsymbol'\n self.emit(type, :symbol_math, text, ts-1, te)\n when 'sc', 'currencysymbol'\n self.emit(type, :symbol_currency, text, ts-1, te)\n when 'sk', 'modifiersymbol'\n self.emit(type, :symbol_modifier, text, ts-1, te)\n when 'so', 'othersymbol'\n self.emit(type, :symbol_other, text, ts-1, te)\n\n # Separators\n when 'z', 'separator'\n self.emit(type, :separator_any, text, ts-1, te)\n when 'zs', 'spaceseparator'\n self.emit(type, :separator_space, text, ts-1, te)\n when 'zl', 'lineseparator'\n self.emit(type, :separator_line, text, ts-1, te)\n when 'zp', 'paragraphseparator'\n self.emit(type, :separator_para, text, ts-1, te)\n\n # Codepoints\n when 'c', 'other'\n self.emit(type, :other, text, ts-1, te)\n when 'cc', 'control'\n self.emit(type, :control, text, ts-1, te)\n when 'cf', 'format'\n self.emit(type, :format, text, ts-1, te)\n when 'cs', 'surrogate'\n self.emit(type, :surrogate, text, ts-1, te)\n when 'co', 'privateuse'\n self.emit(type, :private_use, text, ts-1, te)\n when 'cn', 'unassigned'\n self.emit(type, :unassigned, text, ts-1, te)\n\n # Age\n when 'age=1.1'\n self.emit(type, :age_1_1, text, ts-1, te)\n when 'age=2.0'\n self.emit(type, :age_2_0, text, ts-1, te)\n when 'age=2.1'\n self.emit(type, :age_2_1, text, ts-1, te)\n when 'age=3.0'\n self.emit(type, :age_3_0, text, ts-1, te)\n when 'age=3.1'\n self.emit(type, :age_3_1, text, ts-1, te)\n when 'age=3.2'\n self.emit(type, :age_3_2, text, ts-1, te)\n when 'age=4.0'\n self.emit(type, :age_4_0, text, ts-1, te)\n when 'age=4.1'\n self.emit(type, :age_4_1, text, ts-1, te)\n when 'age=5.0'\n self.emit(type, :age_5_0, text, ts-1, te)\n when 'age=5.1'\n self.emit(type, :age_5_1, text, ts-1, te)\n when 'age=5.2'\n self.emit(type, :age_5_2, text, ts-1, te)\n when 'age=6.0'\n self.emit(type, :age_6_0, text, ts-1, te)\n when 'age=6.1'\n self.emit(type, :age_6_1, text, ts-1, te)\n when 'age=6.2'\n self.emit(type, :age_6_2, text, ts-1, te)\n when 'age=6.3'\n self.emit(type, :age_6_3, text, ts-1, te)\n when 'age=7.0'\n self.emit(type, :age_7_0, text, ts-1, te)\n\n # Derived Properties\n when 'ahex', 'asciihexdigit'\n self.emit(type, :ascii_hex, text, ts-1, te)\n when 'alphabetic'\n self.emit(type, :alphabetic, text, ts-1, te)\n when 'cased'\n self.emit(type, :cased, text, ts-1, te)\n when 'cwcf', 'changeswhencasefolded'\n self.emit(type, :changes_when_casefolded, text, ts-1, te)\n when 'cwcm', 'changeswhencasemapped'\n self.emit(type, :changes_when_casemapped, text, ts-1, te)\n when 'cwl', 'changeswhenlowercased'\n self.emit(type, :changes_when_lowercased, text, ts-1, te)\n when 'cwt', 'changeswhentitlecased'\n self.emit(type, :changes_when_titlecased, text, ts-1, te)\n when 'cwu', 'changeswhenuppercased'\n self.emit(type, :changes_when_uppercased, text, ts-1, te)\n when 'ci', 'caseignorable'\n self.emit(type, :case_ignorable, text, ts-1, te)\n when 'bidic', 'bidicontrol'\n self.emit(type, :bidi_control, text, ts-1, te)\n when 'dash'\n self.emit(type, :dash, text, ts-1, te)\n when 'dep', 'deprecated'\n self.emit(type, :deprecated, text, ts-1, te)\n when 'di', 'defaultignorablecodepoint'\n self.emit(type, :default_ignorable_cp, text, ts-1, te)\n when 'dia', 'diacritic'\n self.emit(type, :diacritic, text, ts-1, te)\n when 'ext', 'extender'\n self.emit(type, :extender, text, ts-1, te)\n when 'grbase', 'graphemebase'\n self.emit(type, :grapheme_base, text, ts-1, te)\n when 'grext', 'graphemeextend'\n self.emit(type, :grapheme_extend, text, ts-1, te)\n when 'grlink', 'graphemelink' # NOTE: deprecated as of Unicode 5.0\n self.emit(type, :grapheme_link, text, ts-1, te)\n when 'hex', 'hexdigit'\n self.emit(type, :hex_digit, text, ts-1, te)\n when 'hyphen' # NOTE: deprecated as of Unicode 6.0\n self.emit(type, :hyphen, text, ts-1, te)\n when 'idc', 'idcontinue'\n self.emit(type, :id_continue, text, ts-1, te)\n when 'ideo', 'ideographic'\n self.emit(type, :ideographic, text, ts-1, te)\n when 'ids', 'idstart'\n self.emit(type, :id_start, text, ts-1, te)\n when 'idsb', 'idsbinaryoperator'\n self.emit(type, :ids_binary_op, text, ts-1, te)\n when 'idst', 'idstrinaryoperator'\n self.emit(type, :ids_trinary_op, text, ts-1, te)\n when 'joinc', 'joincontrol'\n self.emit(type, :join_control, text, ts-1, te)\n when 'loe', 'logicalorderexception'\n self.emit(type, :logical_order_exception, text, ts-1, te)\n when 'lowercase'\n self.emit(type, :lowercase, text, ts-1, te)\n when 'math'\n self.emit(type, :math, text, ts-1, te)\n when 'nchar', 'noncharactercodepoint'\n self.emit(type, :non_character_cp, text, ts-1, te)\n when 'oalpha', 'otheralphabetic'\n self.emit(type, :other_alphabetic, text, ts-1, te)\n when 'odi', 'otherdefaultignorablecodepoint'\n self.emit(type, :other_default_ignorable_cp, text, ts-1, te)\n when 'ogrext', 'othergraphemeextend'\n self.emit(type, :other_grapheme_extended, text, ts-1, te)\n when 'oidc', 'otheridcontinue'\n self.emit(type, :other_id_continue, text, ts-1, te)\n when 'oids', 'otheridstart'\n self.emit(type, :other_id_start, text, ts-1, te)\n when 'olower', 'otherlowercase'\n self.emit(type, :other_lowercase, text, ts-1, te)\n when 'omath', 'othermath'\n self.emit(type, :other_math, text, ts-1, te)\n when 'oupper', 'otheruppercase'\n self.emit(type, :other_uppercase, text, ts-1, te)\n when 'patsyn', 'patternsyntax'\n self.emit(type, :pattern_syntax, text, ts-1, te)\n when 'patws', 'patternwhitespace'\n self.emit(type, :pattern_whitespace, text, ts-1, te)\n when 'qmark', 'quotationmark'\n self.emit(type, :quotation_mark, text, ts-1, te)\n when 'radical'\n self.emit(type, :radical, text, ts-1, te)\n when 'sd', 'softdotted'\n self.emit(type, :soft_dotted, text, ts-1, te)\n when 'sterm'\n self.emit(type, :sentence_terminal, text, ts-1, te)\n when 'term', 'terminalpunctuation'\n self.emit(type, :terminal_punctuation, text, ts-1, te)\n when 'uideo', 'unifiedideograph'\n self.emit(type, :unified_ideograph, text, ts-1, te)\n when 'uppercase'\n self.emit(type, :uppercase, text, ts-1, te)\n when 'vs', 'variationselector'\n self.emit(type, :variation_selector, text, ts-1, te)\n when 'wspace', 'whitespace'\n self.emit(type, :whitespace, text, ts-1, te)\n when 'xids', 'xidstart'\n self.emit(type, :xid_start, text, ts-1, te)\n when 'xidc', 'xidcontinue'\n self.emit(type, :xid_continue, text, ts-1, te)\n\n # Scripts\n when 'aghb', 'caucasianalbanian'\n self.emit(type, :script_caucasian_albanian, text, ts-1, te)\n when 'arab', 'arabic'\n self.emit(type, :script_arabic, text, ts-1, te)\n when 'armi', 'imperialaramaic'\n self.emit(type, :script_imperial_aramaic, text, ts-1, te)\n when 'armn', 'armenian'\n self.emit(type, :script_armenian, text, ts-1, te)\n when 'avst', 'avestan'\n self.emit(type, :script_avestan, text, ts-1, te)\n when 'bali', 'balinese'\n self.emit(type, :script_balinese, text, ts-1, te)\n when 'bamu', 'bamum'\n self.emit(type, :script_bamum, text, ts-1, te)\n when 'bass', 'bassavah'\n self.emit(type, :script_bassa_vah, text, ts-1, te)\n when 'batk', 'batak'\n self.emit(type, :script_batak, text, ts-1, te)\n when 'beng', 'bengali'\n self.emit(type, :script_bengali, text, ts-1, te)\n when 'bopo', 'bopomofo'\n self.emit(type, :script_bopomofo, text, ts-1, te)\n when 'brah', 'brahmi'\n self.emit(type, :script_brahmi, text, ts-1, te)\n when 'brai', 'braille'\n self.emit(type, :script_braille, text, ts-1, te)\n when 'bugi', 'buginese'\n self.emit(type, :script_buginese, text, ts-1, te)\n when 'buhd', 'buhid'\n self.emit(type, :script_buhid, text, ts-1, te)\n when 'cans', 'canadianaboriginal'\n self.emit(type, :script_canadian_aboriginal, text, ts-1, te)\n when 'cari', 'carian'\n self.emit(type, :script_carian, text, ts-1, te)\n when 'cham'\n self.emit(type, :script_cham, text, ts-1, te)\n when 'cher', 'cherokee'\n self.emit(type, :script_cherokee, text, ts-1, te)\n when 'copt', 'coptic', 'qaac'\n self.emit(type, :script_coptic, text, ts-1, te)\n when 'cprt', 'cypriot'\n self.emit(type, :script_cypriot, text, ts-1, te)\n when 'cyrl', 'cyrillic'\n self.emit(type, :script_cyrillic, text, ts-1, te)\n when 'deva', 'devanagari'\n self.emit(type, :script_devanagari, text, ts-1, te)\n when 'dsrt', 'deseret'\n self.emit(type, :script_deseret, text, ts-1, te)\n when 'dupl', 'duployan'\n self.emit(type, :script_duployan, text, ts-1, te)\n when 'egyp', 'egyptianhieroglyphs'\n self.emit(type, :script_egyptian_hieroglyphs, text, ts-1, te)\n when 'elba', 'elbasan'\n self.emit(type, :script_elbasan, text, ts-1, te)\n when 'ethi', 'ethiopic'\n self.emit(type, :script_ethiopic, text, ts-1, te)\n when 'geor', 'georgian'\n self.emit(type, :script_georgian, text, ts-1, te)\n when 'glag', 'glagolitic'\n self.emit(type, :script_glagolitic, text, ts-1, te)\n when 'goth', 'gothic'\n self.emit(type, :script_gothic, text, ts-1, te)\n when 'gran', 'grantha'\n self.emit(type, :script_grantha, text, ts-1, te)\n when 'grek', 'greek'\n self.emit(type, :script_greek, text, ts-1, te)\n when 'gujr', 'gujarati'\n self.emit(type, :script_gujarati, text, ts-1, te)\n when 'guru', 'gurmukhi'\n self.emit(type, :script_gurmukhi, text, ts-1, te)\n when 'hang', 'hangul'\n self.emit(type, :script_hangul, text, ts-1, te)\n when 'hani', 'han'\n self.emit(type, :script_han, text, ts-1, te)\n when 'hano', 'hanunoo'\n self.emit(type, :script_hanunoo, text, ts-1, te)\n when 'hebr', 'hebrew'\n self.emit(type, :script_hebrew, text, ts-1, te)\n when 'hira', 'hiragana'\n self.emit(type, :script_hiragana, text, ts-1, te)\n when 'hmng', 'pahawhhmong'\n self.emit(type, :script_pahawh_hmong, text, ts-1, te)\n when 'hrkt', 'katakanaorhiragana'\n self.emit(type, :script_katakana_or_hiragana, text, ts-1, te)\n when 'ital', 'olditalic'\n self.emit(type, :script_old_italic, text, ts-1, te)\n when 'java', 'javanese'\n self.emit(type, :script_javanese, text, ts-1, te)\n when 'kali', 'kayahli'\n self.emit(type, :script_kayah_li, text, ts-1, te)\n when 'kana', 'katakana'\n self.emit(type, :script_katakana, text, ts-1, te)\n when 'khar', 'kharoshthi'\n self.emit(type, :script_kharoshthi, text, ts-1, te)\n when 'khmr', 'khmer'\n self.emit(type, :script_khmer, text, ts-1, te)\n when 'khoj', 'khojki'\n self.emit(type, :script_khojki, text, ts-1, te)\n when 'knda', 'kannada'\n self.emit(type, :script_kannada, text, ts-1, te)\n when 'kthi', 'kaithi'\n self.emit(type, :script_kaithi, text, ts-1, te)\n when 'lana', 'taitham'\n self.emit(type, :script_tai_tham, text, ts-1, te)\n when 'laoo', 'lao'\n self.emit(type, :script_lao, text, ts-1, te)\n when 'latn', 'latin'\n self.emit(type, :script_latin, text, ts-1, te)\n when 'lepc', 'lepcha'\n self.emit(type, :script_lepcha, text, ts-1, te)\n when 'limb', 'limbu'\n self.emit(type, :script_limbu, text, ts-1, te)\n when 'lina', 'lineara'\n self.emit(type, :script_linear_a, text, ts-1, te)\n when 'linb', 'linearb'\n self.emit(type, :script_linear_b, text, ts-1, te)\n when 'lisu'\n self.emit(type, :script_lisu, text, ts-1, te)\n when 'lyci', 'lycian'\n self.emit(type, :script_lycian, text, ts-1, te)\n when 'lydi', 'lydian'\n self.emit(type, :script_lydian, text, ts-1, te)\n when 'mlym', 'malayalam'\n self.emit(type, :script_malayalam, text, ts-1, te)\n when 'mahj', 'mahajani'\n self.emit(type, :script_mahajani, text, ts-1, te)\n when 'mand', 'mandaic'\n self.emit(type, :script_mandaic, text, ts-1, te)\n when 'mani', 'manichaean'\n self.emit(type, :script_manichaean, text, ts-1, te)\n when 'mend', 'mendekikakui'\n self.emit(type, :script_mende_kikakui, text, ts-1, te)\n when 'modi'\n self.emit(type, :script_modi, text, ts-1, te)\n when 'mong', 'mongolian'\n self.emit(type, :script_mongolian, text, ts-1, te)\n when 'mroo', 'mro'\n self.emit(type, :script_mro, text, ts-1, te)\n when 'mtei', 'meeteimayek'\n self.emit(type, :script_meetei_mayek, text, ts-1, te)\n when 'mymr', 'myanmar'\n self.emit(type, :script_myanmar, text, ts-1, te)\n when 'narb', 'oldnortharabian'\n self.emit(type, :script_old_north_arabian, text, ts-1, te)\n when 'nbat', 'nabataean'\n self.emit(type, :script_nabataean, text, ts-1, te)\n when 'nkoo', 'nko'\n self.emit(type, :script_nko, text, ts-1, te)\n when 'ogam', 'ogham'\n self.emit(type, :script_ogham, text, ts-1, te)\n when 'olck', 'olchiki'\n self.emit(type, :script_ol_chiki, text, ts-1, te)\n when 'orkh', 'oldturkic'\n self.emit(type, :script_old_turkic, text, ts-1, te)\n when 'orya', 'oriya'\n self.emit(type, :script_oriya, text, ts-1, te)\n when 'osma', 'osmanya'\n self.emit(type, :script_osmanya, text, ts-1, te)\n when 'palm', 'palmyrene'\n self.emit(type, :script_palmyrene, text, ts-1, te)\n when 'pauc', 'paucinhau'\n self.emit(type, :script_pau_cin_hau, text, ts-1, te)\n when 'perm', 'oldpermic'\n self.emit(type, :script_old_permic, text, ts-1, te)\n when 'phag', 'phagspa'\n self.emit(type, :script_phags_pa, text, ts-1, te)\n when 'phli', 'inscriptionalpahlavi'\n self.emit(type, :script_inscriptional_pahlavi, text, ts-1, te)\n when 'phlp', 'psalterpahlavi'\n self.emit(type, :script_psalter_pahlavi, text, ts-1, te)\n when 'phnx', 'phoenician'\n self.emit(type, :script_phoenician, text, ts-1, te)\n when 'prti', 'inscriptionalparthian'\n self.emit(type, :script_inscriptional_parthian, text, ts-1, te)\n when 'rjng', 'rejang'\n self.emit(type, :script_rejang, text, ts-1, te)\n when 'runr', 'runic'\n self.emit(type, :script_runic, text, ts-1, te)\n when 'samr', 'samaritan'\n self.emit(type, :script_samaritan, text, ts-1, te)\n when 'sarb', 'oldsoutharabian'\n self.emit(type, :script_old_south_arabian, text, ts-1, te)\n when 'saur', 'saurashtra'\n self.emit(type, :script_saurashtra, text, ts-1, te)\n when 'shaw', 'shavian'\n self.emit(type, :script_shavian, text, ts-1, te)\n when 'sidd', 'siddham'\n self.emit(type, :script_siddham, text, ts-1, te)\n when 'sind', 'khudawadi'\n self.emit(type, :script_khudawadi, text, ts-1, te)\n when 'sinh', 'sinhala'\n self.emit(type, :script_sinhala, text, ts-1, te)\n when 'sund', 'sundanese'\n self.emit(type, :script_sundanese, text, ts-1, te)\n when 'sylo', 'sylotinagri'\n self.emit(type, :script_syloti_nagri, text, ts-1, te)\n when 'syrc', 'syriac'\n self.emit(type, :script_syriac, text, ts-1, te)\n when 'tagb', 'tagbanwa'\n self.emit(type, :script_tagbanwa, text, ts-1, te)\n when 'tale', 'taile'\n self.emit(type, :script_tai_le, text, ts-1, te)\n when 'talu', 'newtailue'\n self.emit(type, :script_new_tai_lue, text, ts-1, te)\n when 'taml', 'tamil'\n self.emit(type, :script_tamil, text, ts-1, te)\n when 'tavt', 'taiviet'\n self.emit(type, :script_tai_viet, text, ts-1, te)\n when 'telu', 'telugu'\n self.emit(type, :script_telugu, text, ts-1, te)\n when 'tfng', 'tifinagh'\n self.emit(type, :script_tifinagh, text, ts-1, te)\n when 'tglg', 'tagalog'\n self.emit(type, :script_tagalog, text, ts-1, te)\n when 'thaa', 'thaana'\n self.emit(type, :script_thaana, text, ts-1, te)\n when 'thai'\n self.emit(type, :script_thai, text, ts-1, te)\n when 'tibt', 'tibetan'\n self.emit(type, :script_tibetan, text, ts-1, te)\n when 'tirh', 'tirhuta'\n self.emit(type, :script_tirhuta, text, ts-1, te)\n when 'ugar', 'ugaritic'\n self.emit(type, :script_ugaritic, text, ts-1, te)\n when 'vaii', 'vai'\n self.emit(type, :script_vai, text, ts-1, te)\n when 'wara', 'warangciti'\n self.emit(type, :script_warang_citi, text, ts-1, te)\n when 'xpeo', 'oldpersian'\n self.emit(type, :script_old_persian, text, ts-1, te)\n when 'xsux', 'cuneiform'\n self.emit(type, :script_cuneiform, text, ts-1, te)\n when 'yiii', 'yi'\n self.emit(type, :script_yi, text, ts-1, te)\n when 'zinh', 'inherited', 'qaai'\n self.emit(type, :script_inherited, text, ts-1, te)\n when 'zyyy', 'common'\n self.emit(type, :script_common, text, ts-1, te)\n when 'zzzz', 'unknown'\n self.emit(type, :script_unknown, text, ts-1, te)\n\n # Unicode blocks\n when 'inalphabetic_presentation_forms'\n self.emit(type, :block_inalphabetic_presentation_forms, text, ts-1, te)\n when 'inalphabeticpresentationforms'\n self.emit(type, :block_inalphabetic_presentation_forms, text, ts-1, te)\n when 'inarabicpresentationforms-a'\n self.emit(type, :block_inarabic_presentation_forms_a, text, ts-1, te)\n when 'inarabicpresentationforms-b'\n self.emit(type, :block_inarabic_presentation_forms_b, text, ts-1, te)\n when 'inarabic'\n self.emit(type, :block_inarabic, text, ts-1, te)\n when 'inarmenian'\n self.emit(type, :block_inarmenian, text, ts-1, te)\n when 'inarrows'\n self.emit(type, :block_inarrows, text, ts-1, te)\n when 'inbasiclatin'\n self.emit(type, :block_inbasic_latin, text, ts-1, te)\n when 'inbengali'\n self.emit(type, :block_inbengali, text, ts-1, te)\n when 'inblockelements'\n self.emit(type, :block_inblock_elements, text, ts-1, te)\n when 'inbopomofoextended'\n self.emit(type, :block_inbopomofo_extended, text, ts-1, te)\n when 'inbopomofo'\n self.emit(type, :block_inbopomofo, text, ts-1, te)\n when 'inboxdrawing'\n self.emit(type, :block_inbox_drawing, text, ts-1, te)\n when 'inbraillepatterns'\n self.emit(type, :block_inbraille_patterns, text, ts-1, te)\n when 'inbuhid'\n self.emit(type, :block_inbuhid, text, ts-1, te)\n when 'incjkcompatibilityforms'\n self.emit(type, :block_incjk_compatibility_forms, text, ts-1, te)\n when 'incjkcompatibilityideographs'\n self.emit(type, :block_incjk_compatibility_ideographs, text, ts-1, te)\n when 'incjkcompatibility'\n self.emit(type, :block_incjk_compatibility, text, ts-1, te)\n when 'incjkradicalssupplement'\n self.emit(type, :block_incjk_radicals_supplement, text, ts-1, te)\n when 'incjksymbolsandpunctuation'\n self.emit(type, :block_incjk_symbols_and_punctuation, text, ts-1, te)\n when 'incjkunifiedideographsextensiona'\n self.emit(type, :block_incjk_unified_ideographs_extension_a, text, ts-1, te)\n when 'incjkunifiedideographs'\n self.emit(type, :block_incjk_unified_ideographs, text, ts-1, te)\n when 'incherokee'\n self.emit(type, :block_incherokee, text, ts-1, te)\n when 'incombiningdiacriticalmarksforsymbols'\n self.emit(type, :block_incombining_diacritical_marks_for_symbols, text, ts-1, te)\n when 'incombiningdiacriticalmarks'\n self.emit(type, :block_incombining_diacritical_marks, text, ts-1, te)\n when 'incombininghalfmarks'\n self.emit(type, :block_incombining_half_marks, text, ts-1, te)\n when 'incontrolpictures'\n self.emit(type, :block_incontrol_pictures, text, ts-1, te)\n when 'incurrencysymbols'\n self.emit(type, :block_incurrency_symbols, text, ts-1, te)\n when 'incyrillicsupplementary'\n self.emit(type, :block_incyrillic_supplementary, text, ts-1, te)\n when 'incyrillic'\n self.emit(type, :block_incyrillic, text, ts-1, te)\n when 'indevanagari'\n self.emit(type, :block_indevanagari, text, ts-1, te)\n when 'indingbats'\n self.emit(type, :block_indingbats, text, ts-1, te)\n when 'inenclosedalphanumerics'\n self.emit(type, :block_inenclosed_alphanumerics, text, ts-1, te)\n when 'inenclosedcjklettersandmonths'\n self.emit(type, :block_inenclosed_cjk_letters_and_months, text, ts-1, te)\n when 'inethiopic'\n self.emit(type, :block_inethiopic, text, ts-1, te)\n when 'ingeneralpunctuation'\n self.emit(type, :block_ingeneral_punctuation, text, ts-1, te)\n when 'ingeometricshapes'\n self.emit(type, :block_ingeometric_shapes, text, ts-1, te)\n when 'ingeorgian'\n self.emit(type, :block_ingeorgian, text, ts-1, te)\n when 'ingreekextended'\n self.emit(type, :block_ingreek_extended, text, ts-1, te)\n when 'ingreekandcoptic'\n self.emit(type, :block_ingreek_and_coptic, text, ts-1, te)\n when 'ingujarati'\n self.emit(type, :block_ingujarati, text, ts-1, te)\n when 'ingurmukhi'\n self.emit(type, :block_ingurmukhi, text, ts-1, te)\n when 'inhalfwidthandfullwidthforms'\n self.emit(type, :block_inhalfwidth_and_fullwidth_forms, text, ts-1, te)\n when 'inhangulcompatibilityjamo'\n self.emit(type, :block_inhangul_compatibility_jamo, text, ts-1, te)\n when 'inhanguljamo'\n self.emit(type, :block_inhangul_jamo, text, ts-1, te)\n when 'inhangulsyllables'\n self.emit(type, :block_inhangul_syllables, text, ts-1, te)\n when 'inhanunoo'\n self.emit(type, :block_inhanunoo, text, ts-1, te)\n when 'inhebrew'\n self.emit(type, :block_inhebrew, text, ts-1, te)\n when 'inhighprivateusesurrogates'\n self.emit(type, :block_inhigh_private_use_surrogates, text, ts-1, te)\n when 'inhighsurrogates'\n self.emit(type, :block_inhigh_surrogates, text, ts-1, te)\n when 'inhiragana'\n self.emit(type, :block_inhiragana, text, ts-1, te)\n when 'inipaextensions'\n self.emit(type, :block_inipa_extensions, text, ts-1, te)\n when 'inideographicdescriptioncharacters'\n self.emit(type, :block_inideographic_description_characters, text, ts-1, te)\n when 'inkanbun'\n self.emit(type, :block_inkanbun, text, ts-1, te)\n when 'inkangxiradicals'\n self.emit(type, :block_inkangxi_radicals, text, ts-1, te)\n when 'inkannada'\n self.emit(type, :block_inkannada, text, ts-1, te)\n when 'inkatakanaphoneticextensions'\n self.emit(type, :block_inkatakana_phonetic_extensions, text, ts-1, te)\n when 'inkatakana'\n self.emit(type, :block_inkatakana, text, ts-1, te)\n when 'inkhmersymbols'\n self.emit(type, :block_inkhmer_symbols, text, ts-1, te)\n when 'inkhmer'\n self.emit(type, :block_inkhmer, text, ts-1, te)\n when 'inlao'\n self.emit(type, :block_inlao, text, ts-1, te)\n when 'inlatin-1supplement'\n self.emit(type, :block_inlatin_1_supplement, text, ts-1, te)\n when 'inlatinextended-a'\n self.emit(type, :block_inlatin_extended_a, text, ts-1, te)\n when 'inlatinextended-b'\n self.emit(type, :block_inlatin_extended_b, text, ts-1, te)\n when 'inlatinextendedadditional'\n self.emit(type, :block_inlatin_extended_additional, text, ts-1, te)\n when 'inletterlikesymbols'\n self.emit(type, :block_inletterlike_symbols, text, ts-1, te)\n when 'inlimbu'\n self.emit(type, :block_inlimbu, text, ts-1, te)\n when 'inlowsurrogates'\n self.emit(type, :block_inlow_surrogates, text, ts-1, te)\n when 'inmalayalam'\n self.emit(type, :block_inmalayalam, text, ts-1, te)\n when 'inmathematicaloperators'\n self.emit(type, :block_inmathematical_operators, text, ts-1, te)\n when 'inmiscellaneousmathematicalsymbols-a'\n self.emit(type, :block_inmiscellaneous_mathematical_symbols_a, text, ts-1, te)\n when 'inmiscellaneousmathematicalsymbols-b'\n self.emit(type, :block_inmiscellaneous_mathematical_symbols_b, text, ts-1, te)\n when 'inmiscellaneoussymbolsandarrows'\n self.emit(type, :block_inmiscellaneous_symbols_and_arrows, text, ts-1, te)\n when 'inmiscellaneoussymbols'\n self.emit(type, :block_inmiscellaneous_symbols, text, ts-1, te)\n when 'inmiscellaneoustechnical'\n self.emit(type, :block_inmiscellaneous_technical, text, ts-1, te)\n when 'inmongolian'\n self.emit(type, :block_inmongolian, text, ts-1, te)\n when 'inmyanmar'\n self.emit(type, :block_inmyanmar, text, ts-1, te)\n when 'innumberforms'\n self.emit(type, :block_innumber_forms, text, ts-1, te)\n when 'inogham'\n self.emit(type, :block_inogham, text, ts-1, te)\n when 'inopticalcharacterrecognition'\n self.emit(type, :block_inoptical_character_recognition, text, ts-1, te)\n when 'inoriya'\n self.emit(type, :block_inoriya, text, ts-1, te)\n when 'inphoneticextensions'\n self.emit(type, :block_inphonetic_extensions, text, ts-1, te)\n when 'inprivateusearea'\n self.emit(type, :block_inprivate_use_area, text, ts-1, te)\n when 'inrunic'\n self.emit(type, :block_inrunic, text, ts-1, te)\n when 'insinhala'\n self.emit(type, :block_insinhala, text, ts-1, te)\n when 'insmallformvariants'\n self.emit(type, :block_insmall_form_variants, text, ts-1, te)\n when 'inspacingmodifierletters'\n self.emit(type, :block_inspacing_modifier_letters, text, ts-1, te)\n when 'inspecials'\n self.emit(type, :block_inspecials, text, ts-1, te)\n when 'insuperscriptsandsubscripts'\n self.emit(type, :block_insuperscripts_and_subscripts, text, ts-1, te)\n when 'insupplementalarrows-a'\n self.emit(type, :block_insupplemental_arrows_a, text, ts-1, te)\n when 'insupplementalarrows-b'\n self.emit(type, :block_insupplemental_arrows_b, text, ts-1, te)\n when 'insupplementalmathematicaloperators'\n self.emit(type, :block_insupplemental_mathematical_operators, text, ts-1, te)\n when 'insyriac'\n self.emit(type, :block_insyriac, text, ts-1, te)\n when 'intagalog'\n self.emit(type, :block_intagalog, text, ts-1, te)\n when 'intagbanwa'\n self.emit(type, :block_intagbanwa, text, ts-1, te)\n when 'intaile'\n self.emit(type, :block_intai_le, text, ts-1, te)\n when 'intamil'\n self.emit(type, :block_intamil, text, ts-1, te)\n when 'intelugu'\n self.emit(type, :block_intelugu, text, ts-1, te)\n when 'inthaana'\n self.emit(type, :block_inthaana, text, ts-1, te)\n when 'inthai'\n self.emit(type, :block_inthai, text, ts-1, te)\n when 'intibetan'\n self.emit(type, :block_intibetan, text, ts-1, te)\n when 'inunifiedcanadianaboriginalsyllabics'\n self.emit(type, :block_inunified_canadian_aboriginal_syllabics, text, ts-1, te)\n when 'invariationselectors'\n self.emit(type, :block_invariation_selectors, text, ts-1, te)\n when 'inyiradicals'\n self.emit(type, :block_inyi_radicals, text, ts-1, te)\n when 'inyisyllables'\n self.emit(type, :block_inyi_syllables, text, ts-1, te)\n when 'inyijinghexagramsymbols'\n self.emit(type, :block_inyijing_hexagram_symbols, text, ts-1, te)\n\n else\n # Should this really be an error? Or would emitting\n # an :unknown for the property be better?\n #\n # self.emit(type, :unknown, text, ts-1, te)\n\n raise UnknownUnicodePropertyError.new(name)\n end\n\n fret;\n };\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"fae0107dcdaaed9f8586950fcfb79ea68f9e35ea","subject":"Revert \"warning fix\"","message":"Revert \"warning fix\"\n\nThis reverts commit 19dbb204b65e954643bebd78c0a69c26de6c69e9.\n\nThe warning exists because the access statement is not implemented yet.\n","repos":"timoc\/ragel,timoc\/ragel,timoc\/ragel,timoc\/ragel","old_file":"test\/mailbox1.rl","new_file":"test\/mailbox1.rl","new_contents":"\/*\n * @LANG: c++\n * @CFLAGS: -I..\/aapl\n *\n * Test works with split code gen.\n *\/\n\n\/*\n * Parses unix mail boxes into headers and bodies.\n *\/\n\n#include \"mailbox1.h\"\n\n%%{\n\tmachine MBox;\n\n\t# Buffer the header names.\n\taction bufHeadName { fsm->headName.append(fc); }\n\n\t# Buffer the header content.\n\taction bufHeadContent { fsm->headContent.append(fc); }\n\n\t# Terminate a header. If it is an interesting header then prints it.\n\taction finBufHeadContent {\n\t\t\/* Terminate the buffers. *\/\n\t\tfsm->headName.append(0);\n\t\tfsm->headContent.append(0);\n\n\t\t\/* Print the header. Interesting headers. *\/\n\t\tprintf(\"%s:%s\\n\", fsm->headName.data, fsm->headContent.data);\n\t\t\n\t\t\/* Clear for the next time we use them. *\/\n\t\tfsm->headName.empty();\n\t\tfsm->headContent.empty();\n\t}\n\n\taction msgstart{\n\t\tprintf(\"NEW MESSAGE\\n\");\n\t}\n\n\t# Prints a blank line after the end of the headers of each message.\n\taction blankLine {\n\t\tprintf(\"\\n\");\n\t}\n\t\n\t# Helpers we will use in matching the date section of the from line.\n\tday = \/[A-Z][a-z][a-z]\/;\n\tmonth = \/[A-Z][a-z][a-z]\/;\n\tyear = \/[0-9][0-9][0-9][0-9]\/;\n\ttime = \/[0-9][0-9]:[0-9][0-9]\/ . ( \/:[0-9][0-9]\/ | '' );\n\tletterZone = \/[A-Z][A-Z][A-Z]\/;\n\tnumZone = \/[+\\-][0-9][0-9][0-9][0-9]\/;\n\tzone = letterZone | numZone;\n\tdayNum = \/[0-9 ][0-9]\/;\n\n\t# These are the different formats of the date minus an obscure\n\t# type that has a funny string 'remote from xxx' on the end. Taken\n\t# from c-client in the imap-2000 distribution.\n\tdate = day . ' ' . month . ' ' . dayNum . ' ' . time . ' ' .\n\t\t( year | year . ' ' . zone | zone . ' ' . year );\n\n\t# Note the priority assignment on the end of the from line. While we\n\t# matching the body of a message we may enter into this machine. We will\n\t# not leave the body of the previous message until this entire from line is\n\t# matched. \n\tfromLine = 'From ' . \/[^\\n]\/* . ' ' . date . '\\n' @(new_msg,1) @msgstart;\n\n\t# The types of characters that can be used as a header name.\n\thchar = print - [ :];\n\n\theader =\n\t\t# The name of the header.\n\t\thchar+ $bufHeadName . ':' \n\t\t# The content of the header. Look out for continuations.\n\t\t. ( (extend - '\\n') $bufHeadContent | '\\n'. [ \\t] @bufHeadContent )*\n\t\t# Buffer must end with a newline that does not continue.\n\t\t. '\\n' %finBufHeadContent;\n\n\tmessageLine = ( extend - '\\n' )* . '\\n' @(new_msg, 0);\n\n\t# When we get to the last newline we are still matching messageLine\n\t# so on the last newline it will think we are still in the message.\n\t# We need this because we can't assume that every newline means\n\t# the end of the current message, whereas at the same time we requre\n\t# that there be a newline before the fromLine of the next message.\n\tmessage = ( fromLine . header* . '\\n' @blankLine . messageLine* . '\\n' );\n\n\t# Its important that the priority in the fromLine gets bumped up\n\t# so that we are able to move to new messages. Otherwise we\n\t# will always stay in the message body of the first message.\n\tmain := message*;\n}%%\n\n%% write data;\n\nvoid MBox::init( )\n{\n\tMBox *fsm = this;\n\t%% write init;\n}\n\nvoid MBox::execute( const char *data, int len )\n{\n\tMBox *fsm = this;\n\tconst char *p = data;\n\tconst char *pe = data + len;\n\t%%{\n\t\taccess fsm->;\n\t\twrite exec;\n\t}%%\n}\n\nint MBox::finish( )\n{\n\tif ( cs == MBox_error )\n\t\treturn -1;\n\tif ( cs >= MBox_first_final )\n\t\treturn 1;\n\treturn 0;\n}\n\nMBox mbox;\n\nvoid test( const char *buf )\n{\n\tint len = strlen( buf );\n\tmbox.init();\n\tmbox.execute( buf, len );\n\tif ( mbox.finish() > 0 )\n\t\tprintf(\"ACCEPT\\n\");\n\telse\n\t\tprintf(\"FAIL\\n\");\n}\n\n\nint main()\n{\n\ttest(\n\t\t\"From email address goes here Wed Nov 28 13:30:05 2001 -0500\\n\"\n\t\t\"Header1: this is the header contents\\n\"\n\t\t\" there is more on the second line\\n\"\n\t\t\"\tand more on the third line.\\n\"\n\t\t\"Header2: slkdj\\n\"\n\t\t\"\\n\"\n\t\t\"This is the message data\\n\"\n\t\t\"\\n\"\n\t\t\"From email Wed Nov 28 13:30:05 2001 -0500\\n\"\n\t\t\"Header: \\n\"\n\t\t\"\\n\"\n\t\t\"mail message\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\"From email Wed Nov 28 13:30:05 EST 2000\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers.\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\">From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t\t\"\\n\"\n\t);\n\n\treturn 0;\n}\n\n#ifdef _____OUTPUT_____\nNEW MESSAGE\nHeader1: this is the header contents there is more on the second line\tand more on the third line.\nHeader2: slkdj\n\nNEW MESSAGE\nHeader: \n\nACCEPT\nNEW MESSAGE\n\nNEW MESSAGE\n\nACCEPT\nNEW MESSAGE\nHeader:alsdj\n\nACCEPT\nNEW MESSAGE\nHeader:alsdj\n\nACCEPT\nNEW MESSAGE\nHeader:alsdj\n\nNEW MESSAGE\n\nFAIL\nNEW MESSAGE\nHeader:alsdj\n\nNEW MESSAGE\n\nACCEPT\n#endif\n","old_contents":"\/*\n * @LANG: c++\n * @CFLAGS: -I..\/aapl\n *\n * Test works with split code gen.\n *\/\n\n\/*\n * Parses unix mail boxes into headers and bodies.\n *\/\n\n#include \"mailbox1.h\"\n\n%%{\n\tmachine MBox;\n\n\t# Buffer the header names.\n\taction bufHeadName { fsm->headName.append(fc); }\n\n\t# Buffer the header content.\n\taction bufHeadContent { fsm->headContent.append(fc); }\n\n\t# Terminate a header. If it is an interesting header then prints it.\n\taction finBufHeadContent {\n\t\t\/* Terminate the buffers. *\/\n\t\tfsm->headName.append(0);\n\t\tfsm->headContent.append(0);\n\n\t\t\/* Print the header. Interesting headers. *\/\n\t\tprintf(\"%s:%s\\n\", fsm->headName.data, fsm->headContent.data);\n\t\t\n\t\t\/* Clear for the next time we use them. *\/\n\t\tfsm->headName.empty();\n\t\tfsm->headContent.empty();\n\t}\n\n\taction msgstart{\n\t\tprintf(\"NEW MESSAGE\\n\");\n\t}\n\n\t# Prints a blank line after the end of the headers of each message.\n\taction blankLine {\n\t\tprintf(\"\\n\");\n\t}\n\t\n\t# Helpers we will use in matching the date section of the from line.\n\tday = \/[A-Z][a-z][a-z]\/;\n\tmonth = \/[A-Z][a-z][a-z]\/;\n\tyear = \/[0-9][0-9][0-9][0-9]\/;\n\ttime = \/[0-9][0-9]:[0-9][0-9]\/ . ( \/:[0-9][0-9]\/ | '' );\n\tletterZone = \/[A-Z][A-Z][A-Z]\/;\n\tnumZone = \/[+\\-][0-9][0-9][0-9][0-9]\/;\n\tzone = letterZone | numZone;\n\tdayNum = \/[0-9 ][0-9]\/;\n\n\t# These are the different formats of the date minus an obscure\n\t# type that has a funny string 'remote from xxx' on the end. Taken\n\t# from c-client in the imap-2000 distribution.\n\tdate = day . ' ' . month . ' ' . dayNum . ' ' . time . ' ' .\n\t\t( year | year . ' ' . zone | zone . ' ' . year );\n\n\t# Note the priority assignment on the end of the from line. While we\n\t# matching the body of a message we may enter into this machine. We will\n\t# not leave the body of the previous message until this entire from line is\n\t# matched. \n\tfromLine = 'From ' . \/[^\\n]\/* . ' ' . date . '\\n' @(new_msg,1) @msgstart;\n\n\t# The types of characters that can be used as a header name.\n\thchar = print - [ :];\n\n\theader =\n\t\t# The name of the header.\n\t\thchar+ $bufHeadName . ':' \n\t\t# The content of the header. Look out for continuations.\n\t\t. ( (extend - '\\n') $bufHeadContent | '\\n'. [ \\t] @bufHeadContent )*\n\t\t# Buffer must end with a newline that does not continue.\n\t\t. '\\n' %finBufHeadContent;\n\n\tmessageLine = ( extend - '\\n' )* . '\\n' @(new_msg, 0);\n\n\t# When we get to the last newline we are still matching messageLine\n\t# so on the last newline it will think we are still in the message.\n\t# We need this because we can't assume that every newline means\n\t# the end of the current message, whereas at the same time we requre\n\t# that there be a newline before the fromLine of the next message.\n\tmessage = ( fromLine . header* . '\\n' @blankLine . messageLine* . '\\n' );\n\n\t# Its important that the priority in the fromLine gets bumped up\n\t# so that we are able to move to new messages. Otherwise we\n\t# will always stay in the message body of the first message.\n\tmain := message*;\n}%%\n\n%% write data;\n\nvoid MBox::init( )\n{\n\t%% write init;\n}\n\nvoid MBox::execute( const char *data, int len )\n{\n\tMBox *fsm = this;\n\tconst char *p = data;\n\tconst char *pe = data + len;\n\t%%{\n\t\taccess fsm->;\n\t\twrite exec;\n\t}%%\n}\n\nint MBox::finish( )\n{\n\tif ( cs == MBox_error )\n\t\treturn -1;\n\tif ( cs >= MBox_first_final )\n\t\treturn 1;\n\treturn 0;\n}\n\nMBox mbox;\n\nvoid test( const char *buf )\n{\n\tint len = strlen( buf );\n\tmbox.init();\n\tmbox.execute( buf, len );\n\tif ( mbox.finish() > 0 )\n\t\tprintf(\"ACCEPT\\n\");\n\telse\n\t\tprintf(\"FAIL\\n\");\n}\n\n\nint main()\n{\n\ttest(\n\t\t\"From email address goes here Wed Nov 28 13:30:05 2001 -0500\\n\"\n\t\t\"Header1: this is the header contents\\n\"\n\t\t\" there is more on the second line\\n\"\n\t\t\"\tand more on the third line.\\n\"\n\t\t\"Header2: slkdj\\n\"\n\t\t\"\\n\"\n\t\t\"This is the message data\\n\"\n\t\t\"\\n\"\n\t\t\"From email Wed Nov 28 13:30:05 2001 -0500\\n\"\n\t\t\"Header: \\n\"\n\t\t\"\\n\"\n\t\t\"mail message\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\"From email Wed Nov 28 13:30:05 EST 2000\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers.\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\">From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t);\n\n\ttest(\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"Header:alsdj\\n\"\n\t\t\"\\n\"\n\t\t\"Header:\\n\"\n\t\t\"salkfj\\n\"\n\t\t\"\\n\"\n\t\t\"There are no headers. \\n\"\n\t\t\"\\n\"\n\t\t\"From user@host.dom Wed Nov 28 13:30:05 2001\\n\"\n\t\t\"\\n\"\n\t\t\"\\n\"\n\t);\n\n\treturn 0;\n}\n\n#ifdef _____OUTPUT_____\nNEW MESSAGE\nHeader1: this is the header contents there is more on the second line\tand more on the third line.\nHeader2: slkdj\n\nNEW MESSAGE\nHeader: \n\nACCEPT\nNEW MESSAGE\n\nNEW MESSAGE\n\nACCEPT\nNEW MESSAGE\nHeader:alsdj\n\nACCEPT\nNEW MESSAGE\nHeader:alsdj\n\nACCEPT\nNEW MESSAGE\nHeader:alsdj\n\nNEW MESSAGE\n\nFAIL\nNEW MESSAGE\nHeader:alsdj\n\nNEW MESSAGE\n\nACCEPT\n#endif\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"c5eec9cb74b7aa99792a162ad8d8b2ec6277f5c2","subject":"Fix uninitialized value","message":"Fix uninitialized value\n","repos":"WizardMac\/ReadStat,WizardMac\/ReadStat","old_file":"src\/txt\/readstat_sas_commands_read.rl","new_file":"src\/txt\/readstat_sas_commands_read.rl","new_contents":"#include \n#include \n\n#include \"..\/readstat.h\"\n#include \"readstat_schema.h\"\n#include \"readstat_sas_commands_read.h\"\n\n#include \"readstat_copy.h\"\n\nenum {\n LABEL_TYPE_NAN = -1,\n LABEL_TYPE_DOUBLE,\n LABEL_TYPE_STRING,\n LABEL_TYPE_RANGE\n};\n\nstatic readstat_error_t submit_columns(readstat_parser_t *parser, readstat_schema_t *dct, void *user_ctx) {\n if (!parser->handlers.variable)\n return READSTAT_OK;\n int i;\n int partial_entry_count = 0;\n for (i=0; ientry_count; i++) {\n readstat_schema_entry_t *entry = &dct->entries[i];\n entry->variable.index = i;\n entry->variable.index_after_skipping = partial_entry_count;\n int cb_retval = parser->handlers.variable(i, &entry->variable,\n entry->labelset[0] ? entry->labelset : NULL, user_ctx);\n if (cb_retval == READSTAT_HANDLER_SKIP_VARIABLE) {\n entry->skip = 1;\n } else if (cb_retval == READSTAT_HANDLER_ABORT) {\n return READSTAT_ERROR_USER_ABORT;\n } else {\n partial_entry_count++;\n }\n }\n return READSTAT_OK;\n}\n\nstatic readstat_schema_entry_t *find_or_create_entry(readstat_schema_t *dct, const char *var_name) {\n readstat_schema_entry_t *entry = NULL;\n int i;\n \/* linear search. this is shitty, but whatever *\/\n for (i=0; ientry_count; i++) {\n if (strcmp(dct->entries[i].variable.name, var_name) == 0) {\n entry = &dct->entries[i];\n break;\n }\n }\n if (!entry) {\n dct->entries = realloc(dct->entries, sizeof(readstat_schema_entry_t) * (dct->entry_count + 1));\n entry = &dct->entries[dct->entry_count];\n memset(entry, 0, sizeof(readstat_schema_entry_t));\n \n readstat_copy(entry->variable.name, sizeof(entry->variable.name),\n (unsigned char *)var_name, strlen(var_name));\n entry->decimal_separator = '.';\n \n dct->entry_count++;\n }\n return entry;\n}\n\n%%{\n machine sas_commands;\n write data noerror nofinal;\n}%%\n\nreadstat_schema_t *readstat_parse_sas_commands(readstat_parser_t *parser,\n const char *filepath, void *user_ctx, readstat_error_t *outError) {\n \/* TODO use the schema_entry data structure, and access it\n * with a hash table (or linear search if we're lazy)\n *\/\n readstat_schema_t *schema = NULL;\n unsigned char *bytes = NULL;\n readstat_error_t error = READSTAT_OK;\n ssize_t len = parser->io->seek(0, READSTAT_SEEK_END, parser->io->io_ctx);\n if (len == -1) {\n error = READSTAT_ERROR_SEEK;\n goto cleanup;\n }\n parser->io->seek(0, READSTAT_SEEK_SET, parser->io->io_ctx);\n\n bytes = malloc(len);\n\n parser->io->read(bytes, len, parser->io->io_ctx);\n\n unsigned char *p = bytes;\n unsigned char *pe = bytes + len;\n \n unsigned char *eof = pe;\n \n unsigned char *str_start = NULL;\n\n size_t str_len = 0;\n \n int cs;\n \n int first_integer = 0;\n int integer = 0;\n int line_no = 0;\n unsigned char *line_start = p;\n\n char varname[32];\n char argname[32];\n char labelset[32];\n char string_value[32];\n char buf[1024];\n\n readstat_type_t var_type = READSTAT_TYPE_DOUBLE;\n int label_type = 0;\n int var_row = 0, var_col = 0;\n int var_len = 0;\n\n if ((schema = calloc(1, sizeof(readstat_schema_t))) == NULL) {\n error = READSTAT_ERROR_MALLOC;\n goto cleanup;\n }\n\n schema->rows_per_observation = 1;\n \n %%{\n action start_integer {\n integer = 0;\n }\n \n action incr_integer {\n integer = 10 * integer + (fc - '0');\n }\n\n action incr_hex_integer {\n int value = 0;\n if (fc >= '0' && fc <= '9') {\n value = fc - '0';\n } else if (fc >= 'A' && fc <= 'F') {\n value = fc - 'A' + 10;\n } else if (fc >= 'a' && fc <= 'f') {\n value = fc - 'a' + 10;\n }\n integer = 16 * integer + value;\n }\n\n action copy_pos {\n var_col = integer - 1;\n var_len = 1;\n }\n\n action set_len {\n var_len = integer - var_col;\n }\n \n action set_str {\n var_type = READSTAT_TYPE_STRING;\n }\n \n action set_dbl {\n var_type = READSTAT_TYPE_DOUBLE;\n }\n\n action copy_buf {\n readstat_copy(buf, sizeof(buf), str_start, str_len);\n }\n\n action copy_labelset {\n readstat_copy(labelset, sizeof(labelset), str_start, str_len);\n }\n\n action copy_string {\n readstat_copy(string_value, sizeof(string_value), str_start, str_len);\n }\n\n action copy_argname {\n readstat_copy(argname, sizeof(argname), str_start, str_len);\n }\n\n action copy_varname {\n readstat_copy_lower(varname, sizeof(varname), str_start, str_len);\n }\n\n action handle_arg {\n if (strcasecmp(argname, \"firstobs\") == 0) {\n schema->first_line = integer;\n }\n if (strcasecmp(argname, \"dlm\") == 0) {\n schema->field_delimiter = integer ? integer : buf[0];\n }\n }\n\n action handle_var {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n entry->variable.type = var_type;\n entry->row = var_row;\n entry->col = var_col;\n entry->len = var_len;\n }\n\n action handle_var_len {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n entry->len = var_len;\n }\n\n action handle_var_label {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n readstat_copy(entry->variable.label, sizeof(entry->variable.label),\n (unsigned char *)buf, sizeof(buf));\n }\n\n action handle_var_labelset {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n readstat_copy(entry->labelset, sizeof(entry->labelset),\n (unsigned char *)labelset, sizeof(labelset));\n }\n\n action handle_value_label {\n if (parser->handlers.value_label) {\n if (label_type == LABEL_TYPE_RANGE) {\n int i;\n for (i=first_integer; i<=integer; i++) {\n readstat_value_t value = { \n .type = READSTAT_TYPE_DOUBLE,\n .v = { .double_value = i } };\n parser->handlers.value_label(labelset, value, buf, user_ctx);\n }\n } else {\n readstat_value_t value = { { 0 } };\n if (label_type == LABEL_TYPE_DOUBLE) {\n value.type = READSTAT_TYPE_DOUBLE;\n value.v.double_value = integer;\n } else if (label_type == LABEL_TYPE_STRING) {\n value.type = READSTAT_TYPE_STRING;\n value.v.string_value = string_value;\n } else if (label_type == LABEL_TYPE_NAN) {\n value.type = READSTAT_TYPE_DOUBLE;\n value.v.double_value = NAN;\n }\n\n parser->handlers.value_label(labelset, value, buf, user_ctx);\n }\n }\n }\n \n single_quoted_string = \"'\" ( [^']* ) >{ str_start = fpc; } %{ str_len = fpc - str_start; } \"'\";\n \n double_quoted_string = \"\\\"\" ( [^\"]* ) >{ str_start = fpc; } %{ str_len = fpc - str_start; } \"\\\"\";\n\n unquoted_string = [A-Za-z] [_A-Za-z0-9\\.]*;\n \n quoted_string = ( single_quoted_string | double_quoted_string ) %copy_buf;\n\n hex_string = \"'\" ( [0-9A-Fa-f]+ ) >start_integer $incr_hex_integer \"'x\";\n \n newline = ( \"\\n\" | \"\\r\\n\" ) %{ line_no++; line_start = p; };\n \n missing_value = \".\" [A-Z]?;\n \n identifier = ( [$_A-Za-z] [_A-Za-z0-9]* ) >{ str_start = fpc; } %{ str_len = fpc - str_start; };\n\n identifier_eval = \"&\"? identifier \".\"?;\n \n integer = [0-9]+ >start_integer $incr_integer;\n \n true_whitespace = [ \\t] | newline;\n \n multiline_comment = \"\/*\" ( any* - ( any* \"*\/\" any* ) ) \"*\/\";\n\n comment = \"*\" ( any* - ( any* \";\" true_whitespace* newline any* ) ) \";\" true_whitespace* newline |\n multiline_comment;\n \n whitespace = true_whitespace | multiline_comment;\n \n var = identifier %copy_varname;\n\n labelset = identifier %copy_labelset;\n\n arg = identifier %copy_argname (whitespace* \"=\" whitespace* (identifier_eval | quoted_string | hex_string | integer) >start_integer %handle_arg)?;\n\n args = arg ( whitespace+ arg)*;\n\n options_cmd = \"OPTIONS\"i whitespace+ args\n whitespace* \";\";\n\n let_macro = \"%LET\"i whitespace+ identifier whitespace* \"=\" whitespace* (unquoted_string | quoted_string) \n whitespace* \";\";\n\n libname_cmd = \"LIBNAME\"i whitespace+ identifier whitespace+ ( \n quoted_string (whitespace+ args)? | \n \"CLEAR\"i | \"_ALL_\"i whitespace* \"CLEAR\"i |\n \"LIST\"i | \"_ALL_\"i whitespace* \"LIST\"i\n ) whitespace* \";\";\n \n footnote_cmd = \"FOOTNOTE\"i whitespace+ quoted_string whitespace* \";\";\n\n empty_cmd = \";\";\n\n value_label = ( \"-\" integer %{ label_type = LABEL_TYPE_DOUBLE; integer *= -1; } |\n integer %{ label_type = LABEL_TYPE_DOUBLE; } |\n integer whitespace+ \"-\" whitespace+ %{ first_integer = integer; label_type = LABEL_TYPE_RANGE; } integer |\n unquoted_string %{ label_type = LABEL_TYPE_STRING; } %copy_string |\n quoted_string %{ label_type = LABEL_TYPE_STRING; } %copy_string\n ) whitespace* \"=\" whitespace* quoted_string %handle_value_label;\n\n var_len = (\"$\" whitespace* integer %set_str | integer %set_dbl) %{ var_len = integer; };\n\n value_cmd = \"VALUE\"i whitespace+ labelset whitespace+ (\"(\" args \")\" whitespace*)?\n value_label (whitespace+ value_label)* \n whitespace* \";\";\n \n proc_format_cmd = \"PROC\"i whitespace+ \"FORMAT\"i whitespace* ( args whitespace* )? \";\"\n ( whitespace | empty_cmd | value_cmd )+;\n\n filename_cmd = \"FILENAME\"i (whitespace+ args)? whitespace+ quoted_string\n whitespace* \";\";\n\n if_statement = \"IF\"i ( whitespace | identifier | \"-\"? integer | \"(\" | \")\" | \".\")+ \";\";\n\n data_cmd = \"DATA\"i (whitespace+ identifier_eval | unquoted_string | quoted_string )+\n whitespace* \";\";\n\n missing_cmd = \"MISSING\"i whitespace+ identifier \n whitespace* \";\";\n\n # lrecl_option = \"LRECL\"i whitespace* \"=\" whitespace* integer %handle_info;\n\n infile_cmd = \"INFILE\"i (whitespace+ quoted_string)? (whitespace* args)?\n whitespace* \";\";\n\n length_spec = var whitespace+ var_len %handle_var_len;\n\n length_cmd = \"LENGTH\"i whitespace+ length_spec (whitespace+ length_spec)*\n whitespace* \";\";\n\n label_spec = var whitespace* \"=\" whitespace* quoted_string %handle_var_label;\n\n label_cmd = \"LABEL\"i whitespace+ label_spec (whitespace+ label_spec)*\n whitespace* \";\";\n \n date_separator = [SN];\n \n date_format = ( \"MMDDYY\" integer |\n \"DATE\" |\n \"DATE9\" |\n \"DATETIME\" |\n \"DAY\" |\n \"DDMMYY\" date_separator? integer |\n \"DOWNAME\" |\n \"JULDAY\" |\n \"JULIAN\" |\n \"MMDDYY\" date_separator? integer |\n \"MMYY\" date_separator? |\n \"MONNAME\" |\n \"MONTH\" |\n \"MONYY\" |\n \"PDFJULG\" |\n \"WEEKDATE\" |\n \"WEEKDAY\" |\n \"WORDDATE\" |\n \"WORDDATX\" |\n \"QTR\" |\n \"QTRR\" |\n \"TIME\" |\n \"TIMEAMPM\" |\n \"TOD\" |\n \"YEAR\" |\n \"YYMMDD\" |\n \"YYMM\" date_separator? |\n \"YYQ\" date_separator? |\n \"YYQR\" date_separator? );\n \n \n format_lbl_spec = labelset \".\" %handle_var_labelset;\n \n format_dbl_spec = integer \".\" integer?;\n \n format_date_spec = date_format \".\" integer?;\n \n var_format_spec = var whitespace+ ( format_lbl_spec | format_dbl_spec | format_date_spec );\n\n format_cmd = \"FORMAT\"i whitespace+ var_format_spec (whitespace+ var_format_spec)*\n whitespace* \";\";\n \n var_attribute = (\n \"LENGTH\"i whitespace* \"=\" whitespace* var_len %handle_var_len |\n \"LABEL\"i whitespace* \"=\" whitespace* quoted_string %handle_var_label |\n \"FORMAT\"i whitespace* \"=\" whitespace* format_dbl_spec\n );\n \n var_attributes = var_attribute (whitespace+ var_attribute)*;\n \n attrib_spec = var whitespace+ var_attributes %handle_var;\n \n attrib_cmd = \"ATTRIB\"i whitespace+ attrib_spec (whitespace+ attrib_spec)* whitespace* \";\";\n \n input_format_spec = (\"$CHAR\" integer %set_str | identifier %set_dbl);\n\n input_int_spec = var whitespace+ integer %copy_pos \"-\" integer %set_len %set_dbl %handle_var;\n \n input_dbl_spec = \"@\" integer %copy_pos whitespace+ var whitespace+ (var_len | input_format_spec) \".\" %handle_var integer?;\n\n input_txt_spec = var whitespace+ \"$\" whitespace+ integer %copy_pos \"-\" integer %set_len %set_str %handle_var;\n\n row_spec = \"#\" integer %{ var_row = integer - 1; };\n \n input_spec = (input_int_spec | input_dbl_spec | input_txt_spec | row_spec | var);\n\n input_cmd = \"INPUT\"i whitespace+ %{ var_row = 0; } input_spec (whitespace+ input_spec)*\n whitespace* \";\";\n \n invalue_missing_spec = single_quoted_string whitespace* \"=\" whitespace* missing_value;\n \n invalue_format_spec = format_dbl_spec | format_date_spec;\n \n invalue_other_spec = \"OTHER\" whitespace* \"=\" whitespace* \"(|\" invalue_format_spec \"|)\";\n \n invalue_spec = invalue_missing_spec | invalue_other_spec;\n \n invalue_cmd = \"INVALUE\"i whitespace+ identifier whitespace+ invalue_spec (whitespace+ invalue_spec)* whitespace* \";\";\n\n proc_print_cmd = \"PROC\"i whitespace+ \"PRINT\"i (whitespace+ args) (whitespace+ \"(\" args \")\")? \n whitespace* \";\";\n\n proc_contents_cmd = \"PROC\"i whitespace+ \"CONTENTS\"i (whitespace+ args) whitespace* \";\";\n\n run_cmd = \"RUN\"i whitespace* \";\";\n\n command = \n options_cmd |\n let_macro |\n libname_cmd |\n footnote_cmd |\n value_cmd |\n proc_format_cmd |\n filename_cmd |\n attrib_cmd |\n data_cmd |\n if_statement |\n missing_cmd |\n infile_cmd |\n format_cmd |\n label_cmd |\n length_cmd |\n input_cmd |\n invalue_cmd |\n proc_print_cmd |\n proc_contents_cmd |\n run_cmd;\n \n main := ( true_whitespace | comment | command )*;\n\n write init;\n write exec;\n }%%\n \n \/* suppress warnings *\/\n (void)sas_commands_en_main;\n\n if (cs < %%{ write first_final; }%%) {\n char error_buf[1024];\n snprintf(error_buf, sizeof(error_buf), \"Error parsing .sas file around line #%d, col #%ld (%c)\",\n line_no + 1, (long)(p - line_start + 1), *p);\n if (parser->handlers.error) {\n parser->handlers.error(error_buf, user_ctx);\n }\n error = READSTAT_ERROR_PARSE;\n goto cleanup;\n }\n \n schema->rows_per_observation = var_row + 1;\n\n error = submit_columns(parser, schema, user_ctx);\n\ncleanup:\n parser->io->close(parser->io->io_ctx);\n free(bytes);\n if (error != READSTAT_OK) {\n if (outError)\n *outError = error;\n readstat_schema_free(schema);\n schema = NULL;\n }\n\n return schema;\n}\n","old_contents":"#include \n#include \n\n#include \"..\/readstat.h\"\n#include \"readstat_schema.h\"\n#include \"readstat_sas_commands_read.h\"\n\n#include \"readstat_copy.h\"\n\nenum {\n LABEL_TYPE_NAN = -1,\n LABEL_TYPE_DOUBLE,\n LABEL_TYPE_STRING,\n LABEL_TYPE_RANGE\n};\n\nstatic readstat_error_t submit_columns(readstat_parser_t *parser, readstat_schema_t *dct, void *user_ctx) {\n if (!parser->handlers.variable)\n return READSTAT_OK;\n int i;\n int partial_entry_count = 0;\n for (i=0; ientry_count; i++) {\n readstat_schema_entry_t *entry = &dct->entries[i];\n entry->variable.index = i;\n entry->variable.index_after_skipping = partial_entry_count;\n int cb_retval = parser->handlers.variable(i, &entry->variable,\n entry->labelset[0] ? entry->labelset : NULL, user_ctx);\n if (cb_retval == READSTAT_HANDLER_SKIP_VARIABLE) {\n entry->skip = 1;\n } else if (cb_retval == READSTAT_HANDLER_ABORT) {\n return READSTAT_ERROR_USER_ABORT;\n } else {\n partial_entry_count++;\n }\n }\n return READSTAT_OK;\n}\n\nstatic readstat_schema_entry_t *find_or_create_entry(readstat_schema_t *dct, const char *var_name) {\n readstat_schema_entry_t *entry = NULL;\n int i;\n \/* linear search. this is shitty, but whatever *\/\n for (i=0; ientry_count; i++) {\n if (strcmp(dct->entries[i].variable.name, var_name) == 0) {\n entry = &dct->entries[i];\n break;\n }\n }\n if (!entry) {\n dct->entries = realloc(dct->entries, sizeof(readstat_schema_entry_t) * (dct->entry_count + 1));\n entry = &dct->entries[dct->entry_count];\n memset(entry, 0, sizeof(readstat_schema_entry_t));\n \n readstat_copy(entry->variable.name, sizeof(entry->variable.name),\n (unsigned char *)var_name, strlen(var_name));\n entry->decimal_separator = '.';\n \n dct->entry_count++;\n }\n return entry;\n}\n\n%%{\n machine sas_commands;\n write data noerror nofinal;\n}%%\n\nreadstat_schema_t *readstat_parse_sas_commands(readstat_parser_t *parser,\n const char *filepath, void *user_ctx, readstat_error_t *outError) {\n \/* TODO use the schema_entry data structure, and access it\n * with a hash table (or linear search if we're lazy)\n *\/\n readstat_schema_t *schema = NULL;\n unsigned char *bytes = NULL;\n readstat_error_t error = READSTAT_OK;\n ssize_t len = parser->io->seek(0, READSTAT_SEEK_END, parser->io->io_ctx);\n if (len == -1) {\n error = READSTAT_ERROR_SEEK;\n goto cleanup;\n }\n parser->io->seek(0, READSTAT_SEEK_SET, parser->io->io_ctx);\n\n bytes = malloc(len);\n\n parser->io->read(bytes, len, parser->io->io_ctx);\n\n unsigned char *p = bytes;\n unsigned char *pe = bytes + len;\n \n unsigned char *eof = pe;\n \n unsigned char *str_start = NULL;\n\n size_t str_len = 0;\n \n int cs;\n \n int first_integer = 0;\n int integer = 0;\n int line_no = 0;\n unsigned char *line_start = p;\n\n char varname[32];\n char argname[32];\n char labelset[32];\n char string_value[32];\n char buf[1024];\n\n readstat_type_t var_type = READSTAT_TYPE_DOUBLE;\n int label_type;\n int var_row = 0, var_col = 0;\n int var_len = 0;\n\n if ((schema = calloc(1, sizeof(readstat_schema_t))) == NULL) {\n error = READSTAT_ERROR_MALLOC;\n goto cleanup;\n }\n\n schema->rows_per_observation = 1;\n \n %%{\n action start_integer {\n integer = 0;\n }\n \n action incr_integer {\n integer = 10 * integer + (fc - '0');\n }\n\n action incr_hex_integer {\n int value = 0;\n if (fc >= '0' && fc <= '9') {\n value = fc - '0';\n } else if (fc >= 'A' && fc <= 'F') {\n value = fc - 'A' + 10;\n } else if (fc >= 'a' && fc <= 'f') {\n value = fc - 'a' + 10;\n }\n integer = 16 * integer + value;\n }\n\n action copy_pos {\n var_col = integer - 1;\n var_len = 1;\n }\n\n action set_len {\n var_len = integer - var_col;\n }\n \n action set_str {\n var_type = READSTAT_TYPE_STRING;\n }\n \n action set_dbl {\n var_type = READSTAT_TYPE_DOUBLE;\n }\n\n action copy_buf {\n readstat_copy(buf, sizeof(buf), str_start, str_len);\n }\n\n action copy_labelset {\n readstat_copy(labelset, sizeof(labelset), str_start, str_len);\n }\n\n action copy_string {\n readstat_copy(string_value, sizeof(string_value), str_start, str_len);\n }\n\n action copy_argname {\n readstat_copy(argname, sizeof(argname), str_start, str_len);\n }\n\n action copy_varname {\n readstat_copy_lower(varname, sizeof(varname), str_start, str_len);\n }\n\n action handle_arg {\n if (strcasecmp(argname, \"firstobs\") == 0) {\n schema->first_line = integer;\n }\n if (strcasecmp(argname, \"dlm\") == 0) {\n schema->field_delimiter = integer ? integer : buf[0];\n }\n }\n\n action handle_var {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n entry->variable.type = var_type;\n entry->row = var_row;\n entry->col = var_col;\n entry->len = var_len;\n }\n\n action handle_var_len {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n entry->len = var_len;\n }\n\n action handle_var_label {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n readstat_copy(entry->variable.label, sizeof(entry->variable.label),\n (unsigned char *)buf, sizeof(buf));\n }\n\n action handle_var_labelset {\n readstat_schema_entry_t *entry = find_or_create_entry(schema, varname);\n readstat_copy(entry->labelset, sizeof(entry->labelset),\n (unsigned char *)labelset, sizeof(labelset));\n }\n\n action handle_value_label {\n if (parser->handlers.value_label) {\n if (label_type == LABEL_TYPE_RANGE) {\n int i;\n for (i=first_integer; i<=integer; i++) {\n readstat_value_t value = { \n .type = READSTAT_TYPE_DOUBLE,\n .v = { .double_value = i } };\n parser->handlers.value_label(labelset, value, buf, user_ctx);\n }\n } else {\n readstat_value_t value = { { 0 } };\n if (label_type == LABEL_TYPE_DOUBLE) {\n value.type = READSTAT_TYPE_DOUBLE;\n value.v.double_value = integer;\n } else if (label_type == LABEL_TYPE_STRING) {\n value.type = READSTAT_TYPE_STRING;\n value.v.string_value = string_value;\n } else if (label_type == LABEL_TYPE_NAN) {\n value.type = READSTAT_TYPE_DOUBLE;\n value.v.double_value = NAN;\n }\n\n parser->handlers.value_label(labelset, value, buf, user_ctx);\n }\n }\n }\n \n single_quoted_string = \"'\" ( [^']* ) >{ str_start = fpc; } %{ str_len = fpc - str_start; } \"'\";\n \n double_quoted_string = \"\\\"\" ( [^\"]* ) >{ str_start = fpc; } %{ str_len = fpc - str_start; } \"\\\"\";\n\n unquoted_string = [A-Za-z] [_A-Za-z0-9\\.]*;\n \n quoted_string = ( single_quoted_string | double_quoted_string ) %copy_buf;\n\n hex_string = \"'\" ( [0-9A-Fa-f]+ ) >start_integer $incr_hex_integer \"'x\";\n \n newline = ( \"\\n\" | \"\\r\\n\" ) %{ line_no++; line_start = p; };\n \n missing_value = \".\" [A-Z]?;\n \n identifier = ( [$_A-Za-z] [_A-Za-z0-9]* ) >{ str_start = fpc; } %{ str_len = fpc - str_start; };\n\n identifier_eval = \"&\"? identifier \".\"?;\n \n integer = [0-9]+ >start_integer $incr_integer;\n \n true_whitespace = [ \\t] | newline;\n \n multiline_comment = \"\/*\" ( any* - ( any* \"*\/\" any* ) ) \"*\/\";\n\n comment = \"*\" ( any* - ( any* \";\" true_whitespace* newline any* ) ) \";\" true_whitespace* newline |\n multiline_comment;\n \n whitespace = true_whitespace | multiline_comment;\n \n var = identifier %copy_varname;\n\n labelset = identifier %copy_labelset;\n\n arg = identifier %copy_argname (whitespace* \"=\" whitespace* (identifier_eval | quoted_string | hex_string | integer) >start_integer %handle_arg)?;\n\n args = arg ( whitespace+ arg)*;\n\n options_cmd = \"OPTIONS\"i whitespace+ args\n whitespace* \";\";\n\n let_macro = \"%LET\"i whitespace+ identifier whitespace* \"=\" whitespace* (unquoted_string | quoted_string) \n whitespace* \";\";\n\n libname_cmd = \"LIBNAME\"i whitespace+ identifier whitespace+ ( \n quoted_string (whitespace+ args)? | \n \"CLEAR\"i | \"_ALL_\"i whitespace* \"CLEAR\"i |\n \"LIST\"i | \"_ALL_\"i whitespace* \"LIST\"i\n ) whitespace* \";\";\n \n footnote_cmd = \"FOOTNOTE\"i whitespace+ quoted_string whitespace* \";\";\n\n empty_cmd = \";\";\n\n value_label = ( \"-\" integer %{ label_type = LABEL_TYPE_DOUBLE; integer *= -1; } |\n integer %{ label_type = LABEL_TYPE_DOUBLE; } |\n integer whitespace+ \"-\" whitespace+ %{ first_integer = integer; label_type = LABEL_TYPE_RANGE; } integer |\n unquoted_string %{ label_type = LABEL_TYPE_STRING; } %copy_string |\n quoted_string %{ label_type = LABEL_TYPE_STRING; } %copy_string\n ) whitespace* \"=\" whitespace* quoted_string %handle_value_label;\n\n var_len = (\"$\" whitespace* integer %set_str | integer %set_dbl) %{ var_len = integer; };\n\n value_cmd = \"VALUE\"i whitespace+ labelset whitespace+ (\"(\" args \")\" whitespace*)?\n value_label (whitespace+ value_label)* \n whitespace* \";\";\n \n proc_format_cmd = \"PROC\"i whitespace+ \"FORMAT\"i whitespace* ( args whitespace* )? \";\"\n ( whitespace | empty_cmd | value_cmd )+;\n\n filename_cmd = \"FILENAME\"i (whitespace+ args)? whitespace+ quoted_string\n whitespace* \";\";\n\n if_statement = \"IF\"i ( whitespace | identifier | \"-\"? integer | \"(\" | \")\" | \".\")+ \";\";\n\n data_cmd = \"DATA\"i (whitespace+ identifier_eval | unquoted_string | quoted_string )+\n whitespace* \";\";\n\n missing_cmd = \"MISSING\"i whitespace+ identifier \n whitespace* \";\";\n\n # lrecl_option = \"LRECL\"i whitespace* \"=\" whitespace* integer %handle_info;\n\n infile_cmd = \"INFILE\"i (whitespace+ quoted_string)? (whitespace* args)?\n whitespace* \";\";\n\n length_spec = var whitespace+ var_len %handle_var_len;\n\n length_cmd = \"LENGTH\"i whitespace+ length_spec (whitespace+ length_spec)*\n whitespace* \";\";\n\n label_spec = var whitespace* \"=\" whitespace* quoted_string %handle_var_label;\n\n label_cmd = \"LABEL\"i whitespace+ label_spec (whitespace+ label_spec)*\n whitespace* \";\";\n \n date_separator = [SN];\n \n date_format = ( \"MMDDYY\" integer |\n \"DATE\" |\n \"DATE9\" |\n \"DATETIME\" |\n \"DAY\" |\n \"DDMMYY\" date_separator? integer |\n \"DOWNAME\" |\n \"JULDAY\" |\n \"JULIAN\" |\n \"MMDDYY\" date_separator? integer |\n \"MMYY\" date_separator? |\n \"MONNAME\" |\n \"MONTH\" |\n \"MONYY\" |\n \"PDFJULG\" |\n \"WEEKDATE\" |\n \"WEEKDAY\" |\n \"WORDDATE\" |\n \"WORDDATX\" |\n \"QTR\" |\n \"QTRR\" |\n \"TIME\" |\n \"TIMEAMPM\" |\n \"TOD\" |\n \"YEAR\" |\n \"YYMMDD\" |\n \"YYMM\" date_separator? |\n \"YYQ\" date_separator? |\n \"YYQR\" date_separator? );\n \n \n format_lbl_spec = labelset \".\" %handle_var_labelset;\n \n format_dbl_spec = integer \".\" integer?;\n \n format_date_spec = date_format \".\" integer?;\n \n var_format_spec = var whitespace+ ( format_lbl_spec | format_dbl_spec | format_date_spec );\n\n format_cmd = \"FORMAT\"i whitespace+ var_format_spec (whitespace+ var_format_spec)*\n whitespace* \";\";\n \n var_attribute = (\n \"LENGTH\"i whitespace* \"=\" whitespace* var_len %handle_var_len |\n \"LABEL\"i whitespace* \"=\" whitespace* quoted_string %handle_var_label |\n \"FORMAT\"i whitespace* \"=\" whitespace* format_dbl_spec\n );\n \n var_attributes = var_attribute (whitespace+ var_attribute)*;\n \n attrib_spec = var whitespace+ var_attributes %handle_var;\n \n attrib_cmd = \"ATTRIB\"i whitespace+ attrib_spec (whitespace+ attrib_spec)* whitespace* \";\";\n \n input_format_spec = (\"$CHAR\" integer %set_str | identifier %set_dbl);\n\n input_int_spec = var whitespace+ integer %copy_pos \"-\" integer %set_len %set_dbl %handle_var;\n \n input_dbl_spec = \"@\" integer %copy_pos whitespace+ var whitespace+ (var_len | input_format_spec) \".\" %handle_var integer?;\n\n input_txt_spec = var whitespace+ \"$\" whitespace+ integer %copy_pos \"-\" integer %set_len %set_str %handle_var;\n\n row_spec = \"#\" integer %{ var_row = integer - 1; };\n \n input_spec = (input_int_spec | input_dbl_spec | input_txt_spec | row_spec | var);\n\n input_cmd = \"INPUT\"i whitespace+ %{ var_row = 0; } input_spec (whitespace+ input_spec)*\n whitespace* \";\";\n \n invalue_missing_spec = single_quoted_string whitespace* \"=\" whitespace* missing_value;\n \n invalue_format_spec = format_dbl_spec | format_date_spec;\n \n invalue_other_spec = \"OTHER\" whitespace* \"=\" whitespace* \"(|\" invalue_format_spec \"|)\";\n \n invalue_spec = invalue_missing_spec | invalue_other_spec;\n \n invalue_cmd = \"INVALUE\"i whitespace+ identifier whitespace+ invalue_spec (whitespace+ invalue_spec)* whitespace* \";\";\n\n proc_print_cmd = \"PROC\"i whitespace+ \"PRINT\"i (whitespace+ args) (whitespace+ \"(\" args \")\")? \n whitespace* \";\";\n\n proc_contents_cmd = \"PROC\"i whitespace+ \"CONTENTS\"i (whitespace+ args) whitespace* \";\";\n\n run_cmd = \"RUN\"i whitespace* \";\";\n\n command = \n options_cmd |\n let_macro |\n libname_cmd |\n footnote_cmd |\n value_cmd |\n proc_format_cmd |\n filename_cmd |\n attrib_cmd |\n data_cmd |\n if_statement |\n missing_cmd |\n infile_cmd |\n format_cmd |\n label_cmd |\n length_cmd |\n input_cmd |\n invalue_cmd |\n proc_print_cmd |\n proc_contents_cmd |\n run_cmd;\n \n main := ( true_whitespace | comment | command )*;\n\n write init;\n write exec;\n }%%\n \n \/* suppress warnings *\/\n (void)sas_commands_en_main;\n\n if (cs < %%{ write first_final; }%%) {\n char error_buf[1024];\n snprintf(error_buf, sizeof(error_buf), \"Error parsing .sas file around line #%d, col #%ld (%c)\",\n line_no + 1, (long)(p - line_start + 1), *p);\n if (parser->handlers.error) {\n parser->handlers.error(error_buf, user_ctx);\n }\n error = READSTAT_ERROR_PARSE;\n goto cleanup;\n }\n \n schema->rows_per_observation = var_row + 1;\n\n error = submit_columns(parser, schema, user_ctx);\n\ncleanup:\n parser->io->close(parser->io->io_ctx);\n free(bytes);\n if (error != READSTAT_OK) {\n if (outError)\n *outError = error;\n readstat_schema_free(schema);\n schema = NULL;\n }\n\n return schema;\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"0cb66e8644afa84ccd4cca8dbb668a70120a42cf","subject":"* lexer.rl: reduce String literal allocations","message":"* lexer.rl: reduce String literal allocations\n","repos":"bbatsov\/parser","old_file":"lib\/parser\/lexer.rl","new_file":"lib\/parser\/lexer.rl","new_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n BLANK_STRING = ''.freeze\n ESCAPED_NEXT_LINE = \"\\\\\\n\".freeze\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && \"\\\\$()*+.<>?[]^{|}\".include?(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(ESCAPED_NEXT_LINE, BLANK_STRING), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, BLANK_STRING)\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, BLANK_STRING)\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? '_'\n diagnostic :error, :trailing_in_number, { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","old_contents":"%%machine lex; # % fix highlighting\n\n#\n# === BEFORE YOU START ===\n#\n# Read the Ruby Hacking Guide chapter 11, available in English at\n# http:\/\/whitequark.org\/blog\/2013\/04\/01\/ruby-hacking-guide-ch-11-finite-state-lexer\/\n#\n# Remember two things about Ragel scanners:\n#\n# 1) Longest match wins.\n#\n# 2) If two matches have the same length, the first\n# in source code wins.\n#\n# General rules of making Ragel and Bison happy:\n#\n# * `p` (position) and `@te` contain the index of the character\n# they're pointing to (\"current\"), plus one. `@ts` contains the index\n# of the corresponding character. The code for extracting matched token is:\n#\n# @source[@ts...@te]\n#\n# * If your input is `foooooooobar` and the rule is:\n#\n# 'f' 'o'+\n#\n# the result will be:\n#\n# foooooooobar\n# ^ ts=0 ^ p=te=9\n#\n# * A Ragel lexer action should not emit more than one token, unless\n# you know what you are doing.\n#\n# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.\n#\n# * If an action emits the token and transitions to another state, use\n# these Ragel commands:\n#\n# emit($whatever)\n# fnext $next_state; fbreak;\n#\n# If you perform `fgoto` in an action which does not emit a token nor\n# rewinds the stream pointer, the parser's side-effectful,\n# context-sensitive lookahead actions will break in a hard to detect\n# and debug way.\n#\n# * If an action does not emit a token:\n#\n# fgoto $next_state;\n#\n# * If an action features lookbehind, i.e. matches characters with the\n# intent of passing them to another action:\n#\n# p = @ts - 1\n# fgoto $next_state;\n#\n# or, if the lookbehind consists of a single character:\n#\n# fhold; fgoto $next_state;\n#\n# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and\n# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result\n# _will_ invoke the action `act`.\n#\n# e_something stands for \"something with **e**mbedded action\".\n#\n# * EOF is explicit and is matched by `c_eof`. If you want to introspect\n# the state of the lexer, add this rule to the state:\n#\n# c_eof => do_eof;\n#\n# * If you proceed past EOF, the lexer will complain:\n#\n# NoMethodError: undefined method `ord' for nil:NilClass\n#\n\nclass Parser::Lexer\n\n %% write data nofinal;\n # %\n\n ESCAPES = {\n 'a' => \"\\a\", 'b' => \"\\b\", 'e' => \"\\e\", 'f' => \"\\f\",\n 'n' => \"\\n\", 'r' => \"\\r\", 's' => \"\\s\", 't' => \"\\t\",\n 'v' => \"\\v\", '\\\\' => \"\\\\\"\n }\n\n attr_reader :source_buffer\n attr_reader :encoding\n\n attr_accessor :diagnostics\n attr_accessor :static_env\n attr_accessor :force_utf32\n\n attr_accessor :cond, :cmdarg, :in_kwarg\n\n attr_accessor :tokens, :comments\n\n def initialize(version)\n @version = version\n @static_env = nil\n\n @tokens = nil\n @comments = nil\n\n @has_encode = ''.respond_to?(:encode)\n\n reset\n end\n\n def reset(reset_state=true)\n # Ragel state:\n if reset_state\n # Unit tests set state prior to resetting lexer.\n @cs = self.class.lex_en_line_begin\n\n @cond = StackState.new('cond')\n @cmdarg = StackState.new('cmdarg')\n @cond_stack = []\n @cmdarg_stack = []\n end\n\n @force_utf32 = false # Set to true by some tests\n\n @source = nil # source string\n @source_pts = nil # @source as a codepoint array\n @encoding = nil # target encoding for output strings\n\n @p = 0 # stream position (saved manually in #advance)\n @ts = nil # token start\n @te = nil # token end\n @act = 0 # next action\n\n @stack = [] # state stack\n @top = 0 # state stack top pointer\n\n # Lexer state:\n @token_queue = []\n @literal_stack = []\n\n @eq_begin_s = nil # location of last encountered =begin\n @sharp_s = nil # location of last encountered #\n\n @newline_s = nil # location of last encountered newline\n\n @num_base = nil # last numeric base\n @num_digits_s = nil # starting position of numeric digits\n @num_suffix_s = nil # starting position of numeric suffix\n @num_xfrm = nil # numeric suffix-induced transformation\n\n @escape_s = nil # starting position of current sequence\n @escape = nil # last escaped sequence, as string\n\n # See below the section on parsing heredocs.\n @heredoc_e = nil\n @herebody_s = nil\n\n # Ruby 1.9 ->() lambdas emit a distinct token if do\/{ is\n # encountered after a matching closing parenthesis.\n @paren_nest = 0\n @lambda_stack = []\n\n # If the lexer is in `command state' (aka expr_value)\n # at the entry to #advance, it will transition to expr_cmdarg\n # instead of expr_arg at certain points.\n @command_state = false\n\n # True at the end of \"def foo a:\"\n @in_kwarg = false\n end\n\n def source_buffer=(source_buffer)\n @source_buffer = source_buffer\n\n if @source_buffer\n @source = @source_buffer.source\n\n if defined?(Encoding)\n @encoding = @source.encoding\n\n # This is a workaround for 1.9.2, which (without force_encoding)\n # would convert the result to UTF-8 (source encoding of lexer.rl).\n @source += \"\\0\".force_encoding(@encoding)\n else\n @source += \"\\0\"\n end\n\n if defined?(Encoding) && @source.encoding == Encoding::UTF_8\n @source_pts = @source.unpack('U*')\n else\n @source_pts = @source.unpack('C*')\n end\n\n if (@source_pts.size > 1_000_000 && @has_encode) ||\n @force_utf32\n # A heuristic: if the buffer is larger than 1M, then\n # store it in UTF-32 and convert the tokens as they're\n # going out. If it's smaller, the conversion overhead\n # dominates runtime and this stops being beneficial.\n #\n # This is not really a good heuristic, as the result\n # heavily depends on token\/character ratio. If it's low,\n # say the gem consists mostly of long identifiers and\n # symbols, then storing the source in UTF-8 would be faster.\n #\n # Patches accepted.\n @source = @source.encode(Encoding::UTF_32LE)\n end\n\n if @source_pts[0] == 0xfeff\n # Skip byte order mark.\n @p = 1\n end\n else\n @source = nil\n @source_pts = nil\n end\n end\n\n LEX_STATES = {\n :line_begin => lex_en_line_begin,\n :expr_dot => lex_en_expr_dot,\n :expr_fname => lex_en_expr_fname,\n :expr_value => lex_en_expr_value,\n :expr_beg => lex_en_expr_beg,\n :expr_mid => lex_en_expr_mid,\n :expr_arg => lex_en_expr_arg,\n :expr_cmdarg => lex_en_expr_cmdarg,\n :expr_end => lex_en_expr_end,\n :expr_endarg => lex_en_expr_endarg,\n :expr_endfn => lex_en_expr_endfn,\n :expr_labelarg => lex_en_expr_labelarg,\n\n :interp_string => lex_en_interp_string,\n :interp_words => lex_en_interp_words,\n :plain_string => lex_en_plain_string,\n :plain_words => lex_en_plain_string,\n }\n\n def state\n LEX_STATES.invert.fetch(@cs, @cs)\n end\n\n def state=(state)\n @cs = LEX_STATES.fetch(state)\n end\n\n def push_cmdarg\n @cmdarg_stack.push(@cmdarg)\n @cmdarg = StackState.new(\"cmdarg.#{@cmdarg_stack.count}\")\n end\n\n def pop_cmdarg\n @cmdarg = @cmdarg_stack.pop\n end\n\n def push_cond\n @cond_stack.push(@cond)\n @cond = StackState.new(\"cond.#{@cond_stack.count}\")\n end\n\n def pop_cond\n @cond = @cond_stack.pop\n end\n\n # Return next token: [type, value].\n def advance\n if @token_queue.any?\n return @token_queue.shift\n end\n\n # Ugly, but dependent on Ragel output. Consider refactoring it somehow.\n klass = self.class\n _lex_trans_keys = klass.send :_lex_trans_keys\n _lex_key_spans = klass.send :_lex_key_spans\n _lex_index_offsets = klass.send :_lex_index_offsets\n _lex_indicies = klass.send :_lex_indicies\n _lex_trans_targs = klass.send :_lex_trans_targs\n _lex_trans_actions = klass.send :_lex_trans_actions\n _lex_to_state_actions = klass.send :_lex_to_state_actions\n _lex_from_state_actions = klass.send :_lex_from_state_actions\n _lex_eof_trans = klass.send :_lex_eof_trans\n\n pe = @source.length + 1\n p, eof = @p, pe\n\n @command_state = (@cs == klass.lex_en_expr_value ||\n @cs == klass.lex_en_line_begin)\n\n %% write exec;\n # %\n\n @p = p\n\n if @token_queue.any?\n @token_queue.shift\n elsif @cs == klass.lex_error\n [ false, [ '$error', range(p - 1, p) ] ]\n else\n eof = @source.length\n [ false, [ '$eof', range(eof, eof) ] ]\n end\n end\n\n protected\n\n def eof_codepoint?(point)\n [0x04, 0x1a, 0x00].include? point\n end\n\n def version?(*versions)\n versions.include?(@version)\n end\n\n def stack_pop\n @top -= 1\n @stack[@top]\n end\n\n if \"\".respond_to?(:encode)\n def encode_escape(ord)\n ord.chr.force_encoding(@encoding)\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e].encode(@encoding)\n end\n else\n def encode_escape(ord)\n ord.chr\n end\n\n def tok(s = @ts, e = @te)\n @source[s...e]\n end\n end\n\n def range(s = @ts, e = @te)\n Parser::Source::Range.new(@source_buffer, s, e)\n end\n\n def emit(type, value = tok, s = @ts, e = @te)\n token = [ type, [ value, range(s, e) ] ]\n\n @token_queue.push(token)\n\n @tokens.push(token) if @tokens\n\n token\n end\n\n def emit_table(table, s = @ts, e = @te)\n value = tok(s, e)\n\n emit(table[value], value, s, e)\n end\n\n def emit_do(do_block=false)\n if @cond.active?\n emit(:kDO_COND)\n elsif @cmdarg.active? || do_block\n emit(:kDO_BLOCK)\n else\n emit(:kDO)\n end\n end\n\n def arg_or_cmdarg\n if @command_state\n self.class.lex_en_expr_cmdarg\n else\n self.class.lex_en_expr_arg\n end\n end\n\n def emit_comment(s = @ts, e = @te)\n if @comments\n @comments.push(Parser::Source::Comment.new(range(s, e)))\n end\n\n if @tokens\n @tokens.push([ :tCOMMENT, [ tok(s, e), range(s, e) ] ])\n end\n\n nil\n end\n\n def diagnostic(type, reason, arguments=nil, location=range, highlights=[])\n @diagnostics.process(\n Parser::Diagnostic.new(type, reason, arguments, location, highlights))\n end\n\n #\n # === LITERAL STACK ===\n #\n\n def push_literal(*args)\n new_literal = Literal.new(self, *args)\n @literal_stack.push(new_literal)\n\n if new_literal.words?\n if new_literal.interpolate?\n self.class.lex_en_interp_words\n else\n self.class.lex_en_plain_words\n end\n else\n if new_literal.interpolate?\n self.class.lex_en_interp_string\n else\n self.class.lex_en_plain_string\n end\n end\n end\n\n def literal\n @literal_stack.last\n end\n\n def pop_literal\n old_literal = @literal_stack.pop\n\n if old_literal.type == :tREGEXP_BEG\n # Fetch modifiers.\n self.class.lex_en_regexp_modifiers\n else\n self.class.lex_en_expr_end\n end\n end\n\n # Mapping of strings to parser tokens.\n\n PUNCTUATION = {\n '=' => :tEQL, '&' => :tAMPER2, '|' => :tPIPE,\n '!' => :tBANG, '^' => :tCARET, '+' => :tPLUS,\n '-' => :tMINUS, '*' => :tSTAR2, '\/' => :tDIVIDE,\n '%' => :tPERCENT, '~' => :tTILDE, ',' => :tCOMMA,\n ';' => :tSEMI, '.' => :tDOT, '..' => :tDOT2,\n '...' => :tDOT3, '[' => :tLBRACK2, ']' => :tRBRACK,\n '(' => :tLPAREN2, ')' => :tRPAREN, '?' => :tEH,\n ':' => :tCOLON, '&&' => :tANDOP, '||' => :tOROP,\n '-@' => :tUMINUS, '+@' => :tUPLUS, '~@' => :tTILDE,\n '**' => :tPOW, '->' => :tLAMBDA, '=~' => :tMATCH,\n '!~' => :tNMATCH, '==' => :tEQ, '!=' => :tNEQ,\n '>' => :tGT, '>>' => :tRSHFT, '>=' => :tGEQ,\n '<' => :tLT, '<<' => :tLSHFT, '<=' => :tLEQ,\n '=>' => :tASSOC, '::' => :tCOLON2, '===' => :tEQQ,\n '<=>' => :tCMP, '[]' => :tAREF, '[]=' => :tASET,\n '{' => :tLCURLY, '}' => :tRCURLY, '`' => :tBACK_REF2,\n '!@' => :tBANG,\n }\n\n PUNCTUATION_BEGIN = {\n '&' => :tAMPER, '*' => :tSTAR, '**' => :tDSTAR,\n '+' => :tUPLUS, '-' => :tUMINUS, '::' => :tCOLON3,\n '(' => :tLPAREN, '{' => :tLBRACE, '[' => :tLBRACK,\n }\n\n KEYWORDS = {\n 'if' => :kIF_MOD, 'unless' => :kUNLESS_MOD,\n 'while' => :kWHILE_MOD, 'until' => :kUNTIL_MOD,\n 'rescue' => :kRESCUE_MOD, 'defined?' => :kDEFINED,\n 'BEGIN' => :klBEGIN, 'END' => :klEND,\n }\n\n KEYWORDS_BEGIN = {\n 'if' => :kIF, 'unless' => :kUNLESS,\n 'while' => :kWHILE, 'until' => :kUNTIL,\n 'rescue' => :kRESCUE, 'defined?' => :kDEFINED,\n }\n\n %w(class module def undef begin end then elsif else ensure case when\n for break next redo retry in do return yield super self nil true\n false and or not alias __FILE__ __LINE__ __ENCODING__).each do |keyword|\n KEYWORDS_BEGIN[keyword] = KEYWORDS[keyword] = :\"k#{keyword.upcase}\"\n end\n\n %%{\n # %\n\n access @;\n getkey (@source_pts[p] || 0);\n\n # === CHARACTER CLASSES ===\n #\n # Pay close attention to the differences between c_any and any.\n # c_any does not include EOF and so will cause incorrect behavior\n # for machine subtraction (any-except rules) and default transitions\n # for scanners.\n\n action do_nl {\n # Record position of a newline for precise location reporting on tNL\n # tokens.\n #\n # This action is embedded directly into c_nl, as it is idempotent and\n # there are no cases when we need to skip it.\n @newline_s = p\n }\n\n c_nl = '\\n' $ do_nl;\n c_space = [ \\t\\r\\f\\v];\n c_space_nl = c_space | c_nl;\n\n c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \\0, EOF\n c_eol = c_nl | c_eof;\n c_any = any - c_eof;\n\n c_nl_zlen = c_nl | zlen;\n c_line = any - c_nl_zlen;\n\n c_unicode = c_any - 0x00..0x7f;\n c_upper = [A-Z];\n c_lower = [a-z_] | c_unicode;\n c_alpha = c_lower | c_upper;\n c_alnum = c_alpha | [0-9];\n\n action do_eof {\n # Sit at EOF indefinitely. #advance would return $eof each time.\n # This allows to feed the lexer more data if needed; this is only used\n # in tests.\n #\n # Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs\n # below. This is due to the fact that scanner state at EOF is observed\n # by tests, and encapsulating it in a rule would break the introspection.\n fhold; fbreak;\n }\n\n #\n # === TOKEN DEFINITIONS ===\n #\n\n # All operators are punctuation. There is more to punctuation\n # than just operators. Operators can be overridden by user;\n # punctuation can not.\n\n # A list of operators which are valid in the function name context, but\n # have different semantics in others.\n operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;\n\n # A list of operators which can occur within an assignment shortcut (+ \u2192 +=).\n operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |\n '*' | '\/' | '**' | '~' | '<<' | '>>' | '%' ;\n\n # A list of all user-definable operators not covered by groups above.\n operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |\n '<' | '<=' | '>' | '>=' | '<=>' | '=>' ;\n\n # Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,\n # as they are ambiguous with interpolation `#{}` and should be counted.\n # These braces are not present in punctuation lists.\n\n # A list of punctuation which has different meaning when used at the\n # beginning of expression.\n punctuation_begin = '-' | '+' | '::' | '(' | '[' |\n '*' | '**' | '&' ;\n\n # A list of all punctuation except punctuation_begin.\n punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |\n '::' | '?' | ':' | '.' | '..' | '...' ;\n\n # A list of keywords which have different meaning at the beginning of expression.\n keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;\n\n # A list of keywords which accept an argument-like expression, i.e. have the\n # same post-processing as method calls or commands. Example: `yield 1`,\n # `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.\n keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;\n\n # A list of keywords which accept a literal function name as an argument.\n keyword_with_fname = 'def' | 'undef' | 'alias' ;\n\n # A list of keywords which accept an expression after them.\n keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |\n 'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |\n 'and' | 'or' ;\n\n # A list of keywords which accept a value, and treat the keywords from\n # `keyword_modifier` list as modifiers.\n keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;\n\n # A list of keywords which do not accept an expression after them.\n keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |\n 'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |\n '__LINE__' | '__ENCODING__';\n\n # All keywords.\n keyword = keyword_with_value | keyword_with_mid |\n keyword_with_end | keyword_with_arg |\n keyword_with_fname | keyword_modifier ;\n\n constant = c_upper c_alnum*;\n bareword = c_alpha c_alnum*;\n\n call_or_var = c_lower c_alnum*;\n class_var = '@@' bareword;\n instance_var = '@' bareword;\n global_var = '$'\n ( bareword | digit+\n | [`'+~*$&?!@\/\\\\;,.=:<>\"] # `\n | '-' c_alnum\n )\n ;\n\n # Ruby accepts (and fails on) variables with leading digit\n # in literal context, but not in unquoted symbol body.\n class_var_v = '@@' c_alnum+;\n instance_var_v = '@' c_alnum+;\n\n label = bareword [?!]? ':';\n\n #\n # === NUMERIC PARSING ===\n #\n\n int_hex = ( xdigit+ '_' )* xdigit* '_'? ;\n int_dec = ( digit+ '_' )* digit* '_'? ;\n int_bin = ( [01]+ '_' )* [01]* '_'? ;\n\n flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';\n flo_frac = '.' ( digit+ '_' )* digit+;\n flo_pow = [eE] [+\\-]? ( digit+ '_' )* digit+;\n\n int_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tINTEGER, chars) } }\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n flo_pow_suffix =\n '' % { @num_xfrm = lambda { |chars| emit(:tFLOAT, Float(chars)) } }\n | 'i' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Float(chars))) } };\n\n flo_suffix =\n flo_pow_suffix\n | 'r' % { @num_xfrm = lambda { |chars| emit(:tRATIONAL, Rational(chars)) } }\n | 'ri' % { @num_xfrm = lambda { |chars| emit(:tIMAGINARY, Complex(0, Rational(chars))) } };\n\n #\n # === ESCAPE SEQUENCE PARSING ===\n #\n\n # Escape parsing code is a Ragel pattern, not a scanner, and therefore\n # it shouldn't directly raise errors or perform other actions with side effects.\n # In reality this would probably just mess up error reporting in pathological\n # cases, through.\n\n # The amount of code required to parse \\M\\C stuff correctly is ridiculous.\n\n escaped_nl = \"\\\\\" c_nl;\n\n action unicode_points {\n @escape = \"\"\n\n codepoints = tok(@escape_s + 2, p - 1)\n codepoint_s = @escape_s + 2\n\n codepoints.split(\/[ \\t]\/).each do |codepoint_str|\n codepoint = codepoint_str.to_i(16)\n\n if codepoint >= 0x110000\n @escape = lambda do\n diagnostic :error, :unicode_point_too_large, nil,\n range(codepoint_s, codepoint_s + codepoint_str.length)\n end\n\n break\n end\n\n @escape += codepoint.chr(Encoding::UTF_8)\n codepoint_s += codepoint_str.length + 1\n end\n }\n\n action unescape_char {\n char = @source[p - 1].chr\n @escape = ESCAPES.fetch(char, char)\n }\n\n action invalid_complex_escape {\n @escape = lambda do\n diagnostic :fatal, :invalid_escape\n end\n }\n\n action slash_c_char {\n @escape = encode_escape(@escape[0].ord & 0x9f)\n }\n\n action slash_m_char {\n @escape = encode_escape(@escape[0].ord | 0x80)\n }\n\n maybe_escaped_char = (\n '\\\\' c_any %unescape_char\n | ( c_any - [\\\\] ) % { @escape = @source[p - 1].chr }\n );\n\n maybe_escaped_ctrl_char = ( # why?!\n '\\\\' c_any %unescape_char %slash_c_char\n | '?' % { @escape = \"\\x7f\" }\n | ( c_any - [\\\\?] ) % { @escape = @source[p - 1].chr } %slash_c_char\n );\n\n escape = (\n # \\377\n [0-7]{1,3}\n % { @escape = encode_escape(tok(@escape_s, p).to_i(8) % 0x100) }\n\n # \\xff\n | ( 'x' xdigit{1,2}\n % { @escape = encode_escape(tok(@escape_s + 1, p).to_i(16)) }\n # \\u263a\n | 'u' xdigit{4}\n % { @escape = tok(@escape_s + 1, p).to_i(16).chr(Encoding::UTF_8) }\n )\n\n # %q[\\x]\n | 'x' ( c_any - xdigit )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_hex_escape, nil,\n range(@escape_s - 1, p + 2)\n end\n }\n\n # %q[\\u123] %q[\\u{12]\n | 'u' ( c_any{0,4} -\n xdigit{4} - # \\u1234 is valid\n ( '{' xdigit{1,3} # \\u{1 \\u{12 \\u{123 are valid\n | '{' xdigit [ \\t}] any # \\u{1. \\u{1} are valid\n | '{' xdigit{2} [ \\t}] # \\u{12. \\u{12} are valid\n )\n )\n % {\n @escape = lambda do\n diagnostic :fatal, :invalid_unicode_escape, nil,\n range(@escape_s - 1, p)\n end\n }\n\n # \\u{123 456}\n | 'u{' ( xdigit{1,6} [ \\t] )*\n ( xdigit{1,6} '}'\n %unicode_points\n | ( xdigit* ( c_any - xdigit - '}' )+ '}'\n | ( c_any - '}' )* c_eof\n | xdigit{7,}\n ) % {\n @escape = lambda do\n diagnostic :fatal, :unterminated_unicode, nil,\n range(p - 1, p)\n end\n }\n )\n\n # \\C-\\a \\cx\n | ( 'C-' | 'c' ) escaped_nl?\n maybe_escaped_ctrl_char\n\n # \\M-a\n | 'M-' escaped_nl?\n maybe_escaped_char\n %slash_m_char\n\n # \\C-\\M-f \\M-\\cf \\c\\M-f\n | ( ( 'C-' | 'c' ) escaped_nl? '\\\\M-'\n | 'M-\\\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?\n maybe_escaped_ctrl_char\n %slash_m_char\n\n | 'C' c_any %invalid_complex_escape\n | 'M' c_any %invalid_complex_escape\n | ( 'M-\\\\C' | 'C-\\\\M' ) c_any %invalid_complex_escape\n\n | ( c_any - [0-7xuCMc] ) %unescape_char\n\n | c_eof % {\n diagnostic :fatal, :escape_eof, nil, range(p - 1, p)\n }\n );\n\n # Use rules in form of `e_bs escape' when you need to parse a sequence.\n e_bs = '\\\\' % {\n @escape_s = p\n @escape = nil\n };\n\n #\n # === STRING AND HEREDOC PARSING ===\n #\n\n # Heredoc parsing is quite a complex topic. First, consider that heredocs\n # can be arbitrarily nested. For example:\n #\n # puts <= 2.2\n if @version >= 22 && !@cond.active?\n lookahead = @source[@te...@te+2]\n lookahead = lookahead.encode(@encoding) if @has_encode\n end\n\n if !literal.heredoc? && (token = literal.nest_and_try_closing(string, @ts, @te, lookahead))\n if token[0] == :tLABEL_END\n p += 1\n pop_literal\n fnext expr_labelarg;\n else\n fnext *pop_literal;\n end\n fbreak;\n else\n literal.extend_string(string, @ts, @te)\n end\n }\n\n action extend_string_escaped {\n if literal.nest_and_try_closing('\\\\', @ts, @ts + 1)\n # If the literal is actually closed by the backslash,\n # rewind the input prior to consuming the escape sequence.\n p = @escape_s - 1\n fnext *pop_literal; fbreak;\n else\n # Get the first character after the backslash.\n escaped_char = @source[@escape_s].chr\n\n if literal.munge_escape? escaped_char\n # If this particular literal uses this character as an opening\n # or closing delimiter, it is an escape sequence for that\n # particular character. Write it without the backslash.\n\n if literal.regexp? && \"\\\\$()*+.<>?[]^{|}\".include?(escaped_char)\n # Regular expressions should include escaped delimiters in their\n # escaped form, except when the escaped character is\n # a closing delimiter but not a regexp metacharacter.\n #\n # The backslash itself cannot be used as a closing delimiter\n # at the same time as an escape symbol, but it is always munged,\n # so this branch also executes for the non-closing-delimiter case\n # for the backslash.\n literal.extend_string(tok, @ts, @te)\n else\n literal.extend_string(escaped_char, @ts, @te)\n end\n else\n # It does not. So this is an actual escape sequence, yay!\n # Two things to consider here.\n #\n # 1. The `escape' rule should be pure and so won't raise any\n # errors by itself. Instead, it stores them in lambdas.\n #\n # 2. Non-interpolated literals do not go through the aforementioned\n # rule. As \\\\ and \\' (and variants) are munged, the full token\n # should always be written for such literals.\n\n @escape.call if @escape.respond_to? :call\n\n if literal.regexp?\n # Regular expressions should include escape sequences in their\n # escaped form. On the other hand, escaped newlines are removed.\n literal.extend_string(tok.gsub(\"\\\\\\n\", ''), @ts, @te)\n else\n literal.extend_string(@escape || tok, @ts, @te)\n end\n end\n end\n }\n\n # Extend a string with a newline or a EOF character.\n # As heredoc closing line can immediately precede EOF, this action\n # has to handle such case specially.\n action extend_string_eol {\n if @te == pe\n diagnostic :fatal, :string_eof, nil,\n range(literal.str_s, literal.str_s + 1)\n end\n\n if literal.heredoc?\n line = tok(@herebody_s, @ts).gsub(\/\\r+$\/, '')\n\n if version?(18, 19, 20)\n # See ruby:c48b4209c\n line = line.gsub(\/\\r.*$\/, '')\n end\n\n # Try ending the heredoc with the complete most recently\n # scanned line. @herebody_s always refers to the start of such line.\n if literal.nest_and_try_closing(line, @herebody_s, @ts)\n # Adjust @herebody_s to point to the next line.\n @herebody_s = @te\n\n # Continue regular lexing after the heredoc reference (< extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n interp_string := |*\n interp_code => extend_interp_code;\n interp_var => extend_interp_var;\n e_bs escape => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_words := |*\n e_bs c_any => extend_string_escaped;\n c_space+ => extend_string_space;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n plain_string := |*\n '\\\\' c_nl => extend_string_eol;\n e_bs c_any => extend_string_escaped;\n c_eol => extend_string_eol;\n c_any => extend_string;\n *|;\n\n regexp_modifiers := |*\n [A-Za-z]+\n => {\n unknown_options = tok.scan(\/[^imxouesn]\/)\n if unknown_options.any?\n diagnostic :error, :regexp_options,\n { :options => unknown_options.join }\n end\n\n emit(:tREGEXP_OPT)\n fnext expr_end; fbreak;\n };\n\n any\n => {\n emit(:tREGEXP_OPT, tok(@ts, @te - 1), @ts, @te - 1)\n fhold; fgoto expr_end;\n };\n *|;\n\n #\n # === WHITESPACE HANDLING ===\n #\n\n # Various contexts in Ruby allow various kinds of whitespace\n # to be used. They are grouped to clarify the lexing machines\n # and ease collection of comments.\n\n # A line of code with inline #comment at end is always equivalent\n # to a line of code ending with just a newline, so an inline\n # comment is deemed equivalent to non-newline whitespace\n # (c_space character class).\n\n w_space =\n c_space+\n | '\\\\' e_heredoc_nl\n ;\n\n w_comment =\n '#' %{ @sharp_s = p - 1 }\n # The (p == pe) condition compensates for added \"\\0\" and\n # the way Ragel handles EOF.\n c_line* %{ emit_comment(@sharp_s, p == pe ? p - 2 : p) }\n ;\n\n w_space_comment =\n w_space\n | w_comment\n ;\n\n # A newline in non-literal context always interoperates with\n # here document logic and can always be escaped by a backslash,\n # still interoperating with here document logic in the same way,\n # yet being invisible to anything else.\n #\n # To demonstrate:\n #\n # foo = <' %{ tm = p - 2 } | # a=>b a => b\n '===' %{ tm = p - 3 } # a===b a === b\n ;\n\n ambiguous_symbol_suffix = # actual parsed\n ambiguous_ident_suffix |\n '==>' %{ tm = p - 2 } # :a==>b :a= => b\n ;\n\n # Ambiguous with 1.9 hash labels.\n ambiguous_const_suffix = # actual parsed\n '::' %{ tm = p - 2 } # A::B A :: B\n ;\n\n # Resolving kDO\/kDO_COND\/kDO_BLOCK ambiguity requires embedding\n # @cond\/@cmdarg-related code to e_lbrack, e_lparen and e_lbrace.\n\n e_lbrack = '[' % {\n @cond.push(false); @cmdarg.push(false)\n };\n\n # Ruby 1.9 lambdas require parentheses counting in order to\n # emit correct opening kDO\/tLBRACE.\n\n e_lparen = '(' % {\n @cond.push(false); @cmdarg.push(false)\n\n @paren_nest += 1\n };\n\n e_rparen = ')' % {\n @paren_nest -= 1\n };\n\n # Ruby is context-sensitive wrt\/ local identifiers.\n action local_ident {\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end; fbreak;\n else\n fnext *arg_or_cmdarg; fbreak;\n end\n }\n\n # Variable lexing code is accessed from both expressions and\n # string interpolation related code.\n #\n expr_variable := |*\n global_var\n => {\n if tok =~ \/^\\$([1-9][0-9]*)$\/\n emit(:tNTH_REF, tok(@ts + 1).to_i)\n elsif tok =~ \/^\\$([&`'+])$\/\n emit(:tBACK_REF)\n else\n emit(:tGVAR)\n end\n\n fnext *stack_pop; fbreak;\n };\n\n class_var_v\n => {\n if tok =~ \/^@@[0-9]\/\n diagnostic :error, :cvar_name, { :name => tok }\n end\n\n emit(:tCVAR)\n fnext *stack_pop; fbreak;\n };\n\n instance_var_v\n => {\n if tok =~ \/^@[0-9]\/\n diagnostic :error, :ivar_name, { :name => tok }\n end\n\n emit(:tIVAR)\n fnext *stack_pop; fbreak;\n };\n *|;\n\n # Literal function name in definition (e.g. `def class`).\n # Keywords are returned as their respective tokens; this is used\n # to support singleton def `def self.foo`. Global variables are\n # returned as `tGVAR`; this is used in global variable alias\n # statements `alias $a $b`. Symbols are returned verbatim; this\n # is used in `alias :a :\"b#{foo}\"` and `undef :a`.\n #\n # Transitions to `expr_endfn` afterwards.\n #\n expr_fname := |*\n keyword\n => { emit(KEYWORDS_BEGIN[tok]);\n fnext expr_endfn; fbreak; };\n\n constant\n => { emit(:tCONSTANT)\n fnext expr_endfn; fbreak; };\n\n bareword [?=!]?\n => { emit(:tIDENTIFIER)\n fnext expr_endfn; fbreak; };\n\n global_var\n => { p = @ts - 1\n fnext expr_end; fcall expr_variable; };\n\n # If the handling was to be delegated to expr_end,\n # these cases would transition to something else than\n # expr_endfn, which is incorrect.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_endfn; fbreak; };\n\n '::'\n => { fhold; fhold; fgoto expr_end; };\n\n ':'\n => { fhold; fgoto expr_beg; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # After literal function name in definition. Behaves like `expr_end`,\n # but allows a tLABEL.\n #\n # Transitions to `expr_end` afterwards.\n #\n expr_endfn := |*\n label\n => { emit(:tLABEL, tok(@ts, @te - 1))\n fnext expr_labelarg; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Literal function name in method call (e.g. `a.class`).\n #\n # Transitions to `expr_arg` afterwards.\n #\n expr_dot := |*\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n call_or_var\n => { emit(:tIDENTIFIER)\n fnext *arg_or_cmdarg; fbreak; };\n\n bareword ambiguous_fid_suffix\n => { emit(:tFID, tok(@ts, tm), @ts, tm)\n fnext *arg_or_cmdarg; p = tm - 1; fbreak; };\n\n # See the comment in `expr_fname`.\n operator_fname |\n operator_arithmetic |\n operator_rest\n => { emit_table(PUNCTUATION)\n fnext expr_arg; fbreak; };\n\n w_any;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token emitted was a `tIDENTIFIER` or `tFID`; no space\n # is consumed; the current expression is a command or method call.\n #\n expr_arg := |*\n #\n # COMMAND MODE SPECIFIC TOKENS\n #\n\n # cmd (1 + 2)\n # See below the rationale about expr_endarg.\n w_space+ e_lparen\n => {\n if version?(18)\n emit(:tLPAREN2, '(', @te - 1, @te)\n fnext expr_value; fbreak;\n else\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n fnext expr_beg; fbreak;\n end\n };\n\n # meth(1 + 2)\n # Regular method call.\n e_lparen\n => { emit(:tLPAREN2)\n fnext expr_beg; fbreak; };\n\n # meth [...]\n # Array argument. Compare with indexing `meth[...]`.\n w_space+ e_lbrack\n => { emit(:tLBRACK, '[', @te - 1, @te)\n fnext expr_beg; fbreak; };\n\n # cmd {}\n # Command: method call without parentheses.\n w_space* e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n p = @ts - 1\n fgoto expr_end;\n else\n emit(:tLCURLY, '{', @te - 1, @te)\n fnext expr_value; fbreak;\n end\n };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_BEG\n #\n\n # a??\n # Ternary operator\n '?' c_space_nl\n => {\n # Unlike expr_beg as invoked in the next rule, do not warn\n p = @ts - 1\n fgoto expr_end;\n };\n\n # a ?b, a? ?\n # Character literal or ternary operator\n w_space* '?'\n => { fhold; fgoto expr_beg; };\n\n # a %{1}, a %[1] (but not \"a %=1=\" or \"a % foo\")\n # a \/foo\/ (but not \"a \/ foo\" or \"a \/=foo\")\n # a < {\n if tok(tm, tm + 1) == '\/'\n # Ambiguous regexp literal.\n diagnostic :warning, :ambiguous_literal, nil, range(tm, tm + 1)\n end\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x *1\n # Ambiguous splat, kwsplat or block-pass.\n w_space+ %{ tm = p } ( '+' | '-' | '*' | '&' | '**' )\n => {\n diagnostic :warning, :ambiguous_prefix, { :prefix => tok(tm, @te) },\n range(tm, @te)\n\n p = tm - 1\n fgoto expr_beg;\n };\n\n # x ::Foo\n # Ambiguous toplevel constant access.\n w_space+ '::'\n => { fhold; fhold; fgoto expr_beg; };\n\n # x:b\n # Symbol.\n w_space* ':'\n => { fhold; fgoto expr_beg; };\n\n w_space+ label\n => { p = @ts - 1; fgoto expr_beg; };\n\n #\n # AMBIGUOUS TOKENS RESOLVED VIA EXPR_END\n #\n\n # a ? b\n # Ternary operator.\n w_space+ %{ tm = p } '?' c_space_nl\n => { p = tm - 1; fgoto expr_end; };\n\n # x + 1: Binary operator or operator-assignment.\n w_space* operator_arithmetic\n ( '=' | c_space_nl )? |\n # x rescue y: Modifier keyword.\n w_space* keyword_modifier |\n # Miscellanea.\n w_space* punctuation_end\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n w_space;\n\n w_comment\n => { fgoto expr_end; };\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # The previous token was an identifier which was seen while in the\n # command mode (that is, the state at the beginning of #advance was\n # expr_value). This state is very similar to expr_arg, but disambiguates\n # two very rare and specific condition:\n # * In 1.8 mode, \"foo (lambda do end)\".\n # * In 1.9+ mode, \"f x: -> do foo do end end\".\n expr_cmdarg := |*\n w_space+ e_lparen\n => {\n emit(:tLPAREN_ARG, '(', @te - 1, @te)\n if version?(18)\n fnext expr_value; fbreak;\n else\n fnext expr_beg; fbreak;\n end\n };\n\n w_space* 'do'\n => {\n if @cond.active?\n emit(:kDO_COND, 'do', @te - 2, @te)\n else\n emit(:kDO, 'do', @te - 2, @te)\n end\n fnext expr_value; fbreak;\n };\n\n c_any |\n # Disambiguate with the `do' rule above.\n w_space* bareword |\n w_space* label\n => { p = @ts - 1\n fgoto expr_arg; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is pretty complex. Normally, if an argument\n # is passed to a command and then there is a block (tLCURLY...tRCURLY),\n # the block is attached to the innermost argument (`f` in `m f {}`), or it\n # is a parse error (`m 1 {}`). But there is a special case for passing a single\n # primary expression grouped with parentheses: if you write `m (1) {}` or\n # (2.0 only) `m () {}`, then the block is attached to `m`.\n #\n # Thus, we recognize the opening `(` of a command (remember, a command is\n # a method call without parens) as a tLPAREN_ARG; then, in parser, we recognize\n # `tLPAREN_ARG expr rparen` as a `primary_expr` and before rparen, set the\n # lexer's state to `expr_endarg`, which makes it emit the possibly following\n # `{` as `tLBRACE_ARG`.\n #\n # The default post-`expr_endarg` state is `expr_end`, so this state also handles\n # `do` (as `kDO_BLOCK` in `expr_beg`).\n expr_endarg := |*\n e_lbrace\n => { emit(:tLBRACE_ARG)\n fnext expr_value; };\n\n 'do'\n => { emit_do(true)\n fnext expr_value; fbreak; };\n\n w_space_comment;\n\n c_any\n => { fhold; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # The rationale for this state is that several keywords accept value\n # (i.e. should transition to `expr_beg`), do not accept it like a command\n # (i.e. not an `expr_arg`), and must behave like a statement, that is,\n # accept a modifier if\/while\/etc.\n #\n expr_mid := |*\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n bareword\n => { p = @ts - 1; fgoto expr_beg; };\n\n w_space_comment;\n\n w_newline\n => { fhold; fgoto expr_end; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Beginning of an expression.\n #\n # Don't fallthrough to this state from `c_any`; make sure to handle\n # `c_space* c_nl` and let `expr_end` handle the newline.\n # Otherwise code like `f\\ndef x` gets glued together and the parser\n # explodes.\n #\n expr_beg := |*\n # Numeric processing. Converts:\n # +5 to [tINTEGER, 5]\n # -5 to [tUMINUS_NUM] [tINTEGER, 5]\n [+\\-][0-9]\n => {\n fhold;\n if tok.start_with? '-'\n emit(:tUMINUS_NUM, '-', @ts, @ts + 1)\n fnext expr_end; fbreak;\n end\n };\n\n # splat *a\n '*'\n => { emit(:tSTAR)\n fbreak; };\n\n #\n # STRING AND REGEXP LITERALS\n #\n\n # \/regexp\/oui\n # \/=\/ (disambiguation with \/=)\n '\/' c_any\n => {\n type = delimiter = tok[0].chr\n fhold; fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %\n '%' ( any - [A-Za-z] )\n => {\n type, delimiter = tok[0].chr, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n # %w(we are the people)\n '%' [A-Za-z]+ c_any\n => {\n type, delimiter = tok[0..-2], tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n '%' c_eof\n => {\n diagnostic :fatal, :string_eof, nil, range(@ts, @ts + 1)\n };\n\n # Heredoc start.\n # < {\n tok(@ts, @heredoc_e) =~ \/^<<(-?)([\"'`]?)(.*)\\2$\/\n\n indent = !$1.empty?\n type = '<<' + ($2.empty? ? '\"' : $2)\n delimiter = $3\n\n fnext *push_literal(type, delimiter, @ts, @heredoc_e, indent);\n\n if @herebody_s.nil?\n @herebody_s = new_herebody_s\n end\n\n p = @herebody_s - 1\n };\n\n #\n # SYMBOL LITERALS\n #\n\n # :\"bar\", :'baz'\n ':' ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n ':' bareword ambiguous_symbol_suffix\n => {\n emit(:tSYMBOL, tok(@ts + 1, tm), @ts, tm)\n p = tm - 1\n fnext expr_end; fbreak;\n };\n\n ':' ( bareword | global_var | class_var | instance_var |\n operator_fname | operator_arithmetic | operator_rest )\n => {\n emit(:tSYMBOL, tok(@ts + 1), @ts)\n fnext expr_end; fbreak;\n };\n\n #\n # AMBIGUOUS TERNARY OPERATOR\n #\n\n '?' ( e_bs escape\n | (c_any - c_space_nl - e_bs) % { @escape = nil }\n )\n => {\n # Show an error if memorized.\n @escape.call if @escape.respond_to? :call\n\n value = @escape || tok(@ts + 1)\n\n if version?(18)\n emit(:tINTEGER, value[0].ord)\n else\n emit(:tCHARACTER, value)\n end\n\n fnext expr_end; fbreak;\n };\n\n '?' c_space_nl\n => {\n escape = { \" \" => '\\s', \"\\r\" => '\\r', \"\\n\" => '\\n', \"\\t\" => '\\t',\n \"\\v\" => '\\v', \"\\f\" => '\\f' }[tok[1]]\n diagnostic :warning, :invalid_escape_use, { :escape => escape }, range\n\n p = @ts - 1\n fgoto expr_end;\n };\n\n '?' c_eof\n => {\n diagnostic :fatal, :incomplete_escape, nil, range(@ts, @ts + 1)\n };\n\n # f ?aa : b: Disambiguate with a character literal.\n '?' [A-Za-z_] bareword\n => {\n p = @ts - 1\n fgoto expr_end;\n };\n\n #\n # KEYWORDS AND PUNCTUATION\n #\n\n # a({b=>c})\n e_lbrace\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n emit(:tLAMBEG)\n else\n emit_table(PUNCTUATION_BEGIN)\n end\n fbreak;\n };\n\n # a([1, 2])\n e_lbrack |\n # a()\n e_lparen\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # a(+b)\n punctuation_begin\n => { emit_table(PUNCTUATION_BEGIN)\n fbreak; };\n\n # rescue Exception => e: Block rescue.\n # Special because it should transition to expr_mid.\n 'rescue' %{ tm = p } '=>'?\n => { emit_table(KEYWORDS_BEGIN, @ts, tm)\n p = tm - 1\n fnext expr_mid; fbreak; };\n\n # if a: Statement if.\n keyword_modifier\n => { emit_table(KEYWORDS_BEGIN)\n fnext expr_value; fbreak; };\n\n #\n # RUBY 1.9 HASH LABELS\n #\n\n label ( any - ':' )\n => {\n fhold;\n\n if version?(18)\n ident = tok(@ts, @te - 2)\n\n emit((tok[0] =~ \/[A-Z]\/) ? :tCONSTANT : :tIDENTIFIER,\n ident, @ts, @te - 2)\n fhold; # continue as a symbol\n\n if !@static_env.nil? && @static_env.declared?(ident)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit(:tLABEL, tok(@ts, @te - 2), @ts, @te - 1)\n fnext expr_labelarg;\n end\n\n fbreak;\n };\n\n #\n # CONTEXT-DEPENDENT VARIABLE LOOKUP OR COMMAND INVOCATION\n #\n\n # foo= bar: Disambiguate with bareword rule below.\n bareword ambiguous_ident_suffix |\n # def foo: Disambiguate with bareword rule below.\n keyword\n => { p = @ts - 1\n fgoto expr_end; };\n\n # a = 42; a [42]: Indexing.\n # def a; end; a [42]: Array argument.\n call_or_var\n => local_ident;\n\n #\n # WHITESPACE\n #\n\n w_any;\n\n e_heredoc_nl '=begin' ( c_space | c_nl_zlen )\n => { p = @ts - 1\n fgoto line_begin; };\n\n #\n # DEFAULT TRANSITION\n #\n\n # The following rules match most binary and all unary operators.\n # Rules for binary operators provide better error reporting.\n operator_arithmetic '=' |\n operator_rest |\n punctuation_end |\n c_any\n => { p = @ts - 1; fgoto expr_end; };\n\n c_eof => do_eof;\n *|;\n\n # Special newline handling for \"def a b:\"\n #\n expr_labelarg := |*\n w_space_comment;\n\n w_newline\n => {\n if @in_kwarg\n fhold; fgoto expr_end;\n else\n fgoto line_begin;\n end\n };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n # Like expr_beg, but no 1.9 label possible.\n #\n expr_value := |*\n # a:b: a(:b), a::B, A::B\n label (any - ':')\n => { p = @ts - 1\n fgoto expr_end; };\n\n w_space_comment;\n\n w_newline\n => { fgoto line_begin; };\n\n c_any\n => { fhold; fgoto expr_beg; };\n\n c_eof => do_eof;\n *|;\n\n expr_end := |*\n #\n # STABBY LAMBDA\n #\n\n '->'\n => {\n emit_table(PUNCTUATION, @ts, @ts + 2)\n\n @lambda_stack.push @paren_nest\n fnext expr_endfn; fbreak;\n };\n\n e_lbrace | 'do'\n => {\n if @lambda_stack.last == @paren_nest\n @lambda_stack.pop\n\n if tok == '{'\n emit(:tLAMBEG)\n else # 'do'\n emit(:kDO_LAMBDA)\n end\n else\n if tok == '{'\n emit_table(PUNCTUATION)\n else # 'do'\n emit_do\n end\n end\n\n fnext expr_value; fbreak;\n };\n\n #\n # KEYWORDS\n #\n\n keyword_with_fname\n => { emit_table(KEYWORDS)\n fnext expr_fname; fbreak; };\n\n 'class' w_any* '<<'\n => { emit(:kCLASS, 'class', @ts, @ts + 5)\n emit(:tLSHFT, '<<', @te - 2, @te)\n fnext expr_value; fbreak; };\n\n # a if b:c: Syntax error.\n keyword_modifier\n => { emit_table(KEYWORDS)\n fnext expr_beg; fbreak; };\n\n # elsif b:c: elsif b(:c)\n keyword_with_value\n => { emit_table(KEYWORDS)\n fnext expr_value; fbreak; };\n\n keyword_with_mid\n => { emit_table(KEYWORDS)\n fnext expr_mid; fbreak; };\n\n keyword_with_arg\n => {\n emit_table(KEYWORDS)\n\n if version?(18) && tok == 'not'\n fnext expr_beg; fbreak;\n else\n fnext expr_arg; fbreak;\n end\n };\n\n '__ENCODING__'\n => {\n if version?(18)\n emit(:tIDENTIFIER)\n\n if !@static_env.nil? && @static_env.declared?(tok)\n fnext expr_end;\n else\n fnext *arg_or_cmdarg;\n end\n else\n emit_table(KEYWORDS)\n end\n fbreak;\n };\n\n keyword_with_end\n => { emit_table(KEYWORDS)\n fbreak; };\n\n #\n # NUMERIC LITERALS\n #\n\n ( '0' [Xx] %{ @num_base = 16; @num_digits_s = p } int_hex\n | '0' [Dd] %{ @num_base = 10; @num_digits_s = p } int_dec\n | '0' [Oo] %{ @num_base = 8; @num_digits_s = p } int_dec\n | '0' [Bb] %{ @num_base = 2; @num_digits_s = p } int_bin\n | [1-9] digit* '_'? %{ @num_base = 10; @num_digits_s = @ts } int_dec\n | '0' digit* '_'? %{ @num_base = 8; @num_digits_s = @ts } int_dec\n ) %{ @num_suffix_s = p } int_suffix\n => {\n digits = tok(@num_digits_s, @num_suffix_s)\n\n if digits.end_with? '_'\n diagnostic :error, :trailing_in_number, { :character => '_' },\n range(@te - 1, @te)\n elsif digits.empty? && @num_base == 8 && version?(18)\n # 1.8 did not raise an error on 0o.\n digits = \"0\"\n elsif digits.empty?\n diagnostic :error, :empty_numeric\n elsif @num_base == 8 && (invalid_idx = digits.index(\/[89]\/))\n invalid_s = @num_digits_s + invalid_idx\n diagnostic :error, :invalid_octal, nil,\n range(invalid_s, invalid_s + 1)\n end\n\n if version?(18, 19, 20)\n emit(:tINTEGER, digits.to_i(@num_base))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits.to_i(@num_base))\n end\n fbreak;\n };\n\n flo_frac flo_pow?\n => {\n diagnostic :error, :no_dot_digit_literal\n };\n\n flo_int [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tINTEGER, tok(@ts, @te - 1).to_i)\n fhold; fbreak;\n end\n };\n\n flo_int flo_frac [eE]\n => {\n if version?(18, 19, 20)\n diagnostic :error,\n :trailing_in_number, { :character => tok(@te - 1, @te) },\n range(@te - 1, @te)\n else\n emit(:tFLOAT, tok(@ts, @te - 1).to_f)\n fhold; fbreak;\n end\n };\n\n flo_int\n ( flo_frac? flo_pow %{ @num_suffix_s = p } flo_pow_suffix\n | flo_frac %{ @num_suffix_s = p } flo_suffix\n )\n => {\n digits = tok(@ts, @num_suffix_s)\n\n if version?(18, 19, 20)\n emit(:tFLOAT, Float(digits))\n p = @num_suffix_s - 1\n else\n @num_xfrm.call(digits)\n end\n fbreak;\n };\n\n #\n # STRING AND XSTRING LITERALS\n #\n\n # `echo foo`, \"bar\", 'baz'\n '`' | ['\"] # '\n => {\n type, delimiter = tok, tok[-1].chr\n fgoto *push_literal(type, delimiter, @ts);\n };\n\n #\n # CONSTANTS AND VARIABLES\n #\n\n constant\n => { emit(:tCONSTANT)\n fnext *arg_or_cmdarg; fbreak; };\n\n constant ambiguous_const_suffix\n => { emit(:tCONSTANT, tok(@ts, tm), @ts, tm)\n p = tm - 1; fbreak; };\n\n global_var | class_var_v | instance_var_v\n => { p = @ts - 1; fcall expr_variable; };\n\n #\n # METHOD CALLS\n #\n\n '.' | '::'\n => { emit_table(PUNCTUATION)\n fnext expr_dot; fbreak; };\n\n call_or_var\n => local_ident;\n\n bareword ambiguous_fid_suffix\n => {\n if tm == @te\n # Suffix was consumed, e.g. foo!\n emit(:tFID)\n else\n # Suffix was not consumed, e.g. foo!=\n emit(:tIDENTIFIER, tok(@ts, tm), @ts, tm)\n p = tm - 1\n end\n fnext expr_arg; fbreak;\n };\n\n #\n # OPERATORS\n #\n\n ( e_lparen\n | operator_arithmetic\n | operator_rest\n )\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n e_rbrace | e_rparen | ']'\n => {\n emit_table(PUNCTUATION)\n @cond.lexpop; @cmdarg.lexpop\n\n if %w\"} ]\".include?(tok)\n fnext expr_endarg;\n else # )\n # fnext expr_endfn; ?\n end\n\n fbreak;\n };\n\n operator_arithmetic '='\n => { emit(:tOP_ASGN, tok(@ts, @te - 1))\n fnext expr_beg; fbreak; };\n\n '?'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n e_lbrack\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n punctuation_end\n => { emit_table(PUNCTUATION)\n fnext expr_beg; fbreak; };\n\n #\n # WHITESPACE\n #\n\n w_space_comment;\n\n w_newline\n => { fgoto leading_dot; };\n\n ';'\n => { emit_table(PUNCTUATION)\n fnext expr_value; fbreak; };\n\n '\\\\' c_line {\n diagnostic :error, :bare_backslash, nil, range(@ts, @ts + 1)\n fhold;\n };\n\n c_any\n => {\n diagnostic :fatal, :unexpected, { :character => tok.inspect[1..-2] }\n };\n\n c_eof => do_eof;\n *|;\n\n leading_dot := |*\n # Insane leading dots:\n # a #comment\n # .b: a.b\n c_space* '.' ( c_any - '.' )\n => { fhold; fhold;\n fgoto expr_end; };\n\n any\n => { emit(:tNL, nil, @newline_s, @newline_s + 1)\n fhold; fnext line_begin; fbreak; };\n *|;\n\n #\n # === EMBEDDED DOCUMENT (aka BLOCK COMMENT) PARSING ===\n #\n\n line_comment := |*\n '=end' c_line* c_nl_zlen\n => {\n emit_comment(@eq_begin_s, @te)\n fgoto line_begin;\n };\n\n c_line* c_nl;\n\n c_line* zlen\n => {\n diagnostic :fatal, :embedded_document, nil,\n range(@eq_begin_s, @eq_begin_s + '=begin'.length)\n };\n *|;\n\n line_begin := |*\n w_any;\n\n '=begin' ( c_space | c_nl_zlen )\n => { @eq_begin_s = @ts\n fgoto line_comment; };\n\n '__END__' ( c_eol - zlen )\n => { p = pe - 3 };\n\n c_any\n => { fhold; fgoto expr_value; };\n\n c_eof => do_eof;\n *|;\n\n }%%\n # %\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e6cdef98b7579ca04230d560437af6d8921f7eb8","subject":"crontab.rl: Make some free functions ParseCfgState member functions.","message":"crontab.rl: Make some free functions ParseCfgState member functions.\n","repos":"niklata\/ncron,niklata\/ncron","old_file":"crontab.rl","new_file":"crontab.rl","new_contents":"\/* crontab.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \"nk\/privilege.h\"\n}\n#include \"make_unique.hpp\"\n\n#include \"ncron.hpp\"\n#include \"sched.hpp\"\n#include \"crontab.hpp\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\nextern int gflags_debug;\n\nstatic void get_history(std::unique_ptr &item);\n\nstruct ParseCfgState\n{\n ParseCfgState(const std::string &ef, std::vector &stk,\n std::vector &dstk) :\n stack(stk), deadstack(dstk), ce(nullptr), execfile(ef),\n jobid_st(nullptr), time_st(nullptr), intv_st(nullptr),\n intv2_st(nullptr), strv_st(nullptr), v_strlen(0), linenum(0), v_int(0),\n v_int2(0), cs(0), cmdret(0), intv2_exist(false), runat(false)\n {\n memset(v_str, 0, sizeof v_str);\n }\n char v_str[1024];\n\n std::vector &stack;\n std::vector &deadstack;\n std::unique_ptr ce;\n\n const std::string execfile;\n\n const char *jobid_st;\n const char *time_st;\n const char *intv_st;\n const char *intv2_st;\n const char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int cmdret;\n\n bool intv2_exist;\n bool runat;\n\n void create_ce()\n {\n assert(!ce);\n ce = nk::make_unique();\n cmdret = 0;\n runat = false;\n }\n\n inline void debug_print_ce() const\n {\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"-=- finish_ce -=-\\n\");\n fmt::print(stderr, \"id: {}\\n\", ce->id);\n fmt::print(stderr, \"command: {}\\n\", ce->command);\n fmt::print(stderr, \"args: {}\\n\", ce->args);\n fmt::print(stderr, \"chroot: {}\\n\", ce->chroot);\n fmt::print(stderr, \"numruns: {}\\n\", ce->numruns);\n fmt::print(stderr, \"maxruns: {}\\n\", ce->maxruns);\n fmt::print(stderr, \"journal: {}\\n\", ce->journal);\n fmt::print(stderr, \"user: {}\\n\", ce->user);\n fmt::print(stderr, \"group: {}\\n\", ce->group);\n for (const auto &i: ce->month)\n fmt::print(stderr, \"month: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->day)\n fmt::print(stderr, \"day: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->weekday)\n fmt::print(stderr, \"weekday: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->hour)\n fmt::print(stderr, \"hour: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ce->minute)\n fmt::print(stderr, \"minute: [{},{}]\\n\", i.first, i.second);\n fmt::print(stderr, \"interval: {}\\n\", ce->interval);\n fmt::print(stderr, \"exectime: {}\\n\", ce->exectime);\n fmt::print(stderr, \"lasttime: {}\\n\", ce->lasttime);\n }\n\n inline void debug_print_ce_history() const\n {\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"[{}]->numruns = {}\\n\", ce->id, ce->numruns);\n fmt::print(stderr, \"[{}]->exectime = {}\\n\", ce->id, ce->exectime);\n fmt::print(stderr, \"[{}]->lasttime = {}\\n\", ce->id, ce->lasttime);\n }\n\n void finish_ce()\n {\n if (!ce)\n return;\n debug_print_ce();\n\n if (ce->id <= 0\n || (ce->interval <= 0 && ce->exectime <= 0)\n || ce->command.empty() || cmdret < 1) {\n if (gflags_debug)\n fmt::print(stderr, \"===> IGNORE\\n\");\n ce.reset();\n return;\n }\n if (gflags_debug)\n fmt::print(stderr, \"===> ADD\\n\");\n\n \/* we have a job to insert *\/\n if (runat) { \/* runat task *\/\n auto forced_exectime = ce->exectime;\n get_history(ce);\n ce->exectime = forced_exectime;\n debug_print_ce_history();\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (!ce->numruns)\n stack.emplace_back(std::move(ce));\n else\n deadstack.emplace_back(std::move(ce));\n } else { \/* interval task *\/\n get_history(ce);\n debug_print_ce_history();\n set_initial_exectime(*ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ce->maxruns == 0 || ce->numruns < ce->maxruns)\n && ce->exectime != 0)\n stack.emplace_back(std::move(ce));\n else\n deadstack.emplace_back(std::move(ce));\n }\n ce.reset();\n }\n\n void setgroupv()\n {\n if (nk_gidbyname(v_str, &ce->group)) {\n fmt::print(stderr, \"{}: nonexistent group specified at line {}\\n\",\n __func__, linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n\n void setuserv()\n {\n if (nk_uidgidbyname(v_str, &ce->user, &ce->group)) {\n fmt::print(stderr, \"{}: nonexistent user specified at line {}\\n\",\n __func__, linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n\n void setlim(int type)\n {\n struct rlimit rli;\n rli.rlim_cur = v_int == 0 ? RLIM_INFINITY : v_int;\n rli.rlim_max = v_int2 == 0 ? RLIM_INFINITY : v_int2;\n\n if (!ce->limits)\n ce->limits = nk::make_unique();\n\n switch (type) {\n case RLIMIT_CPU: ce->limits->cpu = rli; break;\n case RLIMIT_FSIZE: ce->limits->fsize = rli; break;\n case RLIMIT_DATA: ce->limits->data = rli; break;\n case RLIMIT_STACK: ce->limits->stack = rli; break;\n case RLIMIT_CORE: ce->limits->core = rli; break;\n case RLIMIT_RSS: ce->limits->rss = rli; break;\n case RLIMIT_NPROC: ce->limits->nproc = rli; break;\n case RLIMIT_NOFILE: ce->limits->nofile = rli; break;\n case RLIMIT_MEMLOCK: ce->limits->memlock = rli; break;\n #ifndef BSD\n case RLIMIT_AS: ce->limits->as = rli; break;\n case RLIMIT_MSGQUEUE: ce->limits->msgqueue = rli; break;\n case RLIMIT_NICE: ce->limits->nice = rli; break;\n case RLIMIT_RTTIME: ce->limits->rttime = rli; break;\n case RLIMIT_RTPRIO: ce->limits->rtprio = rli; break;\n case RLIMIT_SIGPENDING: ce->limits->sigpending = rli; break;\n #endif \/* BSD *\/\n default: fmt::print(stderr, \"{}: Bad RLIMIT_type specified.\\n\", __func__);\n std::exit(EXIT_FAILURE);\n }\n }\n\n};\n\nstruct item_history {\n item_history() {}\n item_history(boost::optional e, boost::optional l,\n boost::optional n) :\n exectime(e), lasttime(l), numruns(n) {}\n boost::optional exectime;\n boost::optional lasttime;\n boost::optional numruns;\n};\n\nstruct hstm {\n hstm() : st(nullptr), cs(0), id(0) {}\n const char *st;\n int cs;\n unsigned int id;\n item_history h;\n};\n\n%%{\n machine history_m;\n access hst.;\n\n action St { hst.st = p; }\n action LastTimeEn { hst.h.lasttime = atoi(hst.st); }\n action NumRunsEn { hst.h.numruns = atoi(hst.st); }\n action ExecTimeEn { hst.h.exectime = atoi(hst.st); }\n action IdEn { hst.id = atoi(hst.st); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_parse_history(hstm &hst, const std::string &l)\n{\n const char *p = l.c_str();\n const char *pe = p + l.size();\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (hst.cs >= history_m_first_final)\n return 1;\n if (hst.cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic std::unordered_map history_map;\n\nstatic void parse_history(const std::string &path)\n{\n std::string l;\n std::ifstream f(path, std::ifstream::in);\n if (f.fail() || f.bad() || f.eof()) {\n fmt::print(stderr, \"{}: failed to open history file \\\"{}\\\" for read\\n\",\n __func__, path);\n return;\n }\n size_t linenum = 0;\n while (1) {\n std::getline(f, l);\n ++linenum;\n if (f.eof())\n break;\n else if (f.bad() || f.fail()) {\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\",\n __func__, path);\n return;\n }\n if (l.empty())\n continue;\n hstm h;\n auto r = do_parse_history(h, l);\n if (r < 0) {\n if (r == -2)\n fmt::print(stderr, \"{}: Incomplete configuration at line {}; ignoring\\n\",\n __func__, linenum);\n else\n fmt::print(stderr, \"{}: Malformed configuration at line {}; ignoring.\\n\",\n __func__, linenum);\n continue;\n }\n history_map.emplace(std::make_pair(\n h.id, item_history(h.h.exectime, h.h.lasttime, h.h.numruns)));\n }\n}\n\nstatic void get_history(std::unique_ptr &item)\n{\n assert(item);\n\n auto i = history_map.find(item->id);\n if (i == history_map.end())\n return;\n if (i->second.exectime) {\n auto exectm = *i->second.exectime;\n item->exectime = exectm > 0 ? exectm : 0;\n }\n if (i->second.lasttime) {\n auto lasttm = *i->second.lasttime;\n item->lasttime = lasttm > 0 ? lasttm : 0;\n }\n if (i->second.numruns) {\n item->numruns = *i->second.numruns;\n }\n}\n\nstatic void addcstlist(ParseCfgState &ncs, cronentry_t::cst_list &list,\n int wildcard, int min, int max)\n{\n int low = ncs.v_int;\n int high = wildcard;\n if (ncs.intv2_exist)\n high = ncs.v_int2;\n\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (low > high) {\n \/* discontinuous range, split into two continuous rules... *\/\n list.emplace_back(std::make_pair(low, max));\n list.emplace_back(std::make_pair(min, high));\n } else {\n \/* handle continuous ranges normally *\/\n list.emplace_back(std::make_pair(low, high));\n }\n}\n\nstruct pckm {\n pckm() : st(nullptr), cs(0) {}\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n ncs.ce->command = std::string(pckm.st, p - pckm.st);\n boost::algorithm::replace_all(ncs.ce->command, \"\\\\\\\\\", \"\\\\\");\n boost::algorithm::replace_all(ncs.ce->command, \"\\\\ \", \" \");\n }\n action ArgEn { ncs.ce->args = std::string(pckm.st, p - pckm.st); }\n\n sptab = [ \\t];\n cmdstr = ([^\\0 \\t] | '\\\\\\\\' | '\\\\ ')+;\n cmd = sptab* (cmdstr > St % CmdEn);\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args?;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(ParseCfgState &ncs)\n{\n char *p = ncs.v_str;\n const char *pe = ncs.v_str + ncs.v_strlen;\n const char *eof = pe;\n\n struct pckm pckm;\n\n if (ncs.cmdret != 0) {\n ncs.cmdret = -3;\n fmt::print(stderr, \"Duplicate 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs.cmdret = -1;\n fmt::print(stderr, \"Malformed 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs.cmdret = 1;\n else {\n ncs.cmdret = -2;\n fmt::print(stderr, \"Incomplete 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n}\n\n%%{\n machine ncrontab;\n access ncs.;\n\n spc = [ \\t];\n eqsep = spc* '=' spc*;\n\n action TUnitSt { ncs.time_st = p; ncs.v_time = 0; }\n action TSecEn { ncs.v_time += atoi(ncs.time_st); }\n action TMinEn { ncs.v_time += 60 * atoi(ncs.time_st); }\n action THrEn { ncs.v_time += 3600 * atoi(ncs.time_st); }\n action TDayEn { ncs.v_time += 86400 * atoi(ncs.time_st); }\n action TWeekEn { ncs.v_time += 604800 * atoi(ncs.time_st); }\n\n action IntValSt {\n ncs.intv_st = p;\n ncs.v_int = ncs.v_int2 = 0;\n ncs.intv2_exist = false;\n }\n action IntValEn { ncs.v_int = atoi(ncs.intv_st); }\n action IntVal2St { ncs.intv2_st = p; }\n action IntVal2En {\n ncs.v_int2 = atoi(ncs.intv2_st);\n ncs.intv2_exist = true;\n }\n\n action StrValSt { ncs.strv_st = p; ncs.v_strlen = 0; }\n action StrValEn {\n ncs.v_strlen = p - ncs.strv_st;\n if (ncs.v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs.v_str, sizeof ncs.v_str,\n \"%.*s\", (int)ncs.v_strlen, ncs.strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs.v_str) {\n fmt::print(stderr, \"error parsing line {} in crontab; too long?\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn);\n timeval = t_any (spc* t_any)*;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))?;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn);\n\n action JournalEn { ncs.ce->journal = true; }\n journal = 'journal'i % JournalEn;\n\n action RunAtEn {\n ncs.runat = true;\n ncs.ce->exectime = ncs.v_int;\n ncs.ce->maxruns = 1;\n ncs.ce->journal = true;\n }\n action MaxRunsEn {\n if (!ncs.runat)\n ncs.ce->maxruns = ncs.v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { ncs.setlim(RLIMIT_AS); }\n action LimMemlockEn { ncs.setlim(RLIMIT_MEMLOCK); }\n action LimNofileEn { ncs.setlim(RLIMIT_NOFILE); }\n action LimNprocEn { ncs.setlim(RLIMIT_NPROC); }\n action LimRssEn { ncs.setlim(RLIMIT_RSS); }\n action LimCoreEn { ncs.setlim(RLIMIT_CORE); }\n action LimStackEn { ncs.setlim(RLIMIT_STACK); }\n action LimDataEn { ncs.setlim(RLIMIT_DATA); }\n action LimFsizeEn { ncs.setlim(RLIMIT_FSIZE); }\n action LimCpuEn { ncs.setlim(RLIMIT_CPU); }\n action LimMsgQueueEn { ncs.setlim(RLIMIT_MSGQUEUE); }\n action LimNiceEn { ncs.setlim(RLIMIT_NICE); }\n action LimRtTimeEn { ncs.setlim(RLIMIT_RTTIME); }\n action LimRtPrioEn { ncs.setlim(RLIMIT_RTPRIO); }\n action LimSigPendingEn { ncs.setlim(RLIMIT_SIGPENDING); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n lim_msgqueue = 'l_msgqueue'i eqsep intrangeval % LimMsgQueueEn;\n lim_nice = 'l_nice'i eqsep intrangeval % LimNiceEn;\n lim_rttime = 'l_rttime'i eqsep intrangeval % LimRtTimeEn;\n lim_rtprio = 'l_rtprio'i eqsep intrangeval % LimRtPrioEn;\n lim_sigpending = 'l_sigpending'i eqsep intrangeval % LimSigPendingEn;\n\n action IntervalEn { ncs.ce->interval = ncs.v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addcstlist(ncs, ncs.ce->month, 0, 1, 12); }\n action DayEn { addcstlist(ncs, ncs.ce->day, 0, 1, 31); }\n action WeekdayEn { addcstlist(ncs, ncs.ce->weekday, 0, 1, 7); }\n action HourEn { addcstlist(ncs, ncs.ce->hour, 24, 0, 23); }\n action MinuteEn { addcstlist(ncs, ncs.ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { ncs.setgroupv(); }\n action UserEn { ncs.setuserv(); }\n action ChrootEn {\n ncs.ce->chroot = std::string(ncs.v_str, ncs.v_strlen);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n lim_msgqueue | lim_nice | lim_rttime | lim_rtprio | lim_sigpending |\n maxruns | runat | journal;\n\n action JobIdSt { ncs.jobid_st = p; }\n action JobIdEn { ncs.ce->id = atoi(ncs.jobid_st); }\n action CreateCe { ncs.finish_ce(); ncs.create_ce(); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) % JobIdEn;\n\n main := jobid | cmds;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(ParseCfgState &ncs, const std::string &l)\n{\n const char *p = l.c_str();\n const char *pe = p + l.size();\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs.cs == ncrontab_error)\n return -1;\n if (ncs.cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(const std::string &path, const std::string &execfile,\n std::vector &stk,\n std::vector &deadstk)\n{\n struct ParseCfgState ncs(execfile, stk, deadstk);\n parse_history(ncs.execfile);\n\n std::string l;\n std::ifstream f(path, std::ifstream::in);\n if (f.fail() || f.bad() || f.eof()) {\n fmt::print(stderr, \"{}: failed to open file: '{}'\\n\", __func__, path);\n std::exit(EXIT_FAILURE);\n }\n while (1) {\n std::getline(f, l);\n ++ncs.linenum;\n if (f.eof())\n break;\n else if (f.bad() || f.fail()) {\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\",\n __func__, path);\n std::exit(EXIT_FAILURE);\n }\n if (l.empty())\n continue;\n auto r = do_parse_config(ncs, l);\n if (r < 0) {\n fmt::print(stderr, \"{}: do_parse_config({}) failed at line {}\\n\",\n __func__, path, ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n std::make_heap(stk.begin(), stk.end(), GtCronEntry);\n history_map.clear();\n cfg_reload = 1;\n}\n\n","old_contents":"\/* crontab.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n#include \"nk\/privilege.h\"\n}\n#include \"make_unique.hpp\"\n\n#include \"ncron.hpp\"\n#include \"sched.hpp\"\n#include \"crontab.hpp\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\nextern int gflags_debug;\n\nstruct ParseCfgState\n{\n ParseCfgState(const std::string &ef, std::vector &stk,\n std::vector &dstk) :\n stack(stk), deadstack(dstk), ce(nullptr), execfile(ef),\n jobid_st(nullptr), time_st(nullptr), intv_st(nullptr),\n intv2_st(nullptr), strv_st(nullptr), v_strlen(0), linenum(0), v_int(0),\n v_int2(0), cs(0), cmdret(0), intv2_exist(false), runat(false)\n {\n memset(v_str, 0, sizeof v_str);\n }\n char v_str[1024];\n\n std::vector &stack;\n std::vector &deadstack;\n std::unique_ptr ce;\n\n const std::string execfile;\n\n const char *jobid_st;\n const char *time_st;\n const char *intv_st;\n const char *intv2_st;\n const char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int cmdret;\n\n bool intv2_exist;\n bool runat;\n};\n\nstruct item_history {\n item_history() {}\n item_history(boost::optional e, boost::optional l,\n boost::optional n) :\n exectime(e), lasttime(l), numruns(n) {}\n boost::optional exectime;\n boost::optional lasttime;\n boost::optional numruns;\n};\n\nstruct hstm {\n hstm() : st(nullptr), cs(0), id(0) {}\n const char *st;\n int cs;\n unsigned int id;\n item_history h;\n};\n\n%%{\n machine history_m;\n access hst.;\n\n action St { hst.st = p; }\n action LastTimeEn { hst.h.lasttime = atoi(hst.st); }\n action NumRunsEn { hst.h.numruns = atoi(hst.st); }\n action ExecTimeEn { hst.h.exectime = atoi(hst.st); }\n action IdEn { hst.id = atoi(hst.st); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_parse_history(hstm &hst, const std::string &l)\n{\n const char *p = l.c_str();\n const char *pe = p + l.size();\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (hst.cs >= history_m_first_final)\n return 1;\n if (hst.cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic std::unordered_map history_map;\n\nstatic void parse_history(const std::string &path)\n{\n std::string l;\n std::ifstream f(path, std::ifstream::in);\n if (f.fail() || f.bad() || f.eof()) {\n fmt::print(stderr, \"{}: failed to open history file \\\"{}\\\" for read\\n\",\n __func__, path);\n return;\n }\n size_t linenum = 0;\n while (1) {\n std::getline(f, l);\n ++linenum;\n if (f.eof())\n break;\n else if (f.bad() || f.fail()) {\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\",\n __func__, path);\n return;\n }\n if (l.empty())\n continue;\n hstm h;\n auto r = do_parse_history(h, l);\n if (r < 0) {\n if (r == -2)\n fmt::print(stderr, \"{}: Incomplete configuration at line {}; ignoring\\n\",\n __func__, linenum);\n else\n fmt::print(stderr, \"{}: Malformed configuration at line {}; ignoring.\\n\",\n __func__, linenum);\n continue;\n }\n history_map.emplace(std::make_pair(\n h.id, item_history(h.h.exectime, h.h.lasttime, h.h.numruns)));\n }\n}\n\nstatic void get_history(std::unique_ptr &item)\n{\n assert(item);\n\n auto i = history_map.find(item->id);\n if (i == history_map.end())\n return;\n if (i->second.exectime) {\n auto exectm = *i->second.exectime;\n item->exectime = exectm > 0 ? exectm : 0;\n }\n if (i->second.lasttime) {\n auto lasttm = *i->second.lasttime;\n item->lasttime = lasttm > 0 ? lasttm : 0;\n }\n if (i->second.numruns) {\n item->numruns = *i->second.numruns;\n }\n}\n\nstatic void setlim(ParseCfgState &ncs, int type)\n{\n struct rlimit rli;\n rli.rlim_cur = ncs.v_int == 0 ? RLIM_INFINITY : ncs.v_int;\n rli.rlim_max = ncs.v_int2 == 0 ? RLIM_INFINITY : ncs.v_int2;\n\n if (!ncs.ce->limits)\n ncs.ce->limits = nk::make_unique();\n\n switch (type) {\n case RLIMIT_CPU: ncs.ce->limits->cpu = rli; break;\n case RLIMIT_FSIZE: ncs.ce->limits->fsize = rli; break;\n case RLIMIT_DATA: ncs.ce->limits->data = rli; break;\n case RLIMIT_STACK: ncs.ce->limits->stack = rli; break;\n case RLIMIT_CORE: ncs.ce->limits->core = rli; break;\n case RLIMIT_RSS: ncs.ce->limits->rss = rli; break;\n case RLIMIT_NPROC: ncs.ce->limits->nproc = rli; break;\n case RLIMIT_NOFILE: ncs.ce->limits->nofile = rli; break;\n case RLIMIT_MEMLOCK: ncs.ce->limits->memlock = rli; break;\n#ifndef BSD\n case RLIMIT_AS: ncs.ce->limits->as = rli; break;\n case RLIMIT_MSGQUEUE: ncs.ce->limits->msgqueue = rli; break;\n case RLIMIT_NICE: ncs.ce->limits->nice = rli; break;\n case RLIMIT_RTTIME: ncs.ce->limits->rttime = rli; break;\n case RLIMIT_RTPRIO: ncs.ce->limits->rtprio = rli; break;\n case RLIMIT_SIGPENDING: ncs.ce->limits->sigpending = rli; break;\n#endif \/* BSD *\/\n default: fmt::print(stderr, \"{}: Bad RLIMIT_type specified.\\n\", __func__);\n std::exit(EXIT_FAILURE);\n }\n}\n\nstatic void addcstlist(ParseCfgState &ncs, cronentry_t::cst_list &list,\n int wildcard, int min, int max)\n{\n int low = ncs.v_int;\n int high = wildcard;\n if (ncs.intv2_exist)\n high = ncs.v_int2;\n\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (low > high) {\n \/* discontinuous range, split into two continuous rules... *\/\n list.emplace_back(std::make_pair(low, max));\n list.emplace_back(std::make_pair(min, high));\n } else {\n \/* handle continuous ranges normally *\/\n list.emplace_back(std::make_pair(low, high));\n }\n}\n\nstatic void setgroupv(ParseCfgState &ncs)\n{\n if (nk_gidbyname(ncs.v_str, &ncs.ce->group)) {\n fmt::print(stderr, \"{}: nonexistent group specified at line {}\\n\",\n __func__, ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n}\n\nstatic void setuserv(ParseCfgState &ncs)\n{\n if (nk_uidgidbyname(ncs.v_str, &ncs.ce->user, &ncs.ce->group)) {\n fmt::print(stderr, \"{}: nonexistent user specified at line {}\\n\",\n __func__, ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n}\n\nstruct pckm {\n pckm() : st(nullptr), cs(0) {}\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n ncs.ce->command = std::string(pckm.st, p - pckm.st);\n boost::algorithm::replace_all(ncs.ce->command, \"\\\\\\\\\", \"\\\\\");\n boost::algorithm::replace_all(ncs.ce->command, \"\\\\ \", \" \");\n }\n action ArgEn { ncs.ce->args = std::string(pckm.st, p - pckm.st); }\n\n sptab = [ \\t];\n cmdstr = ([^\\0 \\t] | '\\\\\\\\' | '\\\\ ')+;\n cmd = sptab* (cmdstr > St % CmdEn);\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args?;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(ParseCfgState &ncs)\n{\n char *p = ncs.v_str;\n const char *pe = ncs.v_str + ncs.v_strlen;\n const char *eof = pe;\n\n struct pckm pckm;\n\n if (ncs.cmdret != 0) {\n ncs.cmdret = -3;\n fmt::print(stderr, \"Duplicate 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs.cmdret = -1;\n fmt::print(stderr, \"Malformed 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs.cmdret = 1;\n else {\n ncs.cmdret = -2;\n fmt::print(stderr, \"Incomplete 'command' value at line {}\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n}\n\nstatic void create_ce(ParseCfgState &ncs)\n{\n assert(!ncs.ce);\n ncs.ce = nk::make_unique();\n ncs.cmdret = 0;\n ncs.runat = false;\n}\n\nstatic inline void debug_print_ce(const ParseCfgState &ncs)\n{\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"-=- finish_ce -=-\\n\");\n fmt::print(stderr, \"id: {}\\n\", ncs.ce->id);\n fmt::print(stderr, \"command: {}\\n\", ncs.ce->command);\n fmt::print(stderr, \"args: {}\\n\", ncs.ce->args);\n fmt::print(stderr, \"chroot: {}\\n\", ncs.ce->chroot);\n fmt::print(stderr, \"numruns: {}\\n\", ncs.ce->numruns);\n fmt::print(stderr, \"maxruns: {}\\n\", ncs.ce->maxruns);\n fmt::print(stderr, \"journal: {}\\n\", ncs.ce->journal);\n fmt::print(stderr, \"user: {}\\n\", ncs.ce->user);\n fmt::print(stderr, \"group: {}\\n\", ncs.ce->group);\n for (const auto &i: ncs.ce->month)\n fmt::print(stderr, \"month: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ncs.ce->day)\n fmt::print(stderr, \"day: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ncs.ce->weekday)\n fmt::print(stderr, \"weekday: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ncs.ce->hour)\n fmt::print(stderr, \"hour: [{},{}]\\n\", i.first, i.second);\n for (const auto &i: ncs.ce->minute)\n fmt::print(stderr, \"minute: [{},{}]\\n\", i.first, i.second);\n fmt::print(stderr, \"interval: {}\\n\", ncs.ce->interval);\n fmt::print(stderr, \"exectime: {}\\n\", ncs.ce->exectime);\n fmt::print(stderr, \"lasttime: {}\\n\", ncs.ce->lasttime);\n}\n\nstatic inline void debug_print_ce_history(const ParseCfgState &ncs)\n{\n if (!gflags_debug)\n return;\n fmt::print(stderr, \"[{}]->numruns = {}\\n\", ncs.ce->id, ncs.ce->numruns);\n fmt::print(stderr, \"[{}]->exectime = {}\\n\", ncs.ce->id, ncs.ce->exectime);\n fmt::print(stderr, \"[{}]->lasttime = {}\\n\", ncs.ce->id, ncs.ce->lasttime);\n}\n\nstatic void finish_ce(ParseCfgState &ncs)\n{\n if (!ncs.ce)\n return;\n debug_print_ce(ncs);\n\n if (ncs.ce->id <= 0\n || (ncs.ce->interval <= 0 && ncs.ce->exectime <= 0)\n || ncs.ce->command.empty() || ncs.cmdret < 1) {\n if (gflags_debug)\n fmt::print(stderr, \"===> IGNORE\\n\");\n ncs.ce.reset();\n return;\n }\n if (gflags_debug)\n fmt::print(stderr, \"===> ADD\\n\");\n\n \/* we have a job to insert *\/\n if (ncs.runat) { \/* runat task *\/\n auto forced_exectime = ncs.ce->exectime;\n get_history(ncs.ce);\n ncs.ce->exectime = forced_exectime;\n debug_print_ce_history(ncs);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (!ncs.ce->numruns)\n ncs.stack.emplace_back(std::move(ncs.ce));\n else\n ncs.deadstack.emplace_back(std::move(ncs.ce));\n } else { \/* interval task *\/\n get_history(ncs.ce);\n debug_print_ce_history(ncs);\n set_initial_exectime(*ncs.ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs.ce->maxruns == 0 || ncs.ce->numruns < ncs.ce->maxruns)\n && ncs.ce->exectime != 0)\n ncs.stack.emplace_back(std::move(ncs.ce));\n else\n ncs.deadstack.emplace_back(std::move(ncs.ce));\n }\n ncs.ce.reset();\n}\n\n%%{\n machine ncrontab;\n access ncs.;\n\n spc = [ \\t];\n eqsep = spc* '=' spc*;\n\n action TUnitSt { ncs.time_st = p; ncs.v_time = 0; }\n action TSecEn { ncs.v_time += atoi(ncs.time_st); }\n action TMinEn { ncs.v_time += 60 * atoi(ncs.time_st); }\n action THrEn { ncs.v_time += 3600 * atoi(ncs.time_st); }\n action TDayEn { ncs.v_time += 86400 * atoi(ncs.time_st); }\n action TWeekEn { ncs.v_time += 604800 * atoi(ncs.time_st); }\n\n action IntValSt {\n ncs.intv_st = p;\n ncs.v_int = ncs.v_int2 = 0;\n ncs.intv2_exist = false;\n }\n action IntValEn { ncs.v_int = atoi(ncs.intv_st); }\n action IntVal2St { ncs.intv2_st = p; }\n action IntVal2En {\n ncs.v_int2 = atoi(ncs.intv2_st);\n ncs.intv2_exist = true;\n }\n\n action StrValSt { ncs.strv_st = p; ncs.v_strlen = 0; }\n action StrValEn {\n ncs.v_strlen = p - ncs.strv_st;\n if (ncs.v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs.v_str, sizeof ncs.v_str,\n \"%.*s\", (int)ncs.v_strlen, ncs.strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs.v_str) {\n fmt::print(stderr, \"error parsing line {} in crontab; too long?\\n\",\n ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn);\n timeval = t_any (spc* t_any)*;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))?;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn);\n\n action JournalEn { ncs.ce->journal = true; }\n journal = 'journal'i % JournalEn;\n\n action RunAtEn {\n ncs.runat = true;\n ncs.ce->exectime = ncs.v_int;\n ncs.ce->maxruns = 1;\n ncs.ce->journal = true;\n }\n action MaxRunsEn {\n if (!ncs.runat)\n ncs.ce->maxruns = ncs.v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n action LimMsgQueueEn { setlim(ncs, RLIMIT_MSGQUEUE); }\n action LimNiceEn { setlim(ncs, RLIMIT_NICE); }\n action LimRtTimeEn { setlim(ncs, RLIMIT_RTTIME); }\n action LimRtPrioEn { setlim(ncs, RLIMIT_RTPRIO); }\n action LimSigPendingEn { setlim(ncs, RLIMIT_SIGPENDING); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n lim_msgqueue = 'l_msgqueue'i eqsep intrangeval % LimMsgQueueEn;\n lim_nice = 'l_nice'i eqsep intrangeval % LimNiceEn;\n lim_rttime = 'l_rttime'i eqsep intrangeval % LimRtTimeEn;\n lim_rtprio = 'l_rtprio'i eqsep intrangeval % LimRtPrioEn;\n lim_sigpending = 'l_sigpending'i eqsep intrangeval % LimSigPendingEn;\n\n action IntervalEn { ncs.ce->interval = ncs.v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addcstlist(ncs, ncs.ce->month, 0, 1, 12); }\n action DayEn { addcstlist(ncs, ncs.ce->day, 0, 1, 31); }\n action WeekdayEn { addcstlist(ncs, ncs.ce->weekday, 0, 1, 7); }\n action HourEn { addcstlist(ncs, ncs.ce->hour, 24, 0, 23); }\n action MinuteEn { addcstlist(ncs, ncs.ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn {\n ncs.ce->chroot = std::string(ncs.v_str, ncs.v_strlen);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n lim_msgqueue | lim_nice | lim_rttime | lim_rtprio | lim_sigpending |\n maxruns | runat | journal;\n\n action JobIdSt { ncs.jobid_st = p; }\n action JobIdEn { ncs.ce->id = atoi(ncs.jobid_st); }\n action CreateCe { finish_ce(ncs); create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) % JobIdEn;\n\n main := jobid | cmds;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(ParseCfgState &ncs, const std::string &l)\n{\n const char *p = l.c_str();\n const char *pe = p + l.size();\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs.cs == ncrontab_error)\n return -1;\n if (ncs.cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(const std::string &path, const std::string &execfile,\n std::vector &stk,\n std::vector &deadstk)\n{\n struct ParseCfgState ncs(execfile, stk, deadstk);\n parse_history(ncs.execfile);\n\n std::string l;\n std::ifstream f(path, std::ifstream::in);\n if (f.fail() || f.bad() || f.eof()) {\n fmt::print(stderr, \"{}: failed to open file: '{}'\\n\", __func__, path);\n std::exit(EXIT_FAILURE);\n }\n while (1) {\n std::getline(f, l);\n ++ncs.linenum;\n if (f.eof())\n break;\n else if (f.bad() || f.fail()) {\n fmt::print(stderr, \"{}: io error fetching line of '{}'\\n\",\n __func__, path);\n std::exit(EXIT_FAILURE);\n }\n if (l.empty())\n continue;\n auto r = do_parse_config(ncs, l);\n if (r < 0) {\n fmt::print(stderr, \"{}: do_parse_config({}) failed at line {}\\n\",\n __func__, path, ncs.linenum);\n std::exit(EXIT_FAILURE);\n }\n }\n std::make_heap(stk.begin(), stk.end(), GtCronEntry);\n history_map.clear();\n cfg_reload = 1;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"364717ae89e4b2dac69103516ed5ebcc9d4af0bc","subject":"began commenting mtoc","message":"began commenting mtoc\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"confscanner.rl","new_file":"confscanner.rl","new_contents":"#include \"confscanner.h\"\n\nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::set;\nusing std::ifstream;\n\n%%{\n machine ConfFileScanner;\n write data;\n\n action st_tok { \/*cerr << \"st_tok\" << line << \"\\n\";*\/ tmp_p = p; }\n\n action string_tok {\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n action group_add\n {\n\/\/ cerr << \"in group add: \" << endl;\n if(match_at_level_[level_])\n {\n\/\/ cerr << \"do it\" << endl;\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/ clear groupset_ first, if we did not use '+='\n if(!arg_to_be_added_)\n groupset_.clear();\n\n groupset_.insert(tmp_string);\n }\n }\n\n action set_docu_block\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"brief\")\n cblock_ = &docuheader_;\n else if(tmp_string == \"doc\")\n cblock_ = &docubody_;\n else if(tmp_string == \"extra\")\n cblock_ = &docuextra_;\n }\n\n action set_docu_list\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"docu_list: \" << tmp_string << \"\\n\";\n if(tmp_string == \"params\")\n {\n \/\/cerr << \"paramlist\\n\";\n clist_ = ¶m_list_;\n }\n else if(tmp_string == \"return\")\n clist_ = &return_list_;\n }\n\n action set_docu_list_map\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"fields\")\n clistmap_ = &field_docu_;\n }\n\n # add line of a block to the cblock structure which can be one of\n # docublock, docuheader, docuextra or clist[] or clistmap[][]\n action add_block_line\n {\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n string :: size_type found = tmp_string.find_first_not_of(\" \\t\");\n if(found == string::npos || string(tmp_string.substr(found)) != \"\\\"\\\"\")\n {\n found = tmp_string.rfind(\"\\\"\");\n if(found != string::npos && string(tmp_string.substr(found-1)) == \"\\\"\\\"\")\n {\n \/\/cerr << \"a1: \" << tmp_string.substr(0, found-1) + '\\n';\n (*cblock_).push_back(tmp_string.substr(0, found-1) + '\\n');\n \/\/cerr << \"after a1: \" << param_list_[\"detailed_data\"][0];\n }\n else\n {\n \/\/cerr << \"a2: \" << tmp_string + '\\n';\n (*cblock_).push_back(tmp_string + '\\n');\n }\n }\n opt = true;\n }\n }\n\n # set the cblock pointer to clist_[value]\n action set_block_from_list\n {\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"ts:\" << tmp_string << \":ets\\n\";\/\/<< \" \" << tmp_p << \"p: \" << p << \"\\n\";\n cblock_ = &((*clist_)[tmp_string]);\n }\n }\n\n # set the cblock pointer to clist_[value1][value2]\n action set_block_from_listmap\n {\n string s(tmp_p, p-tmp_p);\n cblock_ = &((*clistmap_)[tmp_string][s]);\n }\n\n action reg_glob\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"glob: \" << tmp_string << endl;\n \/\/ TODO: use globlist_map\n globlist_stack_.back().push_back(tmp_string);\n }\n\n # end of file\n EOF = 0;\n\n # end of line (CRLF, LF)\n EOL = '\\r'? . '\\n';\n\n # any not end of file character\n default = ^0;\n\n # identifier\n IDENT = [A-Z]+;\n\n # matlab identifier\n MIDENT = [A-Za-z][A-Za-z0-9_]*;\n\n # glob expression\n GLOB = (default - [\\n \\t;\\{])+;\n\n # swallow till the end of line\n garbling := (default - '\\n')* . EOL @{line++;fret;};\n\n add_param_docu_block = ('brief'|'doc'|'extra');\n add_param_docu_list = ('params'|'return');\n add_param_docu_list_map = ('fields');\n\n # matlab white space or comment\n MWSOC = (\n [ \\t]\n | EOL @{line++;}\n | (('#'. any) -'##') @{ \/*cerr << \"l: \" << line << \"\\n\";*\/ fhold;fcall garbling; }\n );\n# MWSOC = ( [ \\t\\n]);\n\n # equal sign or += sign\n EQ = ('+'? @{arg_to_be_added_ = true;} . '=');\n\n # end of a rule sign\n ENDRULE = ';' @{arg_to_be_added_ = false;};\n\n # line in documentation block\n docu_block_line :=\n (\n ( ( default - [\"\\n] )+ >{ if(opt) { tmp_p = p; } } )\n |\n EOL @(add_block_line) @{line++;}\n |\n '\"\"\"' @(add_block_line) @{fret;}\n |\n ('\"'{1,2} . (default - [\"\\n])) @{ fhold; opt=false; }\n )**;\n\n # begin documentation block\n docu_block = ('\"\"\"'\n @{\n opt=true;\n if(!arg_to_be_added_)\n (*cblock_).clear();\n fcall docu_block_line;\n }\n );\n\n # documentation list item (something like key => value)\n docu_list_item =\n (\n ( MIDENT\n >{tmp_p = p;}\n %(set_block_from_list)\n ) . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n docu_list = (\n (\n '('\n . ( MWSOC* . docu_list_item . MWSOC* . ',')*\n . MWSOC* . docu_list_item . MWSOC* . ')'\n )\n |\n docu_list_item\n );\n\n docu_list_map_item =\n (\n (MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi\\n\";*\/} %(string_tok)\n )\n . '.'\n .(MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi2\\n\";*\/} %(set_block_from_listmap)\n )\n . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n docu_list_map = (\n (\n '('\n . ( MWSOC* . docu_list_map_item . MWSOC* . ',')*\n . MWSOC* . docu_list_map_item . MWSOC* . ')'\n )\n |\n docu_list_map_item\n );\n\n globlist =\n (GLOB >{\/*cerr << \"glob_list\";*\/ tmp_p = p;} %(reg_glob))\n . (MWSOC* . [ \\t]+ . MWSOC*\n . (GLOB >{\/*cerr << \"glob list2\";*\/ tmp_p = p;} %(reg_glob)))*;\n\n grouplist = (\n ((MIDENT >(st_tok)\n %(group_add))\n . ',')*\n .(MIDENT >(st_tok)\n %(group_add))\n );\n\n rules := (\n # glob list\n ('glob' .MWSOC* . '=' . MWSOC* . globlist . MWSOC* . '{')\n @{ check_glob_level_up(); fcall rules; }\n |\n (MWSOC)\n |\n # groups rule\n ('groups'. MWSOC* . EQ\n . MWSOC* . grouplist . MWSOC* . ENDRULE)\n |\n # add rule\n ('add(' %{\/*cerr << \"add:\" << '\\n';*\/ tmp_p = p;}\n . (\n ((add_param_docu_block\n %(set_docu_block)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* . docu_block . MWSOC* . ENDRULE )\n |\n ((add_param_docu_list\n %(set_docu_list)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list . MWSOC* . ENDRULE )\n |\n ((add_param_docu_list_map\n %(set_docu_list_map)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list_map . MWSOC* ENDRULE )\n )\n )\n |\n # go level down\n ('}') @{ go_level_down(); fret; }\n )*;\n\n main := (\n MWSOC\n | (\n (IDENT\n >(st_tok)\n %(string_tok)\n ). MWSOC* . ':=' . MWSOC*\n . (GLOB >st_tok @{\/*TODO*\/})\n . (MWSOC* . (GLOB >st_tok @{\/*TODO*\/}))*\n . MWSOC*\n . ';'\n )\n |\n '##' . [ \\t]* . EOL @{ line++; \/*cerr<<\"-> rules\\n\";*\/ fgoto rules; }\n )**;\n}%%\n\nvoid ConfFileScanner :: go_level_down()\n{\n globlist_stack_.pop_back();\n globlist_stack_.back().clear();\n level_--;\n}\n\nbool ConfFileScanner :: check_for_match(int l, const char * str,\n bool match_path_sep)\n{\n typedef GlobList :: iterator iterator;\n GlobList & gl = globlist_stack_[l];\n \/* cerr << \"globlist at level\" << l << \"\\n \";\n for(unsigned int i = 0; i < gl.size(); ++i)\n {\n cerr << gl[i] << \" \";\n }\n cerr << endl;*\/\n iterator endit = gl.end();\n int flags = (match_path_sep? FNM_PATHNAME : 0);\n \/\/ cerr << \"checking for match at level \" << l <<\" of string \" << str << \":\" << endl;\n for( iterator it = gl.begin(); it != endit; it++ )\n {\n \/\/ cerr << \"with pattern: \" << (*it).c_str() << endl;\n if(fnmatch((*it).c_str(), str, flags) == 0)\n {\n \/\/ cerr << \"SUCCESS!\" << endl;\n return true;\n }\n }\n return false;\n}\n\nbool ConfFileScanner :: check_glob_rec(int l, const string & s)\n{\n string str;\n string :: size_type found;\n if(l == level_+1)\n return true;\n\n found = s.find(\"\/\"); \/\/ try to match dir in path\n while(found != string :: npos)\n {\n str = s.substr(0, found);\n\/\/ cerr << str << endl;\n if(check_for_match(l, str.c_str())\n && check_glob_rec(l+1, s.substr(found+1)))\n return true;\n\n found = s.find(\"\/\", found+1); \/\/ try to match more dirs\n }\n if(l == level_) \/\/ try also to match the entire string\n {\n if(check_for_match(l, s.c_str()))\n return true;\n }\n\n return false;\n}\n\nvoid ConfFileScanner :: check_glob_level_up()\n{\n match_at_level_[level_+1] = check_glob_rec(0, filename_);\n\/* cerr << \"going one level up, match at this level is: \"\n << (match_at_level_[level_+1] ? \"true\" : \"false\");\n cerr << endl;*\/\n\n globlist_stack_.push_back(GlobList());\n level_++;\n}\n\nConfFileScanner\n:: ConfFileScanner(const std::string & filename)\n : line(1), have(0), top(0), opt(true),\n filename_(filename),\n confistream_(set_conffile()),\n level_(0),\n arg_to_be_added_(false)\n{\n globlist_stack_.push_back(GlobList());\n match_at_level_[0] = true;\n}\n\nconst char * ConfFileScanner ::\nset_conffile()\n{\n conffile_ = \"doxygen\/mtoc.conf\";\n return conffile_.c_str();\n}\n\nint ConfFileScanner :: execute()\n{\n \/\/cerr << \"execute\\n\";\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p;\/\/ *tmp_p2 = p;\n string tmp_string;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(1);\n }\n\n confistream_.read( p, space );\n int len = confistream_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( confistream_.eof() )\n {\n eof = pe;\n done = true;\n }\n else\n {\n \/* Find the last semicolon by searching backwards. This\n * is where we will stop processing on this iteration. *\/\n while ( *pe!= ';' && pe > p )\n pe--;\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == ConfFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"in conffile: PARSE ERROR in line \" << line << endl;\n exit(1);\n }\n\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n\n return 0;\n}\n\/* vim: set et sw=2 ft=ragel: *\/\n","old_contents":"#include \"confscanner.h\"\n\nextern \"C\" {\n#include \n}\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::set;\nusing std::ifstream;\n\n%%{\n machine ConfFileScanner;\n write data;\n\n action st_tok { \/*cerr << \"st_tok\" << line << \"\\n\";*\/ tmp_p = p; }\n\n action string_tok {\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n action group_add\n {\n\/\/ cerr << \"in group add: \" << endl;\n if(match_at_level_[level_])\n {\n\/\/ cerr << \"do it\" << endl;\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/ clear groupset_ first, if we did not use '+='\n if(!arg_to_be_added_)\n groupset_.clear();\n\n groupset_.insert(tmp_string);\n }\n }\n\n action set_docu_block\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"brief\")\n cblock_ = &docuheader_;\n else if(tmp_string == \"doc\")\n cblock_ = &docubody_;\n else if(tmp_string == \"extra\")\n cblock_ = &docuextra_;\n }\n\n action set_docu_list\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"docu_list: \" << tmp_string << \"\\n\";\n if(tmp_string == \"params\")\n {\n \/\/cerr << \"paramlist\\n\";\n clist_ = ¶m_list_;\n }\n else if(tmp_string == \"return\")\n clist_ = &return_list_;\n }\n\n action set_docu_list_map\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n if(tmp_string == \"fields\")\n clistmap_ = &field_docu_;\n }\n\n action add_block_line\n {\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n string :: size_type found = tmp_string.find_first_not_of(\" \\t\");\n if(found == string::npos || string(tmp_string.substr(found)) != \"\\\"\\\"\")\n {\n found = tmp_string.rfind(\"\\\"\");\n if(found != string::npos && string(tmp_string.substr(found-1)) == \"\\\"\\\"\")\n {\n \/\/cerr << \"a1: \" << tmp_string.substr(0, found-1) + '\\n';\n (*cblock_).push_back(tmp_string.substr(0, found-1) + '\\n');\n \/\/cerr << \"after a1: \" << param_list_[\"detailed_data\"][0];\n }\n else\n {\n \/\/cerr << \"a2: \" << tmp_string + '\\n';\n (*cblock_).push_back(tmp_string + '\\n');\n }\n }\n opt = true;\n }\n }\n\n action set_block_from_list\n {\n if(match_at_level_[level_])\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"ts:\" << tmp_string << \":ets\\n\";\/\/<< \" \" << tmp_p << \"p: \" << p << \"\\n\";\n cblock_ = &((*clist_)[tmp_string]);\n }\n }\n\n action set_block_from_listmap\n {\n string s(tmp_p, p-tmp_p);\n cblock_ = &((*clistmap_)[tmp_string][s]);\n }\n\n action reg_glob\n {\n tmp_string.assign(tmp_p, p-tmp_p);\n \/\/cerr << \"glob: \" << tmp_string << endl;\n \/\/ TODO: use globlist_map\n globlist_stack_.back().push_back(tmp_string);\n }\n\n EOF = 0;\n\n EOL = '\\r'? . '\\n';\n\n default = ^0;\n\n IDENT = [A-Z]+;\n\n MIDENT = [A-Za-z][A-Za-z0-9_]*;\n\n GLOB = (default - [\\n \\t;\\{])+;\n\n garbling := (default - '\\n')* . EOL @{line++;fret;};\n\n add_param_docu_block = ('brief'|'doc'|'extra');\n add_param_docu_list = ('params'|'return');\n add_param_docu_list_map = ('fields');\n\n MWSOC = (\n [ \\t]\n | EOL @{line++;}\n | (('#'. any) -'##') @{ \/*cerr << \"l: \" << line << \"\\n\";*\/ fhold;fcall garbling; }\n );\n# MWSOC = ( [ \\t\\n]);\n\n EQ = ('+'? @{arg_to_be_added_ = true;} . '=');\n\n ENDRULE = ';' @{arg_to_be_added_ = false;};\n\n docu_block_line :=\n (\n ( ( default - [\"\\n] )+ >{ if(opt) { tmp_p = p; } } )\n |\n EOL @(add_block_line) @{line++;}\n |\n '\"\"\"' @(add_block_line) @{fret;}\n |\n ('\"'{1,2} . (default - [\"\\n])) @{ fhold; opt=false; }\n )**;\n\n docu_block = ('\"\"\"'\n @{\n opt=true;\n if(!arg_to_be_added_)\n (*cblock_).clear();\n fcall docu_block_line;\n }\n );\n\n docu_list_item =\n (\n ( MIDENT\n >{tmp_p = p;}\n %(set_block_from_list)\n ) . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n docu_list = (\n (\n '('\n . ( MWSOC* . docu_list_item . MWSOC* . ',')*\n . MWSOC* . docu_list_item . MWSOC* . ')'\n )\n |\n docu_list_item\n );\n\n docu_list_map_item =\n (\n (MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi\\n\";*\/} %(string_tok)\n )\n . '.'\n .(MIDENT\n >{tmp_p = p;\/* cerr << \"dlmi2\\n\";*\/} %(set_block_from_listmap)\n )\n . MWSOC*\n . '=>' . MWSOC* . docu_block\n );\n\n docu_list_map = (\n (\n '('\n . ( MWSOC* . docu_list_map_item . MWSOC* . ',')*\n . MWSOC* . docu_list_map_item . MWSOC* . ')'\n )\n |\n docu_list_map_item\n );\n\n globlist =\n (GLOB >{\/*cerr << \"glob_list\";*\/ tmp_p = p;} %(reg_glob))\n . (MWSOC* . [ \\t]+ . MWSOC*\n . (GLOB >{\/*cerr << \"glob list2\";*\/ tmp_p = p;} %(reg_glob)))*;\n\n grouplist = (\n ((MIDENT >(st_tok)\n %(group_add))\n . ',')*\n .(MIDENT >(st_tok)\n %(group_add))\n );\n\n rules := (\n # glob list\n ('glob' .MWSOC* . '=' . MWSOC* . globlist . MWSOC* . '{')\n @{ check_glob_level_up(); fcall rules; }\n |\n (MWSOC)\n |\n # groups rule\n ('groups'. MWSOC* . EQ\n . MWSOC* . grouplist . MWSOC* . ENDRULE)\n |\n # add rule\n ('add(' %{\/*cerr << \"add:\" << '\\n';*\/ tmp_p = p;}\n . (\n ((add_param_docu_block\n %(set_docu_block)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* . docu_block . MWSOC* . ENDRULE )\n |\n ((add_param_docu_list\n %(set_docu_list)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list . MWSOC* . ENDRULE )\n |\n ((add_param_docu_list_map\n %(set_docu_list_map)\n )\n . ')' . MWSOC* . EQ\n . MWSOC* :> docu_list_map . MWSOC* ENDRULE )\n )\n )\n |\n # go level down\n ('}') @{ go_level_down(); fret; }\n )*;\n\n main := (\n MWSOC\n | (\n (IDENT\n >(st_tok)\n %(string_tok)\n ). MWSOC* . ':=' . MWSOC*\n . (GLOB >st_tok @{\/*TODO*\/})\n . (MWSOC* . (GLOB >st_tok @{\/*TODO*\/}))*\n . MWSOC*\n . ';'\n )\n |\n '##' . [ \\t]* . EOL @{ line++; \/*cerr<<\"-> rules\\n\";*\/ fgoto rules; }\n )**;\n}%%\n\nvoid ConfFileScanner :: go_level_down()\n{\n globlist_stack_.pop_back();\n globlist_stack_.back().clear();\n level_--;\n}\n\nbool ConfFileScanner :: check_for_match(int l, const char * str,\n bool match_path_sep)\n{\n typedef GlobList :: iterator iterator;\n GlobList & gl = globlist_stack_[l];\n \/* cerr << \"globlist at level\" << l << \"\\n \";\n for(unsigned int i = 0; i < gl.size(); ++i)\n {\n cerr << gl[i] << \" \";\n }\n cerr << endl;*\/\n iterator endit = gl.end();\n int flags = (match_path_sep? FNM_PATHNAME : 0);\n \/\/ cerr << \"checking for match at level \" << l <<\" of string \" << str << \":\" << endl;\n for( iterator it = gl.begin(); it != endit; it++ )\n {\n \/\/ cerr << \"with pattern: \" << (*it).c_str() << endl;\n if(fnmatch((*it).c_str(), str, flags) == 0)\n {\n \/\/ cerr << \"SUCCESS!\" << endl;\n return true;\n }\n }\n return false;\n}\n\nbool ConfFileScanner :: check_glob_rec(int l, const string & s)\n{\n string str;\n string :: size_type found;\n if(l == level_+1)\n return true;\n\/* if(l == level_)\n {*\/\n \/* true if all leading directories in path or the whole path string are\n * matched by pattern\n *\/\n\/* found = s.rfind(\"\/\");\n if(found != string::npos)\n {\n str = s.substr(0, found);\n if(check_for_match(l, str.c_str()))\n return true;\n }\n \/\/ else: try to match complete string\n return check_for_match(l, s.c_str());\n }*\/\n\n found = s.find(\"\/\"); \/\/ try to match dir in path\n while(found != string :: npos)\n {\n str = s.substr(0, found);\n\/\/ cerr << str << endl;\n if(check_for_match(l, str.c_str())\n && check_glob_rec(l+1, s.substr(found+1)))\n return true;\n\n found = s.find(\"\/\", found+1); \/\/ try to match more dirs\n }\n if(l == level_) \/\/ try also to match the entire string\n {\n if(check_for_match(l, s.c_str()))\n return true;\n }\n\n return false;\n}\n\nvoid ConfFileScanner :: check_glob_level_up()\n{\n match_at_level_[level_+1] = check_glob_rec(0, filename_);\n\/* cerr << \"going one level up, match at this level is: \"\n << (match_at_level_[level_+1] ? \"true\" : \"false\");\n cerr << endl;*\/\n\n globlist_stack_.push_back(GlobList());\n level_++;\n}\n\nConfFileScanner\n:: ConfFileScanner(const std::string & filename)\n : line(1), have(0), top(0), opt(true),\n filename_(filename),\n confistream_(set_conffile()),\n level_(0),\n arg_to_be_added_(false)\n{\n globlist_stack_.push_back(GlobList());\n match_at_level_[0] = true;\n}\n\nconst char * ConfFileScanner ::\nset_conffile()\n{\n conffile_ = \"doxygen\/mtoc.conf\";\n return conffile_.c_str();\n}\n\nint ConfFileScanner :: execute()\n{\n \/\/cerr << \"execute\\n\";\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p;\/\/ *tmp_p2 = p;\n string tmp_string;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"OUT OF BUFFER SPACE\" << endl;\n exit(1);\n }\n\n confistream_.read( p, space );\n int len = confistream_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( confistream_.eof() )\n {\n eof = pe;\n done = true;\n }\n else\n {\n \/* Find the last semicolon by searching backwards. This\n * is where we will stop processing on this iteration. *\/\n while ( *pe!= ';' && pe > p )\n pe--;\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == ConfFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"in conffile: PARSE ERROR in line \" << line << endl;\n exit(1);\n }\n\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n\n return 0;\n}\n\/* vim: set et sw=2 ft=ragel: *\/\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"41d986fde251644a724d130b4472910f158b8662","subject":"Ragel: allow for extra fields","message":"Ragel: allow for extra fields\n","repos":"pjotrp\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,pjotrp\/bioruby-vcf,gusevfe\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,CuppenResearch\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Parser for VCF-header info and format fields\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action endquoted {\n emit.call(:value,data,ts,p)\n }\n\n action kw {\n emit.call(:kw,data,ts,p)\n }\n \n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %endquoted squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %endquoted dquote;\n\n integer = ('+'|'-')?digit+;\n float = ('+'|'-')?digit+'.'digit+;\n assignment = '=';\n identifier = (alpha alnum+); \n str = (ss|dd)* ; \n boolean = '.';\n key_word = ( ('Type'|'Description'|'Source'|'Version'|identifier - ('ID'|'Number')) >mark %{ emit.call(:key_word,data,ts,p) } );\n any_value = ( str|( integer|float|boolean|identifier >mark %{ emit.call(:value,data,ts,p) } ));\n id_value = ( identifier >mark %{ emit.call(:value,data,ts,p) } );\n \n number_value = ( ( integer|boolean|'A'|'R'|'G' ) >mark %{ emit.call(:value,data,ts,p) } );\n\n id_kv = ( ( ('ID') %kw '=' id_value ) @!{ error_code=\"ID\"} );\n number_kv = ( ( ('Number') %kw '=' number_value ) @!{ error_code=\"Number\"} );\n key_value = ( id_kv | number_kv | (key_word '=' any_value) ) >mark @!{ error_code=\"key-value\" };\n \n main := ( '##' ('FILTER'|'FORMAT'|'INFO'|'ALT') '=') (('<'|',') key_value )* ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef self.run_lexer(buf, options = {})\n data = buf.unpack(\"c*\") if(buf.is_a?(String))\n eof = data.length\n values = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\" if options[:debug]==true\n values << [type,data[ts...p].pack('c*')]\n }\n\n error_code = nil\n \n %% write init;\n %% write exec;\n\n raise \"ERROR: \"+error_code+\" in \"+buf if error_code\n\n begin\n res = {}\n # p values\n values.each_slice(2) do | a,b |\n # p '*',a,b\n res[a[1]] = b[1]\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\n rescue\n print \"ERROR: \"\n p values\n end\n p res\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s|\n print s,\"\\n\"\n VcfHeader::RagelKeyValues.run_lexer(s, debug: false)\n}\n\nend","old_contents":"# Parser for VCF-header info and format fields\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action endquoted {\n emit.call(:value,data,ts,p)\n }\n\n action kw {\n emit.call(:kw,data,ts,p)\n }\n \n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %endquoted squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %endquoted dquote;\n\n integer = ('+'|'-')?digit+;\n float = ('+'|'-')?digit+'.'digit+;\n assignment = '=';\n identifier = (alpha alnum+); \n str = (ss|dd)* ; \n boolean = '.';\n key_word = ( ('Number'|'Type'|'Description') >mark %{ emit.call(:key_word,data,ts,p) } );\n any_value = ( (integer|float|boolean|identifier|str) >mark %{ emit.call(:value,data,ts,p) } );\n id_value = ( identifier >mark %{ emit.call(:value,data,ts,p) } );\n \n number_value = ( ( integer|boolean|'A' ) >mark %{ emit.call(:value,data,ts,p) } );\n\n id_kv = ( ( ('ID') %kw '=' id_value ) @!{ error_code=\"ID\"} );\n key_value = ( id_kv | (key_word '=' any_value) ) >mark @!{ error_code=\"key-value\" };\n \n main := ( '##' ('FILTER'|'FORMAT'|'INFO'|'ALT') '=') (('<'|',') key_value )* ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef self.run_lexer(buf, options = {})\n data = buf.unpack(\"c*\") if(buf.is_a?(String))\n eof = data.length\n values = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\" if options[:debug]==true\n values << [type,data[ts...p].pack('c*')]\n }\n\n error_code = nil\n \n %% write init;\n %% write exec;\n\n raise \"ERROR: \"+error_code+\" in \"+buf if error_code\n\n begin\n res = {}\n # p values\n values.each_slice(2) do | a,b |\n # p '*',a,b\n res[a[1]] = b[1]\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\n rescue\n print \"ERROR: \"\n p values\n end\n p res\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s|\n print s,\"\\n\"\n VcfHeader::RagelKeyValues.run_lexer(s, debug: false)\n}\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"90db579c0dec913fd5bf8171303acda5aeffb527","subject":"add in4 and in6 ops (to embed literals from C); and atoi, pto4, 4top, pto6, and 6top ops","message":"add in4 and in6 ops (to embed literals from C); and atoi, pto4, 4top, pto6, and 6top ops\n","repos":"wahern\/dns,wahern\/dns","old_file":"src\/spf.rl","new_file":"src\/spf.rl","new_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf setjmp(3) longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (SPF_DEBUG > 0) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-1) == S(-2) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\tlongjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (!(cond)) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic int vm_indexof(struct spf_vm *vm, int p) {\n\tif (p < 0)\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, t & vm_typeof(vm, p), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tfor (i = 0; i < n; i++) {\n\t\tvm_assert(vm, ++vm->pc < vm->end, EFAULT);\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tvm_assert(vm, fgets(sbuf, sizeof sbuf, stdin), ((ferror(stdin))? errno : EINVAL));\n\tspf_rtrim(sbuf, \"\\r\\n\");\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puti, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (SPF_DEBUG >= 2) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto strcode;\n\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nstrcode:\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t}\n\t\t}\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","old_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf setjmp(3) longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (SPF_DEBUG > 0) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned spf_atoi(const char *src) {\n\tunsigned i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > 0; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tterm->macros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str)\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-1) == S(-2) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\tlongjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (!(cond)) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic int vm_indexof(struct spf_vm *vm, int p) {\n\tif (p < 0)\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, t & vm_typeof(vm, p), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tchar *s;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\ts = (char *)v_;\n\t\tn = strlen(s) + 1;\n\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], s, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tfor (i = 0; i < n; i++) {\n\t\tvm_assert(vm, ++vm->pc < vm->end, EFAULT);\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pc = ++vm->pc;\n\n\twhile (pc < spf_lengthof(vm->code) && vm->code[pc])\n\t\tpc++;\n\n\tvm_assert(vm, pc < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[vm->pc], ++pc - vm->pc);\n\n\tvm->pc = pc;\n} \/* op_str() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tvm_assert(vm, fgets(sbuf, sizeof sbuf, stdin), ((ferror(stdin))? errno : EINVAL));\n\tspf_rtrim(sbuf, \"\\r\\n\");\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puti, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (SPF_DEBUG >= 2) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(&error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, 0, 0));\n\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfor (code = 0; code < spf_lengthof(vm_op); code++) {\n\t\t\t\tif (!vm_op[code].name)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!strcasecmp(line, vm_op[code].name))\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t}\n\t\t}\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"448ff61c3276ee86a3057ef373d62d80761abe60","subject":"Add UnicodeBlock detection","message":"Add UnicodeBlock detection\n","repos":"ammar\/regexp_parser,ammar\/regexp_parser,jhart-r7\/regexp_parser","old_file":"lib\/regexp_parser\/scanner\/property.rl","new_file":"lib\/regexp_parser\/scanner\/property.rl","new_contents":"%%{\n machine re_property;\n\n property_char = [pP];\n\n # Property names are being treated as case-insensitive, but it is not clear\n # yet if this applies to all flavors and in all encodings. A bug has just\n # been filed against ruby regarding this issue, see:\n # http:\/\/redmine.ruby-lang.org\/issues\/show\/4014\n property_name_unicode = 'alnum'i | 'alpha'i | 'any'i | 'ascii'i | 'blank'i |\n 'cntrl'i | 'digit'i | 'graph'i | 'lower'i | 'print'i |\n 'punct'i | 'space'i | 'upper'i | 'word'i | 'xdigit'i;\n\n property_name_posix = 'any'i | 'assigned'i | 'newline'i;\n\n property_name = property_name_unicode | property_name_posix;\n\n category_letter = [Ll] . [ultmo]?;\n category_mark = [Mm] . [nce]?;\n category_number = [Nn] . [dlo]?;\n category_punctuation = [Pp] . [cdseifo]?;\n category_symbol = [Ss] . [mcko]?;\n category_separator = [Zz] . [slp]?;\n category_codepoint = [Cc] . [cfson]?;\n\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n property_derived = 'math'i | 'alphabetic'i |\n 'lowercase'i | 'uppercase'i |\n 'id_start'i | 'id_continue'i |\n 'xid_start'i | 'xid_continue'i |\n 'grapheme_base'i | 'grapheme_extend'i |\n 'default_ignorable_code_point'i;\n\n property_age = 'age=1.1'i | 'age=2.0'i | 'age=2.1'i |\n 'age=3.0'i | 'age=3.1'i | 'age=3.2'i |\n 'age=4.0'i | 'age=4.1'i | 'age=5.0'i |\n 'age=5.1'i | 'age=5.2'i | 'age=6.0'i |\n 'age=6.1'i | 'age=6.2'i | 'age=6.3'i |\n 'age=7.0'i;\n\n property_script = (alpha | space | '_')+; # everything else\n\n property_sequence = property_char . '{' . '^'? (\n property_name | general_category |\n property_age | property_derived |\n property_script\n ) . '}';\n\n action premature_property_end {\n raise PrematureEndError.new('unicode property')\n }\n\n # Unicode properties scanner\n # --------------------------------------------------------------------------\n unicode_property := |*\n\n property_sequence < eof(premature_property_end) {\n text = text(data, ts, te, 1).first\n if in_set\n type = :set\n else\n type = text[1,1] == 'p' ? :property : :nonproperty\n end\n\n name = data[ts+2..te-2].pack('c*').gsub(\/[\\s_]\/,'').downcase\n if name[0].chr == '^'\n name = name[1..-1]\n type = :nonproperty\n end\n\n case name\n # Named\n when 'alnum'\n self.emit(type, :alnum, text, ts-1, te)\n when 'alpha'\n self.emit(type, :alpha, text, ts-1, te)\n when 'ascii'\n self.emit(type, :ascii, text, ts-1, te)\n when 'blank'\n self.emit(type, :blank, text, ts-1, te)\n when 'cntrl'\n self.emit(type, :cntrl, text, ts-1, te)\n when 'digit'\n self.emit(type, :digit, text, ts-1, te)\n when 'graph'\n self.emit(type, :graph, text, ts-1, te)\n when 'lower'\n self.emit(type, :lower, text, ts-1, te)\n when 'print'\n self.emit(type, :print, text, ts-1, te)\n when 'punct'\n self.emit(type, :punct, text, ts-1, te)\n when 'space'\n self.emit(type, :space, text, ts-1, te)\n when 'upper'\n self.emit(type, :upper, text, ts-1, te)\n when 'xdigit'\n self.emit(type, :xdigit, text, ts-1, te)\n\n when 'any'\n self.emit(type, :any, text, ts-1, te)\n when 'assigned'\n self.emit(type, :assigned, text, ts-1, te)\n when 'newline'\n self.emit(type, :newline, text, ts-1, te)\n when 'word'\n self.emit(type, :word, text, ts-1, te)\n\n # Letters\n when 'l', 'letter'\n self.emit(type, :letter_any, text, ts-1, te)\n when 'lu', 'uppercaseletter'\n self.emit(type, :letter_uppercase, text, ts-1, te)\n when 'll', 'lowercaseletter'\n self.emit(type, :letter_lowercase, text, ts-1, te)\n when 'lt', 'titlecaseletter'\n self.emit(type, :letter_titlecase, text, ts-1, te)\n when 'lm', 'modifierletter'\n self.emit(type, :letter_modifier, text, ts-1, te)\n when 'lo', 'otherletter'\n self.emit(type, :letter_other, text, ts-1, te)\n\n # Marks\n when 'm', 'mark'\n self.emit(type, :mark_any, text, ts-1, te)\n when 'mn', 'nonspacingmark'\n self.emit(type, :mark_nonspacing, text, ts-1, te)\n when 'mc', 'spacingmark'\n self.emit(type, :mark_spacing, text, ts-1, te)\n when 'me', 'enclosingmark'\n self.emit(type, :mark_enclosing, text, ts-1, te)\n\n # Numbers\n when 'n', 'number'\n self.emit(type, :number_any, text, ts-1, te)\n when 'nd', 'decimalnumber'\n self.emit(type, :number_decimal, text, ts-1, te)\n when 'nl', 'letternumber'\n self.emit(type, :number_letter, text, ts-1, te)\n when 'no', 'othernumber'\n self.emit(type, :number_other, text, ts-1, te)\n\n # Punctuation\n when 'p', 'punctuation'\n self.emit(type, :punct_any, text, ts-1, te)\n when 'pc', 'connectorpunctuation'\n self.emit(type, :punct_connector, text, ts-1, te)\n when 'pd', 'dashpunctuation'\n self.emit(type, :punct_dash, text, ts-1, te)\n when 'ps', 'openpunctuation'\n self.emit(type, :punct_open, text, ts-1, te)\n when 'pe', 'closepunctuation'\n self.emit(type, :punct_close, text, ts-1, te)\n when 'pi', 'initialpunctuation'\n self.emit(type, :punct_initial, text, ts-1, te)\n when 'pf', 'finalpunctuation'\n self.emit(type, :punct_final, text, ts-1, te)\n when 'po', 'otherpunctuation'\n self.emit(type, :punct_other, text, ts-1, te)\n\n # Symbols\n when 's', 'symbol'\n self.emit(type, :symbol_any, text, ts-1, te)\n when 'sm', 'mathsymbol'\n self.emit(type, :symbol_math, text, ts-1, te)\n when 'sc', 'currencysymbol'\n self.emit(type, :symbol_currency, text, ts-1, te)\n when 'sk', 'modifiersymbol'\n self.emit(type, :symbol_modifier, text, ts-1, te)\n when 'so', 'othersymbol'\n self.emit(type, :symbol_other, text, ts-1, te)\n\n # Separators\n when 'z', 'separator'\n self.emit(type, :separator_any, text, ts-1, te)\n when 'zs', 'spaceseparator'\n self.emit(type, :separator_space, text, ts-1, te)\n when 'zl', 'lineseparator'\n self.emit(type, :separator_line, text, ts-1, te)\n when 'zp', 'paragraphseparator'\n self.emit(type, :separator_para, text, ts-1, te)\n\n # Codepoints\n when 'c', 'other'\n self.emit(type, :other, text, ts-1, te)\n when 'cc', 'control'\n self.emit(type, :control, text, ts-1, te)\n when 'cf', 'format'\n self.emit(type, :format, text, ts-1, te)\n when 'cs', 'surrogate'\n self.emit(type, :surrogate, text, ts-1, te)\n when 'co', 'privateuse'\n self.emit(type, :private_use, text, ts-1, te)\n when 'cn', 'unassigned'\n self.emit(type, :unassigned, text, ts-1, te)\n\n # Age\n when 'age=1.1'\n self.emit(type, :age_1_1, text, ts-1, te)\n when 'age=2.0'\n self.emit(type, :age_2_0, text, ts-1, te)\n when 'age=2.1'\n self.emit(type, :age_2_1, text, ts-1, te)\n when 'age=3.0'\n self.emit(type, :age_3_0, text, ts-1, te)\n when 'age=3.1'\n self.emit(type, :age_3_1, text, ts-1, te)\n when 'age=3.2'\n self.emit(type, :age_3_2, text, ts-1, te)\n when 'age=4.0'\n self.emit(type, :age_4_0, text, ts-1, te)\n when 'age=4.1'\n self.emit(type, :age_4_1, text, ts-1, te)\n when 'age=5.0'\n self.emit(type, :age_5_0, text, ts-1, te)\n when 'age=5.1'\n self.emit(type, :age_5_1, text, ts-1, te)\n when 'age=5.2'\n self.emit(type, :age_5_2, text, ts-1, te)\n when 'age=6.0'\n self.emit(type, :age_6_0, text, ts-1, te)\n when 'age=6.1'\n self.emit(type, :age_6_1, text, ts-1, te)\n when 'age=6.2'\n self.emit(type, :age_6_2, text, ts-1, te)\n when 'age=6.3'\n self.emit(type, :age_6_3, text, ts-1, te)\n when 'age=7.0'\n self.emit(type, :age_7_0, text, ts-1, te)\n\n # Derived Properties\n when 'ahex', 'asciihexdigit'\n self.emit(type, :ascii_hex, text, ts-1, te)\n when 'alphabetic'\n self.emit(type, :alphabetic, text, ts-1, te)\n when 'cased'\n self.emit(type, :cased, text, ts-1, te)\n when 'cwcf', 'changeswhencasefolded'\n self.emit(type, :changes_when_casefolded, text, ts-1, te)\n when 'cwcm', 'changeswhencasemapped'\n self.emit(type, :changes_when_casemapped, text, ts-1, te)\n when 'cwl', 'changeswhenlowercased'\n self.emit(type, :changes_when_lowercased, text, ts-1, te)\n when 'cwt', 'changeswhentitlecased'\n self.emit(type, :changes_when_titlecased, text, ts-1, te)\n when 'cwu', 'changeswhenuppercased'\n self.emit(type, :changes_when_uppercased, text, ts-1, te)\n when 'ci', 'caseignorable'\n self.emit(type, :case_ignorable, text, ts-1, te)\n when 'bidic', 'bidicontrol'\n self.emit(type, :bidi_control, text, ts-1, te)\n when 'dash'\n self.emit(type, :dash, text, ts-1, te)\n when 'dep', 'deprecated'\n self.emit(type, :deprecated, text, ts-1, te)\n when 'di', 'defaultignorablecodepoint'\n self.emit(type, :default_ignorable_cp, text, ts-1, te)\n when 'dia', 'diacritic'\n self.emit(type, :diacritic, text, ts-1, te)\n when 'ext', 'extender'\n self.emit(type, :extender, text, ts-1, te)\n when 'grbase', 'graphemebase'\n self.emit(type, :grapheme_base, text, ts-1, te)\n when 'grext', 'graphemeextend'\n self.emit(type, :grapheme_extend, text, ts-1, te)\n when 'grlink', 'graphemelink' # NOTE: deprecated as of Unicode 5.0\n self.emit(type, :grapheme_link, text, ts-1, te)\n when 'hex', 'hexdigit'\n self.emit(type, :hex_digit, text, ts-1, te)\n when 'hyphen' # NOTE: deprecated as of Unicode 6.0\n self.emit(type, :hyphen, text, ts-1, te)\n when 'idc', 'idcontinue'\n self.emit(type, :id_continue, text, ts-1, te)\n when 'ideo', 'ideographic'\n self.emit(type, :ideographic, text, ts-1, te)\n when 'ids', 'idstart'\n self.emit(type, :id_start, text, ts-1, te)\n when 'idsb', 'idsbinaryoperator'\n self.emit(type, :ids_binary_op, text, ts-1, te)\n when 'idst', 'idstrinaryoperator'\n self.emit(type, :ids_trinary_op, text, ts-1, te)\n when 'joinc', 'joincontrol'\n self.emit(type, :join_control, text, ts-1, te)\n when 'loe', 'logicalorderexception'\n self.emit(type, :logical_order_exception, text, ts-1, te)\n when 'lowercase'\n self.emit(type, :lowercase, text, ts-1, te)\n when 'math'\n self.emit(type, :math, text, ts-1, te)\n when 'nchar', 'noncharactercodepoint'\n self.emit(type, :non_character_cp, text, ts-1, te)\n when 'oalpha', 'otheralphabetic'\n self.emit(type, :other_alphabetic, text, ts-1, te)\n when 'odi', 'otherdefaultignorablecodepoint'\n self.emit(type, :other_default_ignorable_cp, text, ts-1, te)\n when 'ogrext', 'othergraphemeextend'\n self.emit(type, :other_grapheme_extended, text, ts-1, te)\n when 'oidc', 'otheridcontinue'\n self.emit(type, :other_id_continue, text, ts-1, te)\n when 'oids', 'otheridstart'\n self.emit(type, :other_id_start, text, ts-1, te)\n when 'olower', 'otherlowercase'\n self.emit(type, :other_lowercase, text, ts-1, te)\n when 'omath', 'othermath'\n self.emit(type, :other_math, text, ts-1, te)\n when 'oupper', 'otheruppercase'\n self.emit(type, :other_uppercase, text, ts-1, te)\n when 'patsyn', 'patternsyntax'\n self.emit(type, :pattern_syntax, text, ts-1, te)\n when 'patws', 'patternwhitespace'\n self.emit(type, :pattern_whitespace, text, ts-1, te)\n when 'qmark', 'quotationmark'\n self.emit(type, :quotation_mark, text, ts-1, te)\n when 'radical'\n self.emit(type, :radical, text, ts-1, te)\n when 'sd', 'softdotted'\n self.emit(type, :soft_dotted, text, ts-1, te)\n when 'sterm'\n self.emit(type, :sentence_terminal, text, ts-1, te)\n when 'term', 'terminalpunctuation'\n self.emit(type, :terminal_punctuation, text, ts-1, te)\n when 'uideo', 'unifiedideograph'\n self.emit(type, :unified_ideograph, text, ts-1, te)\n when 'uppercase'\n self.emit(type, :uppercase, text, ts-1, te)\n when 'vs', 'variationselector'\n self.emit(type, :variation_selector, text, ts-1, te)\n when 'wspace', 'whitespace'\n self.emit(type, :whitespace, text, ts-1, te)\n when 'xids', 'xidstart'\n self.emit(type, :xid_start, text, ts-1, te)\n when 'xidc', 'xidcontinue'\n self.emit(type, :xid_continue, text, ts-1, te)\n\n # Scripts\n when 'aghb', 'caucasianalbanian'\n self.emit(type, :script_caucasian_albanian, text, ts-1, te)\n when 'arab', 'arabic'\n self.emit(type, :script_arabic, text, ts-1, te)\n when 'armi', 'imperialaramaic'\n self.emit(type, :script_imperial_aramaic, text, ts-1, te)\n when 'armn', 'armenian'\n self.emit(type, :script_armenian, text, ts-1, te)\n when 'avst', 'avestan'\n self.emit(type, :script_avestan, text, ts-1, te)\n when 'bali', 'balinese'\n self.emit(type, :script_balinese, text, ts-1, te)\n when 'bamu', 'bamum'\n self.emit(type, :script_bamum, text, ts-1, te)\n when 'bass', 'bassavah'\n self.emit(type, :script_bassa_vah, text, ts-1, te)\n when 'batk', 'batak'\n self.emit(type, :script_batak, text, ts-1, te)\n when 'beng', 'bengali'\n self.emit(type, :script_bengali, text, ts-1, te)\n when 'bopo', 'bopomofo'\n self.emit(type, :script_bopomofo, text, ts-1, te)\n when 'brah', 'brahmi'\n self.emit(type, :script_brahmi, text, ts-1, te)\n when 'brai', 'braille'\n self.emit(type, :script_braille, text, ts-1, te)\n when 'bugi', 'buginese'\n self.emit(type, :script_buginese, text, ts-1, te)\n when 'buhd', 'buhid'\n self.emit(type, :script_buhid, text, ts-1, te)\n when 'cans', 'canadianaboriginal'\n self.emit(type, :script_canadian_aboriginal, text, ts-1, te)\n when 'cari', 'carian'\n self.emit(type, :script_carian, text, ts-1, te)\n when 'cham'\n self.emit(type, :script_cham, text, ts-1, te)\n when 'cher', 'cherokee'\n self.emit(type, :script_cherokee, text, ts-1, te)\n when 'copt', 'coptic', 'qaac'\n self.emit(type, :script_coptic, text, ts-1, te)\n when 'cprt', 'cypriot'\n self.emit(type, :script_cypriot, text, ts-1, te)\n when 'cyrl', 'cyrillic'\n self.emit(type, :script_cyrillic, text, ts-1, te)\n when 'deva', 'devanagari'\n self.emit(type, :script_devanagari, text, ts-1, te)\n when 'dsrt', 'deseret'\n self.emit(type, :script_deseret, text, ts-1, te)\n when 'dupl', 'duployan'\n self.emit(type, :script_duployan, text, ts-1, te)\n when 'egyp', 'egyptianhieroglyphs'\n self.emit(type, :script_egyptian_hieroglyphs, text, ts-1, te)\n when 'elba', 'elbasan'\n self.emit(type, :script_elbasan, text, ts-1, te)\n when 'ethi', 'ethiopic'\n self.emit(type, :script_ethiopic, text, ts-1, te)\n when 'geor', 'georgian'\n self.emit(type, :script_georgian, text, ts-1, te)\n when 'glag', 'glagolitic'\n self.emit(type, :script_glagolitic, text, ts-1, te)\n when 'goth', 'gothic'\n self.emit(type, :script_gothic, text, ts-1, te)\n when 'gran', 'grantha'\n self.emit(type, :script_grantha, text, ts-1, te)\n when 'grek', 'greek'\n self.emit(type, :script_greek, text, ts-1, te)\n when 'gujr', 'gujarati'\n self.emit(type, :script_gujarati, text, ts-1, te)\n when 'guru', 'gurmukhi'\n self.emit(type, :script_gurmukhi, text, ts-1, te)\n when 'hang', 'hangul'\n self.emit(type, :script_hangul, text, ts-1, te)\n when 'hani', 'han'\n self.emit(type, :script_han, text, ts-1, te)\n when 'hano', 'hanunoo'\n self.emit(type, :script_hanunoo, text, ts-1, te)\n when 'hebr', 'hebrew'\n self.emit(type, :script_hebrew, text, ts-1, te)\n when 'hira', 'hiragana'\n self.emit(type, :script_hiragana, text, ts-1, te)\n when 'hmng', 'pahawhhmong'\n self.emit(type, :script_pahawh_hmong, text, ts-1, te)\n when 'hrkt', 'katakanaorhiragana'\n self.emit(type, :script_katakana_or_hiragana, text, ts-1, te)\n when 'ital', 'olditalic'\n self.emit(type, :script_old_italic, text, ts-1, te)\n when 'java', 'javanese'\n self.emit(type, :script_javanese, text, ts-1, te)\n when 'kali', 'kayahli'\n self.emit(type, :script_kayah_li, text, ts-1, te)\n when 'kana', 'katakana'\n self.emit(type, :script_katakana, text, ts-1, te)\n when 'khar', 'kharoshthi'\n self.emit(type, :script_kharoshthi, text, ts-1, te)\n when 'khmr', 'khmer'\n self.emit(type, :script_khmer, text, ts-1, te)\n when 'khoj', 'khojki'\n self.emit(type, :script_khojki, text, ts-1, te)\n when 'knda', 'kannada'\n self.emit(type, :script_kannada, text, ts-1, te)\n when 'kthi', 'kaithi'\n self.emit(type, :script_kaithi, text, ts-1, te)\n when 'lana', 'taitham'\n self.emit(type, :script_tai_tham, text, ts-1, te)\n when 'laoo', 'lao'\n self.emit(type, :script_lao, text, ts-1, te)\n when 'latn', 'latin'\n self.emit(type, :script_latin, text, ts-1, te)\n when 'lepc', 'lepcha'\n self.emit(type, :script_lepcha, text, ts-1, te)\n when 'limb', 'limbu'\n self.emit(type, :script_limbu, text, ts-1, te)\n when 'lina', 'lineara'\n self.emit(type, :script_linear_a, text, ts-1, te)\n when 'linb', 'linearb'\n self.emit(type, :script_linear_b, text, ts-1, te)\n when 'lisu'\n self.emit(type, :script_lisu, text, ts-1, te)\n when 'lyci', 'lycian'\n self.emit(type, :script_lycian, text, ts-1, te)\n when 'lydi', 'lydian'\n self.emit(type, :script_lydian, text, ts-1, te)\n when 'mlym', 'malayalam'\n self.emit(type, :script_malayalam, text, ts-1, te)\n when 'mahj', 'mahajani'\n self.emit(type, :script_mahajani, text, ts-1, te)\n when 'mand', 'mandaic'\n self.emit(type, :script_mandaic, text, ts-1, te)\n when 'mani', 'manichaean'\n self.emit(type, :script_manichaean, text, ts-1, te)\n when 'mend', 'mendekikakui'\n self.emit(type, :script_mende_kikakui, text, ts-1, te)\n when 'modi'\n self.emit(type, :script_modi, text, ts-1, te)\n when 'mong', 'mongolian'\n self.emit(type, :script_mongolian, text, ts-1, te)\n when 'mroo', 'mro'\n self.emit(type, :script_mro, text, ts-1, te)\n when 'mtei', 'meeteimayek'\n self.emit(type, :script_meetei_mayek, text, ts-1, te)\n when 'mymr', 'myanmar'\n self.emit(type, :script_myanmar, text, ts-1, te)\n when 'narb', 'oldnortharabian'\n self.emit(type, :script_old_north_arabian, text, ts-1, te)\n when 'nbat', 'nabataean'\n self.emit(type, :script_nabataean, text, ts-1, te)\n when 'nkoo', 'nko'\n self.emit(type, :script_nko, text, ts-1, te)\n when 'ogam', 'ogham'\n self.emit(type, :script_ogham, text, ts-1, te)\n when 'olck', 'olchiki'\n self.emit(type, :script_ol_chiki, text, ts-1, te)\n when 'orkh', 'oldturkic'\n self.emit(type, :script_old_turkic, text, ts-1, te)\n when 'orya', 'oriya'\n self.emit(type, :script_oriya, text, ts-1, te)\n when 'osma', 'osmanya'\n self.emit(type, :script_osmanya, text, ts-1, te)\n when 'palm', 'palmyrene'\n self.emit(type, :script_palmyrene, text, ts-1, te)\n when 'pauc', 'paucinhau'\n self.emit(type, :script_pau_cin_hau, text, ts-1, te)\n when 'perm', 'oldpermic'\n self.emit(type, :script_old_permic, text, ts-1, te)\n when 'phag', 'phagspa'\n self.emit(type, :script_phags_pa, text, ts-1, te)\n when 'phli', 'inscriptionalpahlavi'\n self.emit(type, :script_inscriptional_pahlavi, text, ts-1, te)\n when 'phlp', 'psalterpahlavi'\n self.emit(type, :script_psalter_pahlavi, text, ts-1, te)\n when 'phnx', 'phoenician'\n self.emit(type, :script_phoenician, text, ts-1, te)\n when 'prti', 'inscriptionalparthian'\n self.emit(type, :script_inscriptional_parthian, text, ts-1, te)\n when 'rjng', 'rejang'\n self.emit(type, :script_rejang, text, ts-1, te)\n when 'runr', 'runic'\n self.emit(type, :script_runic, text, ts-1, te)\n when 'samr', 'samaritan'\n self.emit(type, :script_samaritan, text, ts-1, te)\n when 'sarb', 'oldsoutharabian'\n self.emit(type, :script_old_south_arabian, text, ts-1, te)\n when 'saur', 'saurashtra'\n self.emit(type, :script_saurashtra, text, ts-1, te)\n when 'shaw', 'shavian'\n self.emit(type, :script_shavian, text, ts-1, te)\n when 'sidd', 'siddham'\n self.emit(type, :script_siddham, text, ts-1, te)\n when 'sind', 'khudawadi'\n self.emit(type, :script_khudawadi, text, ts-1, te)\n when 'sinh', 'sinhala'\n self.emit(type, :script_sinhala, text, ts-1, te)\n when 'sund', 'sundanese'\n self.emit(type, :script_sundanese, text, ts-1, te)\n when 'sylo', 'sylotinagri'\n self.emit(type, :script_syloti_nagri, text, ts-1, te)\n when 'syrc', 'syriac'\n self.emit(type, :script_syriac, text, ts-1, te)\n when 'tagb', 'tagbanwa'\n self.emit(type, :script_tagbanwa, text, ts-1, te)\n when 'tale', 'taile'\n self.emit(type, :script_tai_le, text, ts-1, te)\n when 'talu', 'newtailue'\n self.emit(type, :script_new_tai_lue, text, ts-1, te)\n when 'taml', 'tamil'\n self.emit(type, :script_tamil, text, ts-1, te)\n when 'tavt', 'taiviet'\n self.emit(type, :script_tai_viet, text, ts-1, te)\n when 'telu', 'telugu'\n self.emit(type, :script_telugu, text, ts-1, te)\n when 'tfng', 'tifinagh'\n self.emit(type, :script_tifinagh, text, ts-1, te)\n when 'tglg', 'tagalog'\n self.emit(type, :script_tagalog, text, ts-1, te)\n when 'thaa', 'thaana'\n self.emit(type, :script_thaana, text, ts-1, te)\n when 'thai'\n self.emit(type, :script_thai, text, ts-1, te)\n when 'tibt', 'tibetan'\n self.emit(type, :script_tibetan, text, ts-1, te)\n when 'tirh', 'tirhuta'\n self.emit(type, :script_tirhuta, text, ts-1, te)\n when 'ugar', 'ugaritic'\n self.emit(type, :script_ugaritic, text, ts-1, te)\n when 'vaii', 'vai'\n self.emit(type, :script_vai, text, ts-1, te)\n when 'wara', 'warangciti'\n self.emit(type, :script_warang_citi, text, ts-1, te)\n when 'xpeo', 'oldpersian'\n self.emit(type, :script_old_persian, text, ts-1, te)\n when 'xsux', 'cuneiform'\n self.emit(type, :script_cuneiform, text, ts-1, te)\n when 'yiii', 'yi'\n self.emit(type, :script_yi, text, ts-1, te)\n when 'zinh', 'inherited', 'qaai'\n self.emit(type, :script_inherited, text, ts-1, te)\n when 'zyyy', 'common'\n self.emit(type, :script_common, text, ts-1, te)\n when 'zzzz', 'unknown'\n self.emit(type, :script_unknown, text, ts-1, te)\n\n # Unicode blocks\n when 'inalphabetic_presentation_forms'\n self.emit(type, :block_inalphabetic_presentation_forms, text, ts-1, te)\n when 'inalphabeticpresentationforms'\n self.emit(type, :block_inalphabetic_presentation_forms, text, ts-1, te)\n when 'inarabicpresentationforms-a'\n self.emit(type, :block_inarabic_presentation_forms_a, text, ts-1, te)\n when 'inarabicpresentationforms-b'\n self.emit(type, :block_inarabic_presentation_forms_b, text, ts-1, te)\n when 'inarabic'\n self.emit(type, :block_inarabic, text, ts-1, te)\n when 'inarmenian'\n self.emit(type, :block_inarmenian, text, ts-1, te)\n when 'inarrows'\n self.emit(type, :block_inarrows, text, ts-1, te)\n when 'inbasiclatin'\n self.emit(type, :block_inbasic_latin, text, ts-1, te)\n when 'inbengali'\n self.emit(type, :block_inbengali, text, ts-1, te)\n when 'inblockelements'\n self.emit(type, :block_inblock_elements, text, ts-1, te)\n when 'inbopomofoextended'\n self.emit(type, :block_inbopomofo_extended, text, ts-1, te)\n when 'inbopomofo'\n self.emit(type, :block_inbopomofo, text, ts-1, te)\n when 'inboxdrawing'\n self.emit(type, :block_inbox_drawing, text, ts-1, te)\n when 'inbraillepatterns'\n self.emit(type, :block_inbraille_patterns, text, ts-1, te)\n when 'inbuhid'\n self.emit(type, :block_inbuhid, text, ts-1, te)\n when 'incjkcompatibilityforms'\n self.emit(type, :block_incjk_compatibility_forms, text, ts-1, te)\n when 'incjkcompatibilityideographs'\n self.emit(type, :block_incjk_compatibility_ideographs, text, ts-1, te)\n when 'incjkcompatibility'\n self.emit(type, :block_incjk_compatibility, text, ts-1, te)\n when 'incjkradicalssupplement'\n self.emit(type, :block_incjk_radicals_supplement, text, ts-1, te)\n when 'incjksymbolsandpunctuation'\n self.emit(type, :block_incjk_symbols_and_punctuation, text, ts-1, te)\n when 'incjkunifiedideographsextensiona'\n self.emit(type, :block_incjk_unified_ideographs_extension_a, text, ts-1, te)\n when 'incjkunifiedideographs'\n self.emit(type, :block_incjk_unified_ideographs, text, ts-1, te)\n when 'incherokee'\n self.emit(type, :block_incherokee, text, ts-1, te)\n when 'incombiningdiacriticalmarksforsymbols'\n self.emit(type, :block_incombining_diacritical_marks_for_symbols, text, ts-1, te)\n when 'incombiningdiacriticalmarks'\n self.emit(type, :block_incombining_diacritical_marks, text, ts-1, te)\n when 'incombininghalfmarks'\n self.emit(type, :block_incombining_half_marks, text, ts-1, te)\n when 'incontrolpictures'\n self.emit(type, :block_incontrol_pictures, text, ts-1, te)\n when 'incurrencysymbols'\n self.emit(type, :block_incurrency_symbols, text, ts-1, te)\n when 'incyrillicsupplementary'\n self.emit(type, :block_incyrillic_supplementary, text, ts-1, te)\n when 'incyrillic'\n self.emit(type, :block_incyrillic, text, ts-1, te)\n when 'indevanagari'\n self.emit(type, :block_indevanagari, text, ts-1, te)\n when 'indingbats'\n self.emit(type, :block_indingbats, text, ts-1, te)\n when 'inenclosedalphanumerics'\n self.emit(type, :block_inenclosed_alphanumerics, text, ts-1, te)\n when 'inenclosedcjklettersandmonths'\n self.emit(type, :block_inenclosed_cjk_letters_and_months, text, ts-1, te)\n when 'inethiopic'\n self.emit(type, :block_inethiopic, text, ts-1, te)\n when 'ingeneralpunctuation'\n self.emit(type, :block_ingeneral_punctuation, text, ts-1, te)\n when 'ingeometricshapes'\n self.emit(type, :block_ingeometric_shapes, text, ts-1, te)\n when 'ingeorgian'\n self.emit(type, :block_ingeorgian, text, ts-1, te)\n when 'ingreekextended'\n self.emit(type, :block_ingreek_extended, text, ts-1, te)\n when 'ingreekandcoptic'\n self.emit(type, :block_ingreek_and_coptic, text, ts-1, te)\n when 'ingujarati'\n self.emit(type, :block_ingujarati, text, ts-1, te)\n when 'ingurmukhi'\n self.emit(type, :block_ingurmukhi, text, ts-1, te)\n when 'inhalfwidthandfullwidthforms'\n self.emit(type, :block_inhalfwidth_and_fullwidth_forms, text, ts-1, te)\n when 'inhangulcompatibilityjamo'\n self.emit(type, :block_inhangul_compatibility_jamo, text, ts-1, te)\n when 'inhanguljamo'\n self.emit(type, :block_inhangul_jamo, text, ts-1, te)\n when 'inhangulsyllables'\n self.emit(type, :block_inhangul_syllables, text, ts-1, te)\n when 'inhanunoo'\n self.emit(type, :block_inhanunoo, text, ts-1, te)\n when 'inhebrew'\n self.emit(type, :block_inhebrew, text, ts-1, te)\n when 'inhighprivateusesurrogates'\n self.emit(type, :block_inhigh_private_use_surrogates, text, ts-1, te)\n when 'inhighsurrogates'\n self.emit(type, :block_inhigh_surrogates, text, ts-1, te)\n when 'inhiragana'\n self.emit(type, :block_inhiragana, text, ts-1, te)\n when 'inipaextensions'\n self.emit(type, :block_inipa_extensions, text, ts-1, te)\n when 'inideographicdescriptioncharacters'\n self.emit(type, :block_inideographic_description_characters, text, ts-1, te)\n when 'inkanbun'\n self.emit(type, :block_inkanbun, text, ts-1, te)\n when 'inkangxiradicals'\n self.emit(type, :block_inkangxi_radicals, text, ts-1, te)\n when 'inkannada'\n self.emit(type, :block_inkannada, text, ts-1, te)\n when 'inkatakanaphoneticextensions'\n self.emit(type, :block_inkatakana_phonetic_extensions, text, ts-1, te)\n when 'inkatakana'\n self.emit(type, :block_inkatakana, text, ts-1, te)\n when 'inkhmersymbols'\n self.emit(type, :block_inkhmer_symbols, text, ts-1, te)\n when 'inkhmer'\n self.emit(type, :block_inkhmer, text, ts-1, te)\n when 'inlao'\n self.emit(type, :block_inlao, text, ts-1, te)\n when 'inlatin-1supplement'\n self.emit(type, :block_inlatin_1_supplement, text, ts-1, te)\n when 'inlatinextended-a'\n self.emit(type, :block_inlatin_extended_a, text, ts-1, te)\n when 'inlatinextended-b'\n self.emit(type, :block_inlatin_extended_b, text, ts-1, te)\n when 'inlatinextendedadditional'\n self.emit(type, :block_inlatin_extended_additional, text, ts-1, te)\n when 'inletterlikesymbols'\n self.emit(type, :block_inletterlike_symbols, text, ts-1, te)\n when 'inlimbu'\n self.emit(type, :block_inlimbu, text, ts-1, te)\n when 'inlowsurrogates'\n self.emit(type, :block_inlow_surrogates, text, ts-1, te)\n when 'inmalayalam'\n self.emit(type, :block_inmalayalam, text, ts-1, te)\n when 'inmathematicaloperators'\n self.emit(type, :block_inmathematical_operators, text, ts-1, te)\n when 'inmiscellaneousmathematicalsymbols-a'\n self.emit(type, :block_inmiscellaneous_mathematical_symbols_a, text, ts-1, te)\n when 'inmiscellaneousmathematicalsymbols-b'\n self.emit(type, :block_inmiscellaneous_mathematical_symbols_b, text, ts-1, te)\n when 'inmiscellaneoussymbolsandarrows'\n self.emit(type, :block_inmiscellaneous_symbols_and_arrows, text, ts-1, te)\n when 'inmiscellaneoussymbols'\n self.emit(type, :block_inmiscellaneous_symbols, text, ts-1, te)\n when 'inmiscellaneoustechnical'\n self.emit(type, :block_inmiscellaneous_technical, text, ts-1, te)\n when 'inmongolian'\n self.emit(type, :block_inmongolian, text, ts-1, te)\n when 'inmyanmar'\n self.emit(type, :block_inmyanmar, text, ts-1, te)\n when 'innumberforms'\n self.emit(type, :block_innumber_forms, text, ts-1, te)\n when 'inogham'\n self.emit(type, :block_inogham, text, ts-1, te)\n when 'inopticalcharacterrecognition'\n self.emit(type, :block_inoptical_character_recognition, text, ts-1, te)\n when 'inoriya'\n self.emit(type, :block_inoriya, text, ts-1, te)\n when 'inphoneticextensions'\n self.emit(type, :block_inphonetic_extensions, text, ts-1, te)\n when 'inprivateusearea'\n self.emit(type, :block_inprivate_use_area, text, ts-1, te)\n when 'inrunic'\n self.emit(type, :block_inrunic, text, ts-1, te)\n when 'insinhala'\n self.emit(type, :block_insinhala, text, ts-1, te)\n when 'insmallformvariants'\n self.emit(type, :block_insmall_form_variants, text, ts-1, te)\n when 'inspacingmodifierletters'\n self.emit(type, :block_inspacing_modifier_letters, text, ts-1, te)\n when 'inspecials'\n self.emit(type, :block_inspecials, text, ts-1, te)\n when 'insuperscriptsandsubscripts'\n self.emit(type, :block_insuperscripts_and_subscripts, text, ts-1, te)\n when 'insupplementalarrows-a'\n self.emit(type, :block_insupplemental_arrows_a, text, ts-1, te)\n when 'insupplementalarrows-b'\n self.emit(type, :block_insupplemental_arrows_b, text, ts-1, te)\n when 'insupplementalmathematicaloperators'\n self.emit(type, :block_insupplemental_mathematical_operators, text, ts-1, te)\n when 'insyriac'\n self.emit(type, :block_insyriac, text, ts-1, te)\n when 'intagalog'\n self.emit(type, :block_intagalog, text, ts-1, te)\n when 'intagbanwa'\n self.emit(type, :block_intagbanwa, text, ts-1, te)\n when 'intaile'\n self.emit(type, :block_intai_le, text, ts-1, te)\n when 'intamil'\n self.emit(type, :block_intamil, text, ts-1, te)\n when 'intelugu'\n self.emit(type, :block_intelugu, text, ts-1, te)\n when 'inthaana'\n self.emit(type, :block_inthaana, text, ts-1, te)\n when 'inthai'\n self.emit(type, :block_inthai, text, ts-1, te)\n when 'intibetan'\n self.emit(type, :block_intibetan, text, ts-1, te)\n when 'inunifiedcanadianaboriginalsyllabics'\n self.emit(type, :block_inunified_canadian_aboriginal_syllabics, text, ts-1, te)\n when 'invariationselectors'\n self.emit(type, :block_invariation_selectors, text, ts-1, te)\n when 'inyiradicals'\n self.emit(type, :block_inyi_radicals, text, ts-1, te)\n when 'inyisyllables'\n self.emit(type, :block_inyi_syllables, text, ts-1, te)\n when 'inyijinghexagramsymbols'\n self.emit(type, :block_inyijing_hexagram_symbols, text, ts-1, te)\n\n else\n # Should this really be an error? Or would emitting\n # an :unknown for the property be better?\n #\n # self.emit(type, :unknown, text, ts-1, te)\n\n raise UnknownUnicodePropertyError.new(name)\n end\n\n fret;\n };\n *|;\n}%%\n","old_contents":"%%{\n machine re_property;\n\n property_char = [pP];\n\n # Property names are being treated as case-insensitive, but it is not clear\n # yet if this applies to all flavors and in all encodings. A bug has just\n # been filed against ruby regarding this issue, see:\n # http:\/\/redmine.ruby-lang.org\/issues\/show\/4014\n property_name_unicode = 'alnum'i | 'alpha'i | 'any'i | 'ascii'i | 'blank'i |\n 'cntrl'i | 'digit'i | 'graph'i | 'lower'i | 'print'i |\n 'punct'i | 'space'i | 'upper'i | 'word'i | 'xdigit'i;\n\n property_name_posix = 'any'i | 'assigned'i | 'newline'i;\n\n property_name = property_name_unicode | property_name_posix;\n\n category_letter = [Ll] . [ultmo]?;\n category_mark = [Mm] . [nce]?;\n category_number = [Nn] . [dlo]?;\n category_punctuation = [Pp] . [cdseifo]?;\n category_symbol = [Ss] . [mcko]?;\n category_separator = [Zz] . [slp]?;\n category_codepoint = [Cc] . [cfson]?;\n\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n property_derived = 'math'i | 'alphabetic'i |\n 'lowercase'i | 'uppercase'i |\n 'id_start'i | 'id_continue'i |\n 'xid_start'i | 'xid_continue'i |\n 'grapheme_base'i | 'grapheme_extend'i |\n 'default_ignorable_code_point'i; \n\n property_age = 'age=1.1'i | 'age=2.0'i | 'age=2.1'i |\n 'age=3.0'i | 'age=3.1'i | 'age=3.2'i |\n 'age=4.0'i | 'age=4.1'i | 'age=5.0'i |\n 'age=5.1'i | 'age=5.2'i | 'age=6.0'i |\n 'age=6.1'i | 'age=6.2'i | 'age=6.3'i |\n 'age=7.0'i;\n\n property_script = (alpha | space | '_')+; # everything else\n\n property_sequence = property_char . '{' . '^'? (\n property_name | general_category |\n property_age | property_derived |\n property_script\n ) . '}';\n\n action premature_property_end {\n raise PrematureEndError.new('unicode property')\n }\n\n # Unicode properties scanner\n # --------------------------------------------------------------------------\n unicode_property := |*\n\n property_sequence < eof(premature_property_end) {\n text = text(data, ts, te, 1).first\n if in_set\n type = :set\n else\n type = text[1,1] == 'p' ? :property : :nonproperty\n end\n\n name = data[ts+2..te-2].pack('c*').gsub(\/[\\s_]\/,'').downcase\n if name[0].chr == '^'\n name = name[1..-1]\n type = :nonproperty\n end\n\n case name\n # Named\n when 'alnum'\n self.emit(type, :alnum, text, ts-1, te)\n when 'alpha'\n self.emit(type, :alpha, text, ts-1, te)\n when 'ascii'\n self.emit(type, :ascii, text, ts-1, te)\n when 'blank'\n self.emit(type, :blank, text, ts-1, te)\n when 'cntrl'\n self.emit(type, :cntrl, text, ts-1, te)\n when 'digit'\n self.emit(type, :digit, text, ts-1, te)\n when 'graph'\n self.emit(type, :graph, text, ts-1, te)\n when 'lower'\n self.emit(type, :lower, text, ts-1, te)\n when 'print'\n self.emit(type, :print, text, ts-1, te)\n when 'punct'\n self.emit(type, :punct, text, ts-1, te)\n when 'space'\n self.emit(type, :space, text, ts-1, te)\n when 'upper'\n self.emit(type, :upper, text, ts-1, te)\n when 'xdigit'\n self.emit(type, :xdigit, text, ts-1, te)\n\n when 'any'\n self.emit(type, :any, text, ts-1, te)\n when 'assigned'\n self.emit(type, :assigned, text, ts-1, te)\n when 'newline'\n self.emit(type, :newline, text, ts-1, te)\n when 'word'\n self.emit(type, :word, text, ts-1, te)\n\n # Letters\n when 'l', 'letter'\n self.emit(type, :letter_any, text, ts-1, te)\n when 'lu', 'uppercaseletter'\n self.emit(type, :letter_uppercase, text, ts-1, te)\n when 'll', 'lowercaseletter'\n self.emit(type, :letter_lowercase, text, ts-1, te)\n when 'lt', 'titlecaseletter'\n self.emit(type, :letter_titlecase, text, ts-1, te)\n when 'lm', 'modifierletter'\n self.emit(type, :letter_modifier, text, ts-1, te)\n when 'lo', 'otherletter'\n self.emit(type, :letter_other, text, ts-1, te)\n\n # Marks\n when 'm', 'mark'\n self.emit(type, :mark_any, text, ts-1, te)\n when 'mn', 'nonspacingmark'\n self.emit(type, :mark_nonspacing, text, ts-1, te)\n when 'mc', 'spacingmark'\n self.emit(type, :mark_spacing, text, ts-1, te)\n when 'me', 'enclosingmark'\n self.emit(type, :mark_enclosing, text, ts-1, te)\n\n # Numbers\n when 'n', 'number'\n self.emit(type, :number_any, text, ts-1, te)\n when 'nd', 'decimalnumber'\n self.emit(type, :number_decimal, text, ts-1, te)\n when 'nl', 'letternumber'\n self.emit(type, :number_letter, text, ts-1, te)\n when 'no', 'othernumber'\n self.emit(type, :number_other, text, ts-1, te)\n\n # Punctuation\n when 'p', 'punctuation'\n self.emit(type, :punct_any, text, ts-1, te)\n when 'pc', 'connectorpunctuation'\n self.emit(type, :punct_connector, text, ts-1, te)\n when 'pd', 'dashpunctuation'\n self.emit(type, :punct_dash, text, ts-1, te)\n when 'ps', 'openpunctuation'\n self.emit(type, :punct_open, text, ts-1, te)\n when 'pe', 'closepunctuation'\n self.emit(type, :punct_close, text, ts-1, te)\n when 'pi', 'initialpunctuation'\n self.emit(type, :punct_initial, text, ts-1, te)\n when 'pf', 'finalpunctuation'\n self.emit(type, :punct_final, text, ts-1, te)\n when 'po', 'otherpunctuation'\n self.emit(type, :punct_other, text, ts-1, te)\n\n # Symbols\n when 's', 'symbol'\n self.emit(type, :symbol_any, text, ts-1, te)\n when 'sm', 'mathsymbol'\n self.emit(type, :symbol_math, text, ts-1, te)\n when 'sc', 'currencysymbol'\n self.emit(type, :symbol_currency, text, ts-1, te)\n when 'sk', 'modifiersymbol'\n self.emit(type, :symbol_modifier, text, ts-1, te)\n when 'so', 'othersymbol'\n self.emit(type, :symbol_other, text, ts-1, te)\n\n # Separators\n when 'z', 'separator'\n self.emit(type, :separator_any, text, ts-1, te)\n when 'zs', 'spaceseparator'\n self.emit(type, :separator_space, text, ts-1, te)\n when 'zl', 'lineseparator'\n self.emit(type, :separator_line, text, ts-1, te)\n when 'zp', 'paragraphseparator'\n self.emit(type, :separator_para, text, ts-1, te)\n\n # Codepoints\n when 'c', 'other'\n self.emit(type, :other, text, ts-1, te)\n when 'cc', 'control'\n self.emit(type, :control, text, ts-1, te)\n when 'cf', 'format'\n self.emit(type, :format, text, ts-1, te)\n when 'cs', 'surrogate'\n self.emit(type, :surrogate, text, ts-1, te)\n when 'co', 'privateuse'\n self.emit(type, :private_use, text, ts-1, te)\n when 'cn', 'unassigned'\n self.emit(type, :unassigned, text, ts-1, te)\n\n # Age\n when 'age=1.1'\n self.emit(type, :age_1_1, text, ts-1, te)\n when 'age=2.0'\n self.emit(type, :age_2_0, text, ts-1, te)\n when 'age=2.1'\n self.emit(type, :age_2_1, text, ts-1, te)\n when 'age=3.0'\n self.emit(type, :age_3_0, text, ts-1, te)\n when 'age=3.1'\n self.emit(type, :age_3_1, text, ts-1, te)\n when 'age=3.2'\n self.emit(type, :age_3_2, text, ts-1, te)\n when 'age=4.0'\n self.emit(type, :age_4_0, text, ts-1, te)\n when 'age=4.1'\n self.emit(type, :age_4_1, text, ts-1, te)\n when 'age=5.0'\n self.emit(type, :age_5_0, text, ts-1, te)\n when 'age=5.1'\n self.emit(type, :age_5_1, text, ts-1, te)\n when 'age=5.2'\n self.emit(type, :age_5_2, text, ts-1, te)\n when 'age=6.0'\n self.emit(type, :age_6_0, text, ts-1, te)\n when 'age=6.1'\n self.emit(type, :age_6_1, text, ts-1, te)\n when 'age=6.2'\n self.emit(type, :age_6_2, text, ts-1, te)\n when 'age=6.3'\n self.emit(type, :age_6_3, text, ts-1, te)\n when 'age=7.0'\n self.emit(type, :age_7_0, text, ts-1, te)\n\n # Derived Properties\n when 'ahex', 'asciihexdigit'\n self.emit(type, :ascii_hex, text, ts-1, te)\n when 'alphabetic'\n self.emit(type, :alphabetic, text, ts-1, te)\n when 'cased'\n self.emit(type, :cased, text, ts-1, te)\n when 'cwcf', 'changeswhencasefolded'\n self.emit(type, :changes_when_casefolded, text, ts-1, te)\n when 'cwcm', 'changeswhencasemapped'\n self.emit(type, :changes_when_casemapped, text, ts-1, te)\n when 'cwl', 'changeswhenlowercased'\n self.emit(type, :changes_when_lowercased, text, ts-1, te)\n when 'cwt', 'changeswhentitlecased'\n self.emit(type, :changes_when_titlecased, text, ts-1, te)\n when 'cwu', 'changeswhenuppercased'\n self.emit(type, :changes_when_uppercased, text, ts-1, te)\n when 'ci', 'caseignorable'\n self.emit(type, :case_ignorable, text, ts-1, te)\n when 'bidic', 'bidicontrol'\n self.emit(type, :bidi_control, text, ts-1, te)\n when 'dash'\n self.emit(type, :dash, text, ts-1, te)\n when 'dep', 'deprecated'\n self.emit(type, :deprecated, text, ts-1, te)\n when 'di', 'defaultignorablecodepoint'\n self.emit(type, :default_ignorable_cp, text, ts-1, te)\n when 'dia', 'diacritic'\n self.emit(type, :diacritic, text, ts-1, te)\n when 'ext', 'extender'\n self.emit(type, :extender, text, ts-1, te)\n when 'grbase', 'graphemebase'\n self.emit(type, :grapheme_base, text, ts-1, te)\n when 'grext', 'graphemeextend'\n self.emit(type, :grapheme_extend, text, ts-1, te)\n when 'grlink', 'graphemelink' # NOTE: deprecated as of Unicode 5.0\n self.emit(type, :grapheme_link, text, ts-1, te)\n when 'hex', 'hexdigit'\n self.emit(type, :hex_digit, text, ts-1, te)\n when 'hyphen' # NOTE: deprecated as of Unicode 6.0\n self.emit(type, :hyphen, text, ts-1, te)\n when 'idc', 'idcontinue'\n self.emit(type, :id_continue, text, ts-1, te)\n when 'ideo', 'ideographic'\n self.emit(type, :ideographic, text, ts-1, te)\n when 'ids', 'idstart'\n self.emit(type, :id_start, text, ts-1, te)\n when 'idsb', 'idsbinaryoperator'\n self.emit(type, :ids_binary_op, text, ts-1, te)\n when 'idst', 'idstrinaryoperator'\n self.emit(type, :ids_trinary_op, text, ts-1, te)\n when 'joinc', 'joincontrol'\n self.emit(type, :join_control, text, ts-1, te)\n when 'loe', 'logicalorderexception'\n self.emit(type, :logical_order_exception, text, ts-1, te)\n when 'lowercase'\n self.emit(type, :lowercase, text, ts-1, te)\n when 'math'\n self.emit(type, :math, text, ts-1, te)\n when 'nchar', 'noncharactercodepoint'\n self.emit(type, :non_character_cp, text, ts-1, te)\n when 'oalpha', 'otheralphabetic'\n self.emit(type, :other_alphabetic, text, ts-1, te)\n when 'odi', 'otherdefaultignorablecodepoint'\n self.emit(type, :other_default_ignorable_cp, text, ts-1, te)\n when 'ogrext', 'othergraphemeextend'\n self.emit(type, :other_grapheme_extended, text, ts-1, te)\n when 'oidc', 'otheridcontinue'\n self.emit(type, :other_id_continue, text, ts-1, te)\n when 'oids', 'otheridstart'\n self.emit(type, :other_id_start, text, ts-1, te)\n when 'olower', 'otherlowercase'\n self.emit(type, :other_lowercase, text, ts-1, te)\n when 'omath', 'othermath'\n self.emit(type, :other_math, text, ts-1, te)\n when 'oupper', 'otheruppercase'\n self.emit(type, :other_uppercase, text, ts-1, te)\n when 'patsyn', 'patternsyntax'\n self.emit(type, :pattern_syntax, text, ts-1, te)\n when 'patws', 'patternwhitespace'\n self.emit(type, :pattern_whitespace, text, ts-1, te)\n when 'qmark', 'quotationmark'\n self.emit(type, :quotation_mark, text, ts-1, te)\n when 'radical'\n self.emit(type, :radical, text, ts-1, te)\n when 'sd', 'softdotted'\n self.emit(type, :soft_dotted, text, ts-1, te)\n when 'sterm'\n self.emit(type, :sentence_terminal, text, ts-1, te)\n when 'term', 'terminalpunctuation'\n self.emit(type, :terminal_punctuation, text, ts-1, te)\n when 'uideo', 'unifiedideograph'\n self.emit(type, :unified_ideograph, text, ts-1, te)\n when 'uppercase'\n self.emit(type, :uppercase, text, ts-1, te)\n when 'vs', 'variationselector'\n self.emit(type, :variation_selector, text, ts-1, te)\n when 'wspace', 'whitespace'\n self.emit(type, :whitespace, text, ts-1, te)\n when 'xids', 'xidstart'\n self.emit(type, :xid_start, text, ts-1, te)\n when 'xidc', 'xidcontinue'\n self.emit(type, :xid_continue, text, ts-1, te)\n\n # Scripts\n when 'aghb', 'caucasianalbanian'\n self.emit(type, :script_caucasian_albanian, text, ts-1, te)\n when 'arab', 'arabic'\n self.emit(type, :script_arabic, text, ts-1, te)\n when 'armi', 'imperialaramaic'\n self.emit(type, :script_imperial_aramaic, text, ts-1, te)\n when 'armn', 'armenian'\n self.emit(type, :script_armenian, text, ts-1, te)\n when 'avst', 'avestan'\n self.emit(type, :script_avestan, text, ts-1, te)\n when 'bali', 'balinese'\n self.emit(type, :script_balinese, text, ts-1, te)\n when 'bamu', 'bamum'\n self.emit(type, :script_bamum, text, ts-1, te)\n when 'bass', 'bassavah'\n self.emit(type, :script_bassa_vah, text, ts-1, te)\n when 'batk', 'batak'\n self.emit(type, :script_batak, text, ts-1, te)\n when 'beng', 'bengali'\n self.emit(type, :script_bengali, text, ts-1, te)\n when 'bopo', 'bopomofo'\n self.emit(type, :script_bopomofo, text, ts-1, te)\n when 'brah', 'brahmi'\n self.emit(type, :script_brahmi, text, ts-1, te)\n when 'brai', 'braille'\n self.emit(type, :script_braille, text, ts-1, te)\n when 'bugi', 'buginese'\n self.emit(type, :script_buginese, text, ts-1, te)\n when 'buhd', 'buhid'\n self.emit(type, :script_buhid, text, ts-1, te)\n when 'cans', 'canadianaboriginal'\n self.emit(type, :script_canadian_aboriginal, text, ts-1, te)\n when 'cari', 'carian'\n self.emit(type, :script_carian, text, ts-1, te)\n when 'cham'\n self.emit(type, :script_cham, text, ts-1, te)\n when 'cher', 'cherokee'\n self.emit(type, :script_cherokee, text, ts-1, te)\n when 'copt', 'coptic', 'qaac'\n self.emit(type, :script_coptic, text, ts-1, te)\n when 'cprt', 'cypriot'\n self.emit(type, :script_cypriot, text, ts-1, te)\n when 'cyrl', 'cyrillic'\n self.emit(type, :script_cyrillic, text, ts-1, te)\n when 'deva', 'devanagari'\n self.emit(type, :script_devanagari, text, ts-1, te)\n when 'dsrt', 'deseret'\n self.emit(type, :script_deseret, text, ts-1, te)\n when 'dupl', 'duployan'\n self.emit(type, :script_duployan, text, ts-1, te)\n when 'egyp', 'egyptianhieroglyphs'\n self.emit(type, :script_egyptian_hieroglyphs, text, ts-1, te)\n when 'elba', 'elbasan'\n self.emit(type, :script_elbasan, text, ts-1, te)\n when 'ethi', 'ethiopic'\n self.emit(type, :script_ethiopic, text, ts-1, te)\n when 'geor', 'georgian'\n self.emit(type, :script_georgian, text, ts-1, te)\n when 'glag', 'glagolitic'\n self.emit(type, :script_glagolitic, text, ts-1, te)\n when 'goth', 'gothic'\n self.emit(type, :script_gothic, text, ts-1, te)\n when 'gran', 'grantha'\n self.emit(type, :script_grantha, text, ts-1, te)\n when 'grek', 'greek'\n self.emit(type, :script_greek, text, ts-1, te)\n when 'gujr', 'gujarati'\n self.emit(type, :script_gujarati, text, ts-1, te)\n when 'guru', 'gurmukhi'\n self.emit(type, :script_gurmukhi, text, ts-1, te)\n when 'hang', 'hangul'\n self.emit(type, :script_hangul, text, ts-1, te)\n when 'hani', 'han'\n self.emit(type, :script_han, text, ts-1, te)\n when 'hano', 'hanunoo'\n self.emit(type, :script_hanunoo, text, ts-1, te)\n when 'hebr', 'hebrew'\n self.emit(type, :script_hebrew, text, ts-1, te)\n when 'hira', 'hiragana'\n self.emit(type, :script_hiragana, text, ts-1, te)\n when 'hmng', 'pahawhhmong'\n self.emit(type, :script_pahawh_hmong, text, ts-1, te)\n when 'hrkt', 'katakanaorhiragana'\n self.emit(type, :script_katakana_or_hiragana, text, ts-1, te)\n when 'ital', 'olditalic'\n self.emit(type, :script_old_italic, text, ts-1, te)\n when 'java', 'javanese'\n self.emit(type, :script_javanese, text, ts-1, te)\n when 'kali', 'kayahli'\n self.emit(type, :script_kayah_li, text, ts-1, te)\n when 'kana', 'katakana'\n self.emit(type, :script_katakana, text, ts-1, te)\n when 'khar', 'kharoshthi'\n self.emit(type, :script_kharoshthi, text, ts-1, te)\n when 'khmr', 'khmer'\n self.emit(type, :script_khmer, text, ts-1, te)\n when 'khoj', 'khojki'\n self.emit(type, :script_khojki, text, ts-1, te)\n when 'knda', 'kannada'\n self.emit(type, :script_kannada, text, ts-1, te)\n when 'kthi', 'kaithi'\n self.emit(type, :script_kaithi, text, ts-1, te)\n when 'lana', 'taitham'\n self.emit(type, :script_tai_tham, text, ts-1, te)\n when 'laoo', 'lao'\n self.emit(type, :script_lao, text, ts-1, te)\n when 'latn', 'latin'\n self.emit(type, :script_latin, text, ts-1, te)\n when 'lepc', 'lepcha'\n self.emit(type, :script_lepcha, text, ts-1, te)\n when 'limb', 'limbu'\n self.emit(type, :script_limbu, text, ts-1, te)\n when 'lina', 'lineara'\n self.emit(type, :script_linear_a, text, ts-1, te)\n when 'linb', 'linearb'\n self.emit(type, :script_linear_b, text, ts-1, te)\n when 'lisu'\n self.emit(type, :script_lisu, text, ts-1, te)\n when 'lyci', 'lycian'\n self.emit(type, :script_lycian, text, ts-1, te)\n when 'lydi', 'lydian'\n self.emit(type, :script_lydian, text, ts-1, te)\n when 'mlym', 'malayalam'\n self.emit(type, :script_malayalam, text, ts-1, te)\n when 'mahj', 'mahajani'\n self.emit(type, :script_mahajani, text, ts-1, te)\n when 'mand', 'mandaic'\n self.emit(type, :script_mandaic, text, ts-1, te)\n when 'mani', 'manichaean'\n self.emit(type, :script_manichaean, text, ts-1, te)\n when 'mend', 'mendekikakui'\n self.emit(type, :script_mende_kikakui, text, ts-1, te)\n when 'modi'\n self.emit(type, :script_modi, text, ts-1, te)\n when 'mong', 'mongolian'\n self.emit(type, :script_mongolian, text, ts-1, te)\n when 'mroo', 'mro'\n self.emit(type, :script_mro, text, ts-1, te)\n when 'mtei', 'meeteimayek'\n self.emit(type, :script_meetei_mayek, text, ts-1, te)\n when 'mymr', 'myanmar'\n self.emit(type, :script_myanmar, text, ts-1, te)\n when 'narb', 'oldnortharabian'\n self.emit(type, :script_old_north_arabian, text, ts-1, te)\n when 'nbat', 'nabataean'\n self.emit(type, :script_nabataean, text, ts-1, te)\n when 'nkoo', 'nko'\n self.emit(type, :script_nko, text, ts-1, te)\n when 'ogam', 'ogham'\n self.emit(type, :script_ogham, text, ts-1, te)\n when 'olck', 'olchiki'\n self.emit(type, :script_ol_chiki, text, ts-1, te)\n when 'orkh', 'oldturkic'\n self.emit(type, :script_old_turkic, text, ts-1, te)\n when 'orya', 'oriya'\n self.emit(type, :script_oriya, text, ts-1, te)\n when 'osma', 'osmanya'\n self.emit(type, :script_osmanya, text, ts-1, te)\n when 'palm', 'palmyrene'\n self.emit(type, :script_palmyrene, text, ts-1, te)\n when 'pauc', 'paucinhau'\n self.emit(type, :script_pau_cin_hau, text, ts-1, te)\n when 'perm', 'oldpermic'\n self.emit(type, :script_old_permic, text, ts-1, te)\n when 'phag', 'phagspa'\n self.emit(type, :script_phags_pa, text, ts-1, te)\n when 'phli', 'inscriptionalpahlavi'\n self.emit(type, :script_inscriptional_pahlavi, text, ts-1, te)\n when 'phlp', 'psalterpahlavi'\n self.emit(type, :script_psalter_pahlavi, text, ts-1, te)\n when 'phnx', 'phoenician'\n self.emit(type, :script_phoenician, text, ts-1, te)\n when 'prti', 'inscriptionalparthian'\n self.emit(type, :script_inscriptional_parthian, text, ts-1, te)\n when 'rjng', 'rejang'\n self.emit(type, :script_rejang, text, ts-1, te)\n when 'runr', 'runic'\n self.emit(type, :script_runic, text, ts-1, te)\n when 'samr', 'samaritan'\n self.emit(type, :script_samaritan, text, ts-1, te)\n when 'sarb', 'oldsoutharabian'\n self.emit(type, :script_old_south_arabian, text, ts-1, te)\n when 'saur', 'saurashtra'\n self.emit(type, :script_saurashtra, text, ts-1, te)\n when 'shaw', 'shavian'\n self.emit(type, :script_shavian, text, ts-1, te)\n when 'sidd', 'siddham'\n self.emit(type, :script_siddham, text, ts-1, te)\n when 'sind', 'khudawadi'\n self.emit(type, :script_khudawadi, text, ts-1, te)\n when 'sinh', 'sinhala'\n self.emit(type, :script_sinhala, text, ts-1, te)\n when 'sund', 'sundanese'\n self.emit(type, :script_sundanese, text, ts-1, te)\n when 'sylo', 'sylotinagri'\n self.emit(type, :script_syloti_nagri, text, ts-1, te)\n when 'syrc', 'syriac'\n self.emit(type, :script_syriac, text, ts-1, te)\n when 'tagb', 'tagbanwa'\n self.emit(type, :script_tagbanwa, text, ts-1, te)\n when 'tale', 'taile'\n self.emit(type, :script_tai_le, text, ts-1, te)\n when 'talu', 'newtailue'\n self.emit(type, :script_new_tai_lue, text, ts-1, te)\n when 'taml', 'tamil'\n self.emit(type, :script_tamil, text, ts-1, te)\n when 'tavt', 'taiviet'\n self.emit(type, :script_tai_viet, text, ts-1, te)\n when 'telu', 'telugu'\n self.emit(type, :script_telugu, text, ts-1, te)\n when 'tfng', 'tifinagh'\n self.emit(type, :script_tifinagh, text, ts-1, te)\n when 'tglg', 'tagalog'\n self.emit(type, :script_tagalog, text, ts-1, te)\n when 'thaa', 'thaana'\n self.emit(type, :script_thaana, text, ts-1, te)\n when 'thai' \n self.emit(type, :script_thai, text, ts-1, te)\n when 'tibt', 'tibetan'\n self.emit(type, :script_tibetan, text, ts-1, te)\n when 'tirh', 'tirhuta'\n self.emit(type, :script_tirhuta, text, ts-1, te)\n when 'ugar', 'ugaritic'\n self.emit(type, :script_ugaritic, text, ts-1, te)\n when 'vaii', 'vai'\n self.emit(type, :script_vai, text, ts-1, te)\n when 'wara', 'warangciti'\n self.emit(type, :script_warang_citi, text, ts-1, te)\n when 'xpeo', 'oldpersian'\n self.emit(type, :script_old_persian, text, ts-1, te)\n when 'xsux', 'cuneiform'\n self.emit(type, :script_cuneiform, text, ts-1, te)\n when 'yiii', 'yi'\n self.emit(type, :script_yi, text, ts-1, te)\n when 'zinh', 'inherited', 'qaai'\n self.emit(type, :script_inherited, text, ts-1, te)\n when 'zyyy', 'common'\n self.emit(type, :script_common, text, ts-1, te)\n when 'zzzz', 'unknown'\n self.emit(type, :script_unknown, text, ts-1, te)\n\n else\n # Should this really be an error? Or would emitting\n # an :unknown for the property be better?\n #\n # self.emit(type, :unknown, text, ts-1, te)\n\n raise UnknownUnicodePropertyError.new(name)\n end\n\n fret;\n };\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e36235634614852f0174981486fce8c9763c5135","subject":"Code cleanup.","message":"Code cleanup.\n","repos":"versatica\/mediasoup,versatica\/mediasoup,versatica\/mediasoup,versatica\/mediasoup,versatica\/mediasoup,versatica\/mediasoup,ibc\/MediaSoup,versatica\/mediasoup,ibc\/MediaSoup,versatica\/mediasoup,ibc\/MediaSoup,versatica\/mediasoup","old_file":"worker\/src\/Utils\/IP.rl","new_file":"worker\/src\/Utils\/IP.rl","new_contents":"#define MS_CLASS \"Utils::IP\"\n\/\/ #define MS_LOG_DEV\n\n#include \"Utils.h\"\n#include \"Logger.h\"\n#include \n\nnamespace Utils\n{\n\tint IP::GetFamily(const char *ip, size_t ip_len)\n\t{\n\t\tMS_TRACE();\n\n\t\tint ip_family = 0;\n\n\t\t\/**\n\t\t * Ragel: machine definition.\n\t\t *\/\n\t\t%%{\n\t\t\tmachine IPParser;\n\n\t\t\talphtype unsigned char;\n\n\t\t\taction on_ipv4\n\t\t\t{\n\t\t\t\tip_family = AF_INET;\n\t\t\t}\n\n\t\t\taction on_ipv6\n\t\t\t{\n\t\t\t\tip_family = AF_INET6;\n\t\t\t}\n\n\t\t\tinclude grammar \"grammar.rl\";\n\n\t\t\tmain := IPv4address @on_ipv4 |\n\t\t\t IPv6address @on_ipv6;\n\t\t}%%\n\n\t\t\/**\n\t\t * Ragel: %%write data\n\t\t * This generates Ragel's static variables.\n\t\t *\/\n\t\t%%write data;\n\n\t\t\/\/ Used by Ragel:\n\t\tsize_t cs;\n\t\tconst unsigned char* p;\n\t\tconst unsigned char* pe;\n\n\t\tp = (const unsigned char*)ip;\n\t\tpe = p + ip_len;\n\n\t\t\/**\n\t\t * Ragel: %%write init\n\t\t *\/\n\t\t%%write init;\n\n\t\t\/**\n\t\t * Ragel: %%write exec\n\t\t * This updates cs variable needed by Ragel.\n\t\t *\/\n\t\t%%write exec;\n\n\t\t\/\/ Ensure that the parsing has consumed all the given length.\n\t\tif (ip_len == (size_t)(p - (const unsigned char*)ip))\n\t\t\treturn ip_family;\n\t\telse\n\t\t\treturn AF_UNSPEC;\n\t}\n\n\tvoid IP::GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, uint16_t* port)\n\t{\n\t\tMS_TRACE();\n\n\t\tchar _ip[INET6_ADDRSTRLEN+1];\n\t\tint err;\n\n\t\tswitch (addr->sa_family)\n\t\t{\n\t\t\tcase AF_INET:\n\t\t\t{\n\t\t\t\terr = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip, INET_ADDRSTRLEN);\n\t\t\t\tif (err)\n\t\t\t\t\tMS_ABORT(\"uv_inet_ntop() failed: %s\", uv_strerror(err));\n\t\t\t\t*port = (uint16_t)ntohs(((struct sockaddr_in*)addr)->sin_port);\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase AF_INET6:\n\t\t\t{\n\t\t\t\terr = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip, INET6_ADDRSTRLEN);\n\t\t\t\tif (err)\n\t\t\t\t\tMS_ABORT(\"uv_inet_ntop() failed: %s\", uv_strerror(err));\n\t\t\t\t*port = (uint16_t)ntohs(((struct sockaddr_in6*)addr)->sin6_port);\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tMS_ABORT(\"unknown network family: %d\", (int)addr->sa_family);\n\t\t}\n\n\t\t*family = addr->sa_family;\n\t\tip.assign(_ip);\n\t}\n}\n","old_contents":"#define MS_CLASS \"Utils::IP\"\n\/\/ #define MS_LOG_DEV\n\n#include \"Utils.h\"\n#include \"Logger.h\"\n#include \n\nnamespace Utils\n{\n\tint IP::GetFamily(const char *ip, size_t ip_len)\n\t{\n\t\tMS_TRACE();\n\n\t\tint ip_family = 0;\n\n\t\t\/**\n\t\t * Ragel: machine definition\n\t\t *\/\n\t\t%%{\n\t\t\tmachine IPParser;\n\n\t\t\talphtype unsigned char;\n\n\t\t\taction on_ipv4\n\t\t\t{\n\t\t\t\tip_family = AF_INET;\n\t\t\t}\n\n\t\t\taction on_ipv6\n\t\t\t{\n\t\t\t\tip_family = AF_INET6;\n\t\t\t}\n\n\t\t\tinclude grammar \"grammar.rl\";\n\n\t\t\tmain := IPv4address @on_ipv4 |\n\t\t\t IPv6address @on_ipv6;\n\t\t}%%\n\n\t\t\/**\n\t\t * Ragel: %%write data\n\t\t * This generates Ragel's static variables.\n\t\t *\/\n\t\t%%write data;\n\n\t\t\/\/ Used by Ragel:\n\t\tsize_t cs;\n\t\tconst unsigned char* p;\n\t\tconst unsigned char* pe;\n\n\t\tp = (const unsigned char*)ip;\n\t\tpe = p + ip_len;\n\n\t\t\/**\n\t\t * Ragel: %%write init\n\t\t *\/\n\t\t%%write init;\n\n\t\t\/**\n\t\t * Ragel: %%write exec\n\t\t * This updates cs variable needed by Ragel.\n\t\t *\/\n\t\t%%write exec;\n\n\t\t\/\/ Ensure that the parsing has consumed all the given length.\n\t\tif (ip_len == (size_t)(p - (const unsigned char*)ip))\n\t\t\treturn ip_family;\n\t\telse\n\t\t\treturn AF_UNSPEC;\n\t}\n\n\tvoid IP::GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, uint16_t* port)\n\t{\n\t\tMS_TRACE();\n\n\t\tchar _ip[INET6_ADDRSTRLEN+1];\n\t\tint err;\n\n\t\tswitch (addr->sa_family)\n\t\t{\n\t\t\tcase AF_INET:\n\t\t\t\terr = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip, INET_ADDRSTRLEN);\n\t\t\t\tif (err)\n\t\t\t\t\tMS_ABORT(\"uv_inet_ntop() failed: %s\", uv_strerror(err));\n\t\t\t\t*port = (uint16_t)ntohs(((struct sockaddr_in*)addr)->sin_port);\n\t\t\t\tbreak;\n\t\t\tcase AF_INET6:\n\t\t\t\terr = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip, INET6_ADDRSTRLEN);\n\t\t\t\tif (err)\n\t\t\t\t\tMS_ABORT(\"uv_inet_ntop() failed: %s\", uv_strerror(err));\n\t\t\t\t*port = (uint16_t)ntohs(((struct sockaddr_in6*)addr)->sin6_port);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tMS_ABORT(\"unknown network family: %d\", (int)addr->sa_family);\n\t\t}\n\n\t\t*family = addr->sa_family;\n\t\tip.assign(_ip);\n\t}\n}\n","returncode":0,"stderr":"","license":"isc","lang":"Ragel in Ruby Host"} {"commit":"9e046ddb0162bdf98f62afb10fc14385cbb6eb87","subject":"Added support for escape sequences in strings (so now tqrepl works properly again)","message":"Added support for escape sequences in strings (so now tqrepl works properly again)\n","repos":"gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil","old_file":"Source\/Tranquil\/lex.rl","new_file":"Source\/Tranquil\/lex.rl","new_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")+ \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new]\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = [NSError errorWithDomain:kTQSyntaxErrorDomain\n code:kTQGenericError\n userInfo:[NSDictionary dictionaryWithObject:[e reason] forKey:@\"reason\"]];\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","old_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n string = '\"' strCont* '\"';\n constStr = \"@\" (string | [^\\n ;,\\]}.)`]+);\n lStr = '\"' strCont* lGuillmt;\n mStr = rGuillmt strCont* lGuillmt;\n rStr = rGuillmt strCont* '\"';\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")+ \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n lStr => { EmitStringToken(LSTR, 1, 2); ExprBeg(); };\n mStr => { EmitStringToken(MSTR, 2, 2); ExprBeg(); };\n rStr %{temp1 = p;} term => { EmitStringToken(RSTRNL, 2, 1+(te-temp1)); ExprBeg(); BacktrackTerm(); };\n rStr => { EmitStringToken(RSTR, 2, 1); };\n string %{temp1 = p;} term => { EmitStringToken(STRNL, 1, 1+(te-temp1)); ExprBeg(); BacktrackTerm(); };\n string => { EmitStringToken(STR, 1, 1); };\n\n nl => { IncrementLine(); };\n space;\n*|;\n\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n\n unsigned char *temp1, *temp2;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new]\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = [NSError errorWithDomain:kTQSyntaxErrorDomain\n code:kTQGenericError\n userInfo:[NSDictionary dictionaryWithObject:[e reason] forKey:@\"reason\"]];\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"dbf7c1075bb96c67388e8c3cf738583c920a1251","subject":"* fixed error in blank line paragraph detection (multiple newlines were consumed by whitespace rule)","message":"* fixed error in blank line paragraph detection (multiple newlines were consumed by whitespace rule)\n","repos":"schwa-lab\/libschwa,schwa-lab\/libschwa,schwa-lab\/libschwa,schwa-lab\/libschwa","old_file":"rules\/main.rl","new_file":"rules\/main.rl","new_contents":"\/* -*- Mode: C++; indent-tabs-mode: nil -*- *\/\n\n%%{\n machine tokenizer;\n\n action ignore {}\n action word { word_(WORD, dest, s); }\n action punct { punct_(PUNCTUATION, dest, s); }\n action end { end_(PUNCTUATION, dest, s); }\n action contraction { split_(WORD, CONTRACTION, dest, s); }\n action catchall {\n switch(errors){\n case ERROR_SKIP:\n break;\n case ERROR_CALL:\n error_(dest, s);\n break;\n case ERROR_THROW:\n die_(msg << \"stuck on character \" << (int)*p\n << \" at offset \" << (p - s.offset));\n break;\n default:\n die_(msg << \"illegal value \" << errors << \" for bad byte error handling\");\n }\n }\n\n main := |*\n single_quote => { single_quote_(dest, s, eof); };\n double_quote => { double_quote_(dest, s, eof); };\n\n open_single_quote => { open_single_quote_(dest, s); };\n close_single_quote => { close_single_quote_(dest, s); };\n\n open_double_quote => { open_double_quote_(dest, s); };\n close_double_quote => { close_double_quote_(dest, s); };\n\n full_stop => { terminator_(dest, s, \".\"); };\n question_mark => { terminator_(dest, s, \"?\"); };\n exclamation_mark => { terminator_(dest, s, \"!\"); };\n ellipsis => { terminator_(dest, s, \"...\"); };\n\n dash => { dash_or_item_(dest, s); };\n# [1-9][0-9]* \".\" => { number_or_item_(dest, s); };\n\n (space - newline | other_ws)+ | newline => ignore;\n newline{2,} => { sep_text_paragraph_(dest, s); };\n\n open_p_tag => { begin_html_paragraph_(dest, s); };\n close_p_tag => { end_html_paragraph_(dest, s); };\n sep_p_tag => { sep_html_paragraph_(dest, s); };\n\n open_ul_tag | open_ol_tag => { begin_html_list_(dest, s); };\n close_ul_tag | close_ol_tag => { end_html_list_(dest, s); };\n\n open_li_tag => { begin_html_item_(dest, s); };\n close_li_tag => { end_html_item_(dest, s); };\n\n html_tag | html_comment | script_tag | style_tag => ignore;\n\n neg => contraction;\n neg_error => contraction;\n letter+ cont_suffix => contraction;\n\n (letter+ \".\"? possessive) - abbrev_decade => { split_(WORD, POSSESSIVE, dest, s); };\n\n (numbers units) - abbrev_decade => { split_(NUMBER, UNIT, dest, s); };\n time_ambiguous meridian => { split_(NUMBER, UNIT, dest, s); };\n meridian_token | date_time => word;\n\n (integer | float) \"-\" alpha+ (\"-\" alpha+)* => word;\n\n \"and\/or\" | \"AND\/OR\" => word;\n\n cont_misc | acron | title => word;\n symbols => punct;\n end_punct => end;\n date_abbrev | state | addr => word;\n\n org | abbrev | lines | dollars | numbers | date_time => word;\n uri | host_name | email_address => word;\n default => word;\n\n any => catchall;\n *|;\n\n}%%\n","old_contents":"\/* -*- Mode: C++; indent-tabs-mode: nil -*- *\/\n\n%%{\n machine tokenizer;\n\n action ignore {}\n action word { word_(WORD, dest, s); }\n action punct { punct_(PUNCTUATION, dest, s); }\n action end { end_(PUNCTUATION, dest, s); }\n action contraction { split_(WORD, CONTRACTION, dest, s); }\n action catchall {\n switch(errors){\n case ERROR_SKIP:\n break;\n case ERROR_CALL:\n error_(dest, s);\n break;\n case ERROR_THROW:\n die_(msg << \"stuck on character \" << (int)*p\n << \" at offset \" << (p - s.offset));\n break;\n default:\n die_(msg << \"illegal value \" << errors << \" for bad byte error handling\");\n }\n }\n\n main := |*\n single_quote => { single_quote_(dest, s, eof); };\n double_quote => { double_quote_(dest, s, eof); };\n\n open_single_quote => { open_single_quote_(dest, s); };\n close_single_quote => { close_single_quote_(dest, s); };\n\n open_double_quote => { open_double_quote_(dest, s); };\n close_double_quote => { close_double_quote_(dest, s); };\n\n full_stop => { terminator_(dest, s, \".\"); };\n question_mark => { terminator_(dest, s, \"?\"); };\n exclamation_mark => { terminator_(dest, s, \"!\"); };\n ellipsis => { terminator_(dest, s, \"...\"); };\n\n dash => { dash_or_item_(dest, s); };\n# [1-9][0-9]* \".\" => { number_or_item_(dest, s); };\n\n (space | other_ws)+ | newline => ignore;\n newline {2,} => { sep_text_paragraph_(dest, s); };\n\n open_p_tag => { begin_html_paragraph_(dest, s); };\n close_p_tag => { end_html_paragraph_(dest, s); };\n sep_p_tag => { sep_html_paragraph_(dest, s); };\n\n open_ul_tag | open_ol_tag => { begin_html_list_(dest, s); };\n close_ul_tag | close_ol_tag => { end_html_list_(dest, s); };\n\n open_li_tag => { begin_html_item_(dest, s); };\n close_li_tag => { end_html_item_(dest, s); };\n\n html_tag | html_comment | script_tag | style_tag => ignore;\n\n neg => contraction;\n neg_error => contraction;\n letter+ cont_suffix => contraction;\n\n (letter+ \".\"? possessive) - abbrev_decade => { split_(WORD, POSSESSIVE, dest, s); };\n\n (numbers units) - abbrev_decade => { split_(NUMBER, UNIT, dest, s); };\n time_ambiguous meridian => { split_(NUMBER, UNIT, dest, s); };\n meridian_token | date_time => word;\n\n (integer | float) \"-\" alpha+ (\"-\" alpha+)* => word;\n\n \"and\/or\" | \"AND\/OR\" => word;\n\n cont_misc | acron | title => word;\n symbols => punct;\n end_punct => end;\n date_abbrev | state | addr => word;\n\n org | abbrev | lines | dollars | numbers | date_time => word;\n uri | host_name | email_address => word;\n default => word;\n\n any => catchall;\n *|;\n\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"62580c9fe8c6592e583071c743337ee113d2bb10","subject":"not using rigel no more","message":"not using rigel no more\n","repos":"thommay\/config-general-parser","old_file":"lib\/config_general_parser\/parser.rl","new_file":"lib\/config_general_parser\/parser.rl","new_contents":"","old_contents":"%%{\n\n machine config_general;\n \n attribute = ^(space | '=')+ %attributeName space* '=' space* ('\"' ^'\"'* %attribute '\"');\n \n main := space* element space*;\n}%%\n\n%% write data;\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"6f9bb2c23a61f3c88a95d9993736236a4dc8f3f6","subject":"Fixed parser bug where double quotes inside single quoted strings crashed","message":"Fixed parser bug where double quotes inside single quoted strings crashed\n","repos":"gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil","old_file":"Source\/Tranquil\/lex.rl","new_file":"Source\/Tranquil\/lex.rl","new_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\nenum {\n kTQStrTypeSimple,\n kTQStrTypeLeftOrMiddle,\n kTQStrTypeRight\n};\n#define PushStr(dblQuot, type) \\\n [strings addObject:[NSDictionary dictionaryWithObjectsAndKeys: \\\n [NSNumber numberWithBool:dblQuot], @\"dblQuot\", \\\n [NSNumber numberWithInt:type], @\"type\", \\\n [NSMutableData data], @\"value\", nil]];\n#define PopStr() ({ id last = [Str() retain]; [strings removeLastObject]; [last autorelease]; })\n#define StrData() [[strings lastObject] objectForKey:@\"value\"]\n#define Str() [[[NSMutableString alloc] initWithData:StrData() encoding:NSUTF8StringEncoding] autorelease]\n#define IsDblQuot() [[[strings lastObject] objectForKey:@\"dblQuot\"] boolValue]\n#define IsRstr() ([[[strings lastObject] objectForKey:@\"type\"] intValue] == kTQStrTypeRight)\n#define IsSimpleStr() ([[[strings lastObject] objectForKey:@\"type\"] intValue] == kTQStrTypeSimple)\n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n NSError *syntaxError;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n int tokenId_ = tokenId; \\\n id val_ = val; \\\n \/* NSLog(@\"emitting %d = '%@' on line: %d\", tokenId, val_, parserState.currentLine); *\/ \\\n Parse(parser, tokenId_, [TQToken withId:tokenId value:val_ line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken(tokenId, [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n else if(strncmp(\"else\", (const char*)p-3, 4) == 0) \\\n p -= 4; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) NSUInteger id, lineNumber;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.lineNumber = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n lGuillemet = 0xC2 0xAB; # \u00ab\n rGuillemet = 0xC2 0xBB; # \u00bb\n specialChar = 0xC2 | '\"' | \"'\" | '.' | ',' | ';' | ':' | '|' | '#' | '@' | '~' | '`' | '{' | '}' | '[' | ']' | '(' | ')' | '+' | '-' | '*' | '\/' | '%' | '=' | '<' | '>' | '^' | '\\\\' | '\\r' | '\\n' | space;\n\n char = (any - specialChar) | (0xC2 ^(0xAB|0xBB));\n constant = '_'* uupper char*;\n identifier = (char -- (uupper|udigit)) char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\"|\"else\");\n\n constStr = \"#\" (char | [:@#~+\\-*\/%=<>^])+;\n selector = char* \":\";\n\n regexCont = (ualnum | ascii) - '\/' - '\\\\';\n\nstring := |*\n '\\n' => { [StrData() appendBytes:\"\\n\" length:1]; IncrementLine(); };\n '\\\\n' => { [StrData() appendBytes:\"\\n\" length:1]; };\n '\\\\t' => { [StrData() appendBytes:\"\\t\" length:1]; };\n '\\\\r' => { [StrData() appendBytes:\"\\r\" length:1]; };\n '\\\\\"' => { [StrData() appendBytes:\"\\\"\" length:1]; };\n \"\\\\'\" => { [StrData() appendBytes:\"'\" length:1]; };\n \"\\\\\\\\\" => { [StrData() appendBytes:\"\\\\\" length:1]; };\n \"\\\\\" lGuillemet => { [StrData() appendBytes:\"\u00ab\" length:2]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n NSString *strVal = [NSString stringWithFormat:@\"%c\", (int)code];\n [StrData() appendData:[strVal dataUsingEncoding:NSUTF8StringEncoding]];\n };\n \"\\\\\" any => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n\n lGuillemet => { \n TQAssert(!IsSimpleStr(), @\"Interpolation is not allowed in constant strings\");\n _EmitToken(IsRstr() ? MSTR : LSTR, Str());\n fret;\n };\n '\"' term => {\n if(IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTRNL\n : (IsRstr() ? RSTRNL : STRNL);\n _EmitToken(tokId, PopStr());\n BacktrackTerm();\n fret;\n } else\n [StrData() appendBytes:\"\\\"\" length:1];\n };\n '\"' => {\n if(IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTR\n : (IsRstr() ? RSTR : STR);\n _EmitToken(tokId, PopStr());\n fret;\n } else\n [StrData() appendBytes:\"\\\"\" length:1];\n };\n \"'\" term => {\n if(!IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTRNL\n : (IsRstr() ? RSTRNL : STRNL);\n _EmitToken(tokId, PopStr());\n BacktrackTerm();\n fret;\n } else\n [StrData() appendBytes:\"'\" length:1];\n };\n \"'\" => {\n if(!IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTR\n : (IsRstr() ? RSTR : STR);\n _EmitToken(tokId, PopStr());\n fret;\n } else\n [StrData() appendBytes:\"'\" length:1];\n };\n\n any => { [StrData() appendBytes:ts length:1]; };\n*|;\n\nregex := |*\n '\\n' => { [StrData() appendBytes:\"\\n\" length:1]; IncrementLine(); };\n \"\\\\\/\" => { [StrData() appendBytes:\"\\\\\/\" length:1]; };\n \"\\\\\" => { [StrData() appendBytes:\"\\\\\" length:1]; };\n regexCont => { [StrData() appendBytes:ts length:1]; };\n \"\/\" [im]* term => { [StrData() appendBytes:\"\/\" length:1];\n _EmitToken(REGEXNL, PopStr());\n BacktrackTerm(); fret; };\n \"\/\" [im]* => { [StrData() appendBytes:\"\/\" length:1];\n _EmitToken(REGEX, PopStr()); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else {\n PushStr(false, kTQStrTypeLeftOrMiddle);\n [StrData() appendBytes:\"\/\" length:1];\n fcall regex;\n }\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"@\" => { EmitToken(ATMARK); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"do\" term? => { EmitToken(DO); ExprBeg(); BacktrackTerm(); };\n \"else\" term => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"else\" => { EmitToken(ELSE); ExprBeg(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n \"#\" '\"' => { PushStr(YES, kTQStrTypeSimple); fcall string; };\n \"#\" \"'\" => { PushStr(NO, kTQStrTypeSimple); fcall string; };\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { PushStr(YES, kTQStrTypeLeftOrMiddle); fcall string; };\n \"'\" => { PushStr(NO, kTQStrTypeLeftOrMiddle); fcall string; };\n rGuillemet => {\n BOOL dbl = IsDblQuot();\n PopStr();\n PushStr(dbl, kTQStrTypeRight);\n fcall string;\n };\n\n \".\" => { EmitToken(PERIOD); };\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableArray *strings = [NSMutableArray array];\n\n unsigned char *temp1, *temp2;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new], nil\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n _EmitToken(0, @\"EOF\");\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = parserState.syntaxError;\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","old_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\nenum {\n kTQStrTypeSimple,\n kTQStrTypeLeftOrMiddle,\n kTQStrTypeRight\n};\n#define PushStr(dblQuot, type) \\\n [strings addObject:[NSDictionary dictionaryWithObjectsAndKeys: \\\n [NSNumber numberWithBool:dblQuot], @\"dblQuot\", \\\n [NSNumber numberWithInt:type], @\"type\", \\\n [NSMutableData data], @\"value\", nil]];\n#define PopStr() ({ id last = [Str() retain]; [strings removeLastObject]; [last autorelease]; })\n#define StrData() [[strings lastObject] objectForKey:@\"value\"]\n#define Str() [[[NSMutableString alloc] initWithData:StrData() encoding:NSUTF8StringEncoding] autorelease]\n#define IsDblQuot() [[[strings lastObject] objectForKey:@\"dblQuot\"] boolValue]\n#define IsRstr() ([[[strings lastObject] objectForKey:@\"type\"] intValue] == kTQStrTypeRight)\n#define IsSimpleStr() ([[[strings lastObject] objectForKey:@\"type\"] intValue] == kTQStrTypeSimple)\n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n NSError *syntaxError;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n int tokenId_ = tokenId; \\\n id val_ = val; \\\n \/*NSLog(@\"emitting %d = '%@' on line: %d\", tokenId, val_, parserState.currentLine); *\/\\\n Parse(parser, tokenId_, [TQToken withId:tokenId value:val_ line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken(tokenId, [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n else if(strncmp(\"else\", (const char*)p-3, 4) == 0) \\\n p -= 4; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) NSUInteger id, lineNumber;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.lineNumber = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n lGuillemet = 0xC2 0xAB; # \u00ab\n rGuillemet = 0xC2 0xBB; # \u00bb\n specialChar = 0xC2 | '\"' | \"'\" | '.' | ',' | ';' | ':' | '|' | '#' | '@' | '~' | '`' | '{' | '}' | '[' | ']' | '(' | ')' | '+' | '-' | '*' | '\/' | '%' | '=' | '<' | '>' | '^' | '\\\\' | '\\r' | '\\n' | space;\n\n char = (any - specialChar) | (0xC2 ^(0xAB|0xBB));\n constant = '_'* uupper char*;\n identifier = (char -- (uupper|udigit)) char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\"|\"else\");\n\n constStr = \"#\" (char | [:@#~+\\-*\/%=<>^])+;\n selector = char* \":\";\n\n regexCont = (ualnum | ascii) - '\/' - '\\\\';\n\nstring := |*\n '\\n' => { [StrData() appendBytes:\"\\n\" length:1]; IncrementLine(); };\n '\\\\n' => { [StrData() appendBytes:\"\\n\" length:1]; };\n '\\\\t' => { [StrData() appendBytes:\"\\t\" length:1]; };\n '\\\\r' => { [StrData() appendBytes:\"\\r\" length:1]; };\n '\\\\\"' => { [StrData() appendBytes:\"\\\"\" length:1]; };\n \"\\\\'\" => { [StrData() appendBytes:\"'\" length:1]; };\n \"\\\\\\\\\" => { [StrData() appendBytes:\"\\\\\" length:1]; };\n \"\\\\\" lGuillemet => { [StrData() appendBytes:\"\u00ab\" length:2]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n NSString *strVal = [NSString stringWithFormat:@\"%c\", (int)code];\n [StrData() appendData:[strVal dataUsingEncoding:NSUTF8StringEncoding]];\n };\n \"\\\\\" any => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n\n lGuillemet => { \n TQAssert(!IsSimpleStr(), @\"Interpolation is not allowed in constant strings\");\n _EmitToken(IsRstr() ? MSTR : LSTR, Str());\n fret;\n };\n '\"' term => {\n if(IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTRNL\n : (IsRstr() ? RSTRNL : STRNL);\n _EmitToken(tokId, PopStr());\n BacktrackTerm();\n fret;\n } else\n [StrData() appendBytes:@\"\\\"\" length:1];\n };\n '\"' => {\n if(IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTR\n : (IsRstr() ? RSTR : STR);\n _EmitToken(tokId, PopStr());\n fret;\n } else\n [StrData() appendBytes:@\"\\\"\" length:1];\n };\n \"'\" term => {\n if(!IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTRNL\n : (IsRstr() ? RSTRNL : STRNL);\n _EmitToken(tokId, PopStr());\n BacktrackTerm();\n fret;\n } else\n [StrData() appendBytes:@\"'\" length:1];\n };\n \"'\" => {\n if(!IsDblQuot()) {\n int tokId = IsSimpleStr() ? CONSTSTR\n : (IsRstr() ? RSTR : STR);\n _EmitToken(tokId, PopStr());\n fret;\n } else\n [StrData() appendBytes:\"'\" length:1];\n };\n\n any => { [StrData() appendBytes:ts length:1]; };\n*|;\n\nregex := |*\n '\\n' => { [StrData() appendBytes:\"\\n\" length:1]; IncrementLine(); };\n \"\\\\\/\" => { [StrData() appendBytes:\"\\\\\/\" length:1]; };\n \"\\\\\" => { [StrData() appendBytes:\"\\\\\" length:1]; };\n regexCont => { [StrData() appendBytes:ts length:1]; };\n \"\/\" [im]* term => { [StrData() appendBytes:\"\/\" length:1];\n _EmitToken(REGEXNL, PopStr());\n BacktrackTerm(); fret; };\n \"\/\" [im]* => { [StrData() appendBytes:\"\/\" length:1];\n _EmitToken(REGEX, PopStr()); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else {\n PushStr(false, kTQStrTypeLeftOrMiddle);\n [StrData() appendBytes:\"\/\" length:1];\n fcall regex;\n }\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"@\" => { EmitToken(ATMARK); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"do\" term? => { EmitToken(DO); ExprBeg(); BacktrackTerm(); };\n \"else\" term => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"else\" => { EmitToken(ELSE); ExprBeg(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n \"#\" '\"' => { PushStr(YES, kTQStrTypeSimple); fcall string; };\n \"#\" \"'\" => { PushStr(NO, kTQStrTypeSimple); fcall string; };\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { PushStr(YES, kTQStrTypeLeftOrMiddle); fcall string; };\n \"'\" => { PushStr(NO, kTQStrTypeLeftOrMiddle); fcall string; };\n rGuillemet => {\n BOOL dbl = IsDblQuot();\n PopStr();\n PushStr(dbl, kTQStrTypeRight);\n fcall string;\n };\n\n \".\" => { EmitToken(PERIOD); };\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableArray *strings = [NSMutableArray array];\n\n unsigned char *temp1, *temp2;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new], nil\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n _EmitToken(0, @\"EOF\");\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = parserState.syntaxError;\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"a1c64c448d032ef8a8d11f28a7797dcd6b7ce1f4","subject":"Make sure to initialize content_length in before every body","message":"Make sure to initialize content_length in before every body","repos":"elabs\/stomp_parser,elabs\/stomp_parser,elabs\/stompede,elabs\/stompede","old_file":"lib\/stompede\/stomp\/parser.rb.rl","new_file":"lib\/stompede\/stomp\/parser.rb.rl","new_contents":"%%{\n machine message;\n\n # data, p, pe, eof, cs, top, stack, ts, te and act\n getkey data.getbyte(p); # code for retrieving current char\n\n ## Action state - needs resetting once consumed!\n action mark {\n buffer = EMPTY_BUFFER.dup\n }\n action buffer {\n buffer << fc\n }\n action mark_key {\n mk = buffer # needs reset\n buffer = nil\n }\n action mark_message {\n message = Stomp::Message.new(nil, nil)\n message_size = 0\n }\n action check_message_size {\n message_size += 1\n raise MessageSizeExceeded if message_size > max_message_size\n }\n\n ## Action commands - should reset used state!\n action write_command {\n message.write_command(buffer)\n buffer = nil\n }\n\n action write_header {\n message.write_header(mk, buffer)\n mk = buffer = nil\n }\n\n action write_body {\n message.write_body(buffer)\n buffer = nil\n }\n\n action finish_headers {\n if message.headers.has_key?(\"content-length\")\n content_length = Integer(message.headers[\"content-length\"])\n else\n content_length = nil\n end\n }\n\n action consume_null {\n buffer.bytesize < content_length if content_length\n }\n\n action consume_octet {\n if content_length\n buffer.bytesize < content_length\n else\n true\n end\n }\n\n action finish_message {\n yield message\n message = nil\n }\n\n ## Stomp message grammar\n\n NULL = \"\\0\";\n EOL = \"\\r\"? . \"\\n\";\n OCTET = any;\n\n client_command = \"CONNECT\" > mark;\n command = client_command $ buffer % write_command . EOL;\n\n HEADER_ESCAPE = \"\\\\\" . (\"\\\\\" | \"n\" | \"r\" | \"c\");\n HEADER_OCTET = HEADER_ESCAPE | (OCTET - \"\\r\" - \"\\n\" - \"\\\\\" - \":\");\n header_key = HEADER_OCTET+ > mark $ buffer % mark_key;\n header_value = HEADER_OCTET* > mark $ buffer;\n header = header_key . \":\" . header_value;\n headers = (header % write_header . EOL)* % finish_headers . EOL;\n\n body = ((NULL when consume_null | ^NULL when consume_octet)* $ buffer) >to(mark) % write_body <: NULL;\n\n message = ((command > mark_message) :> headers :> (body @ finish_message)) $ check_message_size;\n\n stream := (EOL | message)*;\n}%%\n\nmodule Stompede\n module Stomp\n # Provides an API for running parsers.\n #\n # It:\n # - provides a .parse method which remembers state between invocations\n # - buffering of data between chunks\n class Parser\n # this manipulates the singleton class of our context,\n # so we do not want to run this code very often or we\n # bust our ruby method caching\n %% write data noprefix;\n\n class << self\n # @attr [Integer] maximum size (in bytes) a message may become before raising MessageSizeExceeded.\n attr_accessor :max_message_size\n end\n\n EMPTY_BUFFER = \"\".force_encoding(\"BINARY\").freeze\n self.max_message_size = 1024 * 100 # 100KB\n\n # Parse a chunk of Stomp-formatted data into a Message.\n #\n # @param [String] data\n # @param [Parser] state\n # @return [Stomp::Message, nil]\n def self.parse(data, state)\n pe = data.bytesize # end of chunk\n\n p = 0 # pointer to current character\n message = state.message # message currently being parsed, if any\n cs = state.current_state # current state\n mk = state.mark_key # key for header currently being read\n buffer = state.buffer # buffered data for marks\n message_size = state.message_size # how many bytes current message contains in total\n content_length = state.content_length # content length of current message\n\n %% write exec;\n\n if cs == Stomp::Parser.error\n # build error message context\n ctx = 7\n min = [0, p - ctx].max\n cur = p - min\n err = data.byteslice(min, ctx + 1 + ctx)\n chr = err[cur]\n err[cur] = \" -->#{err[cur]}<-- \"\n\n raise ParseError.new(\"unexpected #{chr.inspect} in data (#{err.inspect})\")\n else\n state.message = message\n state.current_state = cs\n state.mark_key = mk\n state.buffer = buffer\n state.message_size = message_size\n state.content_length = content_length\n end\n\n nil\n end\n\n # Construct the parser.\n def initialize\n @error = nil\n @buffer = nil\n @message_size = nil\n @current_state = Stomp::Parser.start\n @message = nil\n @mark_key = nil\n end\n\n # @return [StandardError] error raised during parsing\n attr_accessor :error\n\n # @return [Integer] message size accumulated so far\n attr_accessor :message_size\n\n # @return [String] binary string of current parsing buffer\n attr_accessor :buffer\n\n # @return [Integer, nil]\n attr_accessor :content_length\n\n # @return [Integer] current parsing state\n attr_accessor :current_state\n\n # @return [Stomp::Message] stomp message currently being parsed\n attr_accessor :message\n\n # @return [String] header key currently being parsed\n attr_accessor :mark_key\n\n # Parse a chunk of data. Retains state beteween invocations.\n #\n # @param [String] data\n # @raise [ParseError]\n def parse(data)\n raise error if error\n\n begin\n Parser.parse(data, self) do |message|\n yield message\n end\n rescue => error\n self.error = error\n raise\n end\n end\n end\n end\nend\n","old_contents":"%%{\n machine message;\n\n # data, p, pe, eof, cs, top, stack, ts, te and act\n getkey data.getbyte(p); # code for retrieving current char\n\n ## Action state - needs resetting once consumed!\n action mark {\n buffer = EMPTY_BUFFER.dup\n }\n action buffer {\n buffer << fc\n }\n action mark_key {\n mk = buffer # needs reset\n buffer = nil\n }\n action mark_message {\n message = Stomp::Message.new(nil, nil)\n message_size = 0\n }\n action check_message_size {\n message_size += 1\n raise MessageSizeExceeded if message_size > max_message_size\n }\n\n ## Action commands - should reset used state!\n action write_command {\n message.write_command(buffer)\n buffer = nil\n }\n\n action write_header {\n message.write_header(mk, buffer)\n mk = buffer = nil\n }\n\n action write_body {\n message.write_body(buffer)\n buffer = nil\n }\n\n action finish_headers {\n if message.headers.has_key?(\"content-length\")\n content_length = Integer(message.headers[\"content-length\"])\n end\n }\n\n action consume_null {\n buffer.bytesize < content_length if content_length\n }\n\n action consume_octet {\n if content_length\n buffer.bytesize < content_length\n else\n true\n end\n }\n\n action finish_message {\n yield message\n message = nil\n }\n\n ## Stomp message grammar\n\n NULL = \"\\0\";\n EOL = \"\\r\"? . \"\\n\";\n OCTET = any;\n\n client_command = \"CONNECT\" > mark;\n command = client_command $ buffer % write_command . EOL;\n\n HEADER_ESCAPE = \"\\\\\" . (\"\\\\\" | \"n\" | \"r\" | \"c\");\n HEADER_OCTET = HEADER_ESCAPE | (OCTET - \"\\r\" - \"\\n\" - \"\\\\\" - \":\");\n header_key = HEADER_OCTET+ > mark $ buffer % mark_key;\n header_value = HEADER_OCTET* > mark $ buffer;\n header = header_key . \":\" . header_value;\n headers = (header % write_header . EOL)* % finish_headers . EOL;\n\n body = ((NULL when consume_null | ^NULL when consume_octet)* $ buffer) >to(mark) % write_body <: NULL;\n\n message = ((command > mark_message) :> headers :> (body @ finish_message)) $ check_message_size;\n\n stream := (EOL | message)*;\n}%%\n\nmodule Stompede\n module Stomp\n # Provides an API for running parsers.\n #\n # It:\n # - provides a .parse method which remembers state between invocations\n # - buffering of data between chunks\n class Parser\n # this manipulates the singleton class of our context,\n # so we do not want to run this code very often or we\n # bust our ruby method caching\n %% write data noprefix;\n\n class << self\n # @attr [Integer] maximum size (in bytes) a message may become before raising MessageSizeExceeded.\n attr_accessor :max_message_size\n end\n\n EMPTY_BUFFER = \"\".force_encoding(\"BINARY\").freeze\n self.max_message_size = 1024 * 100 # 100KB\n\n # Parse a chunk of Stomp-formatted data into a Message.\n #\n # @param [String] data\n # @param [Parser] state\n # @return [Stomp::Message, nil]\n def self.parse(data, state)\n pe = data.bytesize # end of chunk\n\n p = 0 # pointer to current character\n message = state.message # message currently being parsed, if any\n cs = state.current_state # current state\n mk = state.mark_key # key for header currently being read\n buffer = state.buffer # buffered data for marks\n message_size = state.message_size # how many bytes current message contains in total\n content_length = state.content_length # content length of current message\n\n %% write exec;\n\n if cs == Stomp::Parser.error\n # build error message context\n ctx = 7\n min = [0, p - ctx].max\n cur = p - min\n err = data.byteslice(min, ctx + 1 + ctx)\n chr = err[cur]\n err[cur] = \" -->#{err[cur]}<-- \"\n\n raise ParseError.new(\"unexpected #{chr.inspect} in data (#{err.inspect})\")\n else\n state.message = message\n state.current_state = cs\n state.mark_key = mk\n state.buffer = buffer\n state.message_size = message_size\n state.content_length = content_length\n end\n\n nil\n end\n\n # Construct the parser.\n def initialize\n @error = nil\n @buffer = nil\n @message_size = nil\n @current_state = Stomp::Parser.start\n @message = nil\n @mark_key = nil\n end\n\n # @return [StandardError] error raised during parsing\n attr_accessor :error\n\n # @return [Integer] message size accumulated so far\n attr_accessor :message_size\n\n # @return [String] binary string of current parsing buffer\n attr_accessor :buffer\n\n # @return [Integer, nil]\n attr_accessor :content_length\n\n # @return [Integer] current parsing state\n attr_accessor :current_state\n\n # @return [Stomp::Message] stomp message currently being parsed\n attr_accessor :message\n\n # @return [String] header key currently being parsed\n attr_accessor :mark_key\n\n # Parse a chunk of data. Retains state beteween invocations.\n #\n # @param [String] data\n # @raise [ParseError]\n def parse(data)\n raise error if error\n\n begin\n Parser.parse(data, self) do |message|\n yield message\n end\n rescue => error\n self.error = error\n raise\n end\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"a499a5e792d37a0ac151bba02e00bb5dbf6d2dc2","subject":"* remove old code","message":"* remove old code\n","repos":"nineties\/amber","old_file":"rlc1\/regalloc.rl","new_file":"rlc1\/regalloc.rl","new_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: regalloc.rl 2010-04-02 21:57:54 nineties $\n %);\n\n(% Register allocation %);\n\ninclude(stddef, code);\nexport(regalloc);\n\nconflicts: NULL;\nequivregs: NULL;\ninput_count: NULL;\noutput_count: NULL;\n\n(% p0: register, p1: is output %);\ncompute_score: (p0) {\n allocate(1);\n x0 = num_conflicts(p0) * 5;\n x0 = x0 + equivreg_score(p0) * 3;\n x0 = x0 + vec_at(input_count, p0[1]);\n x0 = x0 + vec_at(output_count, p0[1]) * 2;\n return x0;\n};\n\n(% p0: set of location-ids, p1: location %);\nadd_conflicts: (p0, p1) {\n allocate(3);\n if (p1 == NULL) { return; };\n if (is_constant_operand(p1)) { return; };\n x0 = p1[1];\n while (p0 != NULL) {\n x1 = ls_value(p0);\n if (x0 != x1) {\n puts(\"conflict: \");\n emit_opd(stdout, get_reg(x0), 32);\n puts(\" <-> \");\n emit_opd(stdout, get_reg(x1), 32);\n putc('\\n');\n x2 = iset_add(vec_at(conflicts, x0), x1);\n vec_put(conflicts, x0, x2);\n x2 = iset_add(vec_at(conflicts, x1), x0);\n vec_put(conflicts, x1, x2);\n };\n p0 = ls_next(p0);\n };\n};\n\nnum_conflicts: (p0) {\n allocate(1);\n x0 = p0[1]; (% index %);\n return iset_size(vec_at(conflicts, x0));\n};\n\n(% p1: registers assigned to p0 %);\nupdate_tables: (p0, p1) {\n allocate(3);\n x0 = p1;\n (% registers conflicting with p1 now be conflict with registers in p1 %);\n while (x0 != NULL) {\n x1 = vec_at(conflicts, p0[1]);\n add_conflicts(x1, ls_value(x0));\n x0 = ls_next(x0);\n };\n (% remove entries of p0 %);\n x0 = 0;\n x1 = num_locations();\n while (x0 < x1) {\n x2 = vec_at(conflicts, x0);\n x2 = iset_del(x2, p0[1]);\n vec_put(conflicts, x0, x2);\n\n x2 = vec_at(equivregs, x0);\n x2 = iset_del(x2, p0[1]);\n vec_put(equivregs, x0, x2);\n\n x0 = x0 + 1;\n };\n};\n\nequivreg_score: (p0) {\n allocate(3);\n x0 = p0[1]; (% index %);\n x1 = vec_at(equivregs, x0);\n x2 = 0;\n while (x1 != NULL) {\n if (p0[0] == OPD_PSEUDO) {\n x2 = x2 + 2;\n goto &next;\n };\n if (p0[0] == OPD_REGISTER) {\n x2 = x2 + 1;\n goto &next;\n };\n if (p0[0] == OPD_STACK) {\n x2 = x2 + 4;\n goto &next;\n };\n if (p0[0] == OPD_ARG) {\n x2 = x2 + 4;\n goto &next;\n };\n label next;\n x1 = ls_next(x1);\n };\n return x2;\n};\n\nadd_equivregs: (p0, p1) {\n allocate(1);\n if (is_constant_operand(p0)) { return; };\n if (is_constant_operand(p1)) { return; };\n x0 = vec_at(equivregs, p0[1]);\n x0 = iset_add(x0, p1[1]);\n vec_put(equivregs, p0[1], x0);\n};\n\nincr_output_count: (p0) {\n allocate(1);\n if (p0 == NULL) { return; };\n if (is_constant_operand(p0)) { return; };\n x0 = vec_at(output_count, p0[1]);\n vec_size(output_count, p0[1], x0 + 1);\n return;\n};\n\nincr_input_count: (p0) {\n allocate(1);\n if (p0 == NULL) { return; };\n if (is_constant_operand(p0)) { return; };\n x0 = vec_at(input_count, p0[1]);\n vec_size(input_count, p0[1], x0 + 1);\n return;\n};\n\n(% p0: instructions %);\ncompute_conflicts: (p0) {\n allocate(3);\n conflicts = mkvec(num_locations());\n equivregs = mkvec(num_locations());\n input_count = mkvec(num_locations());\n output_count = mkvec(num_locations());\n while (p0 != NULL) {\n x0 = ls_value(p0); (% instruction %);\n x1 = x0[INST_LIVE]; (% live locations %);\n\n add_conflicts(x1, x0[INST_OPERAND2]);\n add_conflicts(x1, x0[INST_OPERAND1]);\n\n (% live registers in x1 conflict each other %);\n x2 = x1;\n while (x2 != NULL) {\n add_conflicts(x1, get_reg(ls_value(x2)));\n x2 = ls_next(x2);\n };\n\n if (x0[INST_OPCODE] == INST_MOVL) {\n add_equivregs(x0[INST_OPERAND1], x0[INST_OPERAND2]);\n add_equivregs(x0[INST_OPERAND2], x0[INST_OPERAND1]);\n };\n incr_output_count(x0[INST_OPERAND1]);\n incr_input_count(x0[INST_OPERAND2]);\n p0 = ls_next(p0);\n };\n};\n\n(% pickup pseudo register which have maximal conflicts %);\npickup_pseudo_reg: () {\n allocate(4);\n x0 = NULL;\n x1 = num_pseudo();\n x2 = 0;\n while (x2 < x1) {\n x3 = get_pseudo(x2);\n if (x3 != NULL) {\n if (x0 == NULL) {\n x0 = x3;\n } else {\n if (compute_score(x0) < compute_score(x3)) {\n x0 = x3;\n };\n };\n };\n x2 = x2 + 1;\n };\n assert(x0 != NULL);\n return x0;\n};\n\nmove_cost: (p0) {\n if (p0[0] == OPD_PSEUDO) { return 2; };\n if (p0[0] == OPD_REGISTER) { return 1; };\n if (p0[0] == OPD_STACK) { return 3; };\n if (p0[0] == OPD_ARG) { return 3; };\n if (p0[0] == OPD_AT) { return 3; };\n fputs(stderr, \"ERROR: not reachable here\\n\");\n exit(1);\n};\n\nis_memory_access: (p0) {\n if (p0[0] == OPD_STACK) { return TRUE; };\n if (p0[0] == OPD_ARG) { return TRUE; };\n return FALSE;\n};\n\nselect_best_equivreg: (p0) {\n allocate(6);\n x0 = vec_at(conflicts, p0[1]);\n x1 = vec_at(equivregs, p0[1]);\n x2 = NULL; (% location with maximum cost %);\n x3 = NULL; (% register with maximum cost %);\n x5 = FALSE; (% TRUE if it must be a register %);\n while (x1 != NULL) {\n if (iset_contains(x0, ls_value(x1)) == FALSE) {\n if (ls_value(x1) != p0[1]) {\n x4 = get_reg(ls_value(x1));\n if (x3 == NULL) {\n if (x4[0] == OPD_REGISTER) {\n x3 = x4;\n };\n };\n if (x2 == NULL) {\n x2 = x4;\n } else {\n if (is_memory_access(x2)) {\n if (is_memory_access(x4)) {\n x5 = TRUE;\n goto &skip;\n };\n };\n if (move_cost(x2) < move_cost(x4)) {\n x2 = x4;\n };\n };\n };\n };\n label skip;\n x1 = ls_next(x1);\n };\n if (x5) { return x3; };\n if (p0[PSEUDO_TYPE] == LOCATION_REGISTER) { return x3; };\n return x2;\n};\n\nselect_location: (p0) {\n allocate(4);\n if (p0[PSEUDO_TYPE] == LOCATION_MEMORY) {\n\tgoto &alloc_stackmem;\n };\n\n x0 = vec_at(conflicts, p0[1]);\n\n (% try to allocate register from equivregs %);\n x1 = select_best_equivreg(p0);\n if (x1 != NULL) { return ls_singleton(x1); };\n\n (% try to allocation register %);\n x1 = 0;\n while (x1 < num_normal_regs()) {\n if (iset_contains(x0, x1) == FALSE) {\n if (p0[1] != x1) {\n return ls_singleton(get_reg(x1));\n };\n };\n x1 = x1 + 1;\n };\n\n if (p0[PSEUDO_TYPE] == LOCATION_REGISTER) {\n fputs(stderr, \"ERROR: failed to allocate register\\n\");\n exit(1);\n };\n\n label alloc_stackmem;\n\n if (p0[PSEUDO_LENGTH] == 1) {\n (% try to reuse stack memory %);\n x1 = 0;\n while (x1 < num_stack()) {\n x2 = get_stack(x1);\n if (iset_contains(x0, x2[1]) == FALSE) {\n return ls_singleton(x2);\n };\n x1 = x1 + 1;\n };\n\n (% allocate new stack memory %);\n (% here, we must resize working tables. %);\n vec_pushback(conflicts, NULL);\n vec_pushback(equivregs, NULL);\n vec_pushback(input_count, NULL);\n vec_pushback(output_count, NULL);\n return ls_singleton(get_stack(x1));\n } else {\n (% returns continuous memories %);\n x0 = p0[PSEUDO_LENGTH];\n x1 = get_stack_array(num_stack(), x0);\n vec_resize(conflicts, vec_size(conflicts) + x0);\n vec_resize(equivregs, vec_size(equivregs) + x0);\n vec_resize(input_count, vec_size(input_count) + x0);\n vec_resize(output_count, vec_size(output_count) + x0);\n return x1;\n };\n};\n\nassign_location: (p0) {\n allocate(2);\n x0 = select_location(p0);\n (% update register table %);\n puts(\">> assign: \");\n emit_opd(stdout, p0, 32);\n puts(\" <-\");\n x1 = x0;\n while (x1 != NULL) {\n putc(' ');\n emit_opd(stdout, ls_value(x1), 32);\n x1 = ls_next(x1);\n };\n putc('\\n');\n\n assign_pseudo(p0, x0);\n (% update conflicts\/equivregs %);\n update_tables(p0, x0);\n\n (% update output_count\/input_count %);\n while (x0 != NULL) {\n vec_put(output_count, (ls_value(x0))[1],\n vec_at(output_count, p0[1]) + vec_at(output_count, (ls_value(x0))[1]));\n vec_put(input_count, (ls_value(x0))[1],\n vec_at(input_count, p0[1]) + vec_at(input_count, (ls_value(x0))[1]));\n x0 = ls_next(x0);\n };\n};\n\nassign_locations: () {\n allocate(2);\n x0 = 0;\n x1 = num_pseudo();\n while (x0 < x1) {\n assign_location(pickup_pseudo_reg());\n\tx0 = x0 + 1;\n };\n};\n\n(% replace pseudo-reg to physical register or stack memory %);\nreplace: (p0) {\n allocate(2);\n if (p0 == NULL) { return NULL; };\n if (p0[0] == OPD_PSEUDO) {\n return replace(ls_value(p0[PSEUDO_LOCATION]));\n };\n if (p0[0] == OPD_AT) {\n x0 = p0[2];\n x1 = p0[3]; (% index %);\n if (x0[0] == OPD_STACK) {\n return get_stack(x0[STACK_OFFSET] + x1);\n };\n if (x0[0] == OPD_PSEUDO) {\n return replace(ls_at(x0[PSEUDO_LOCATION], x1));\n };\n fputs(stderr, \"ERROR: not reachable here\\n\");\n exit(1);\n };\n return p0;\n};\n\nupdate_instructions: (p0) {\n allocate(2);\n if (p0 == NULL) { return NULL; };\n x0 = ls_value(p0);\n x0[INST_OPERAND1] = replace(x0[INST_OPERAND1]);\n x0[INST_OPERAND2] = replace(x0[INST_OPERAND2]);\n\n (% eliminate meaningless move %);\n if (x0[INST_OPCODE] == INST_MOVL) {\n if (x0[INST_OPERAND1] == x0[INST_OPERAND2]) {\n return update_instructions(ls_next(p0));\n };\n };\n\n x1 = ls_cons(x0, update_instructions(ls_next(p0)));\n\n (% insert leave instruction %);\n if (x0[INST_OPCODE] == INST_RET) {\n x1 = ls_cons(mkinst(INST_LEAVE, NULL, NULL), x1);\n };\n return x1;\n};\n\nallocate_stack_frame: (p0) {\n allocate(1);\n x0 = p0;\n if (num_stack() > 0) {\n x0 = ls_cons(mkinst(INST_SUBL, mktup2(OPD_INTEGER, 4*num_stack()), get_esp()), x0);\n };\n return\n ls_cons(mkinst(INST_PUSHL, get_ebp(), NULL),\n ls_cons(mkinst(INST_MOVL, get_esp(), get_ebp()),\n x0));\n};\n\n(% p0: TCODE_FUNC object %);\nregalloc: (p0) {\n allocate(1);\n\n (% liveness analysis %);\n liveness(p0);\n\n x0 = p0[3]; (% instructions %);\n if (num_pseudo() > 0) {\n compute_conflicts(x0);\n assign_locations();\n };\n x0 = update_instructions(x0);\n x0 = allocate_stack_frame(x0);\n p0[3] = x0;\n};\n","old_contents":"(%\n % rowl - generation 1\n % Copyright (C) 2010 nineties\n %\n % $Id: regalloc.rl 2010-04-02 16:40:39 nineties $\n %);\n\n(% Register allocation %);\n\ninclude(stddef, code);\nexport(regalloc);\n\nconflicts: NULL;\nequivregs: NULL;\ninput_count: NULL;\noutput_count: NULL;\n\n(% p0: register, p1: is output %);\ncompute_score: (p0) {\n allocate(1);\n x0 = num_conflicts(p0) * 5;\n x0 = x0 + equivreg_score(p0) * 3;\n x0 = x0 + vec_at(input_count, p0[1]);\n x0 = x0 + vec_at(output_count, p0[1]) * 2;\n return x0;\n};\n\n(% p0: set of location-ids, p1: location %);\nadd_conflicts: (p0, p1) {\n allocate(3);\n if (p1 == NULL) { return; };\n if (is_constant_operand(p1)) { return; };\n x0 = p1[1];\n while (p0 != NULL) {\n x1 = ls_value(p0);\n if (x0 != x1) {\n puts(\"conflict: \");\n emit_opd(stdout, get_reg(x0), 32);\n puts(\" <-> \");\n emit_opd(stdout, get_reg(x1), 32);\n putc('\\n');\n x2 = iset_add(vec_at(conflicts, x0), x1);\n vec_put(conflicts, x0, x2);\n x2 = iset_add(vec_at(conflicts, x1), x0);\n vec_put(conflicts, x1, x2);\n };\n p0 = ls_next(p0);\n };\n};\n\nnum_conflicts: (p0) {\n allocate(1);\n x0 = p0[1]; (% index %);\n return iset_size(vec_at(conflicts, x0));\n};\n\n(% p1: registers assigned to p0 %);\nupdate_tables: (p0, p1) {\n allocate(3);\n x0 = p1;\n (% registers conflicting with p1 now be conflict with registers in p1 %);\n while (x0 != NULL) {\n x1 = vec_at(conflicts, p0[1]);\n add_conflicts(x1, ls_value(x0));\n x0 = ls_next(x0);\n };\n (% remove entries of p0 %);\n x0 = 0;\n x1 = num_locations();\n while (x0 < x1) {\n x2 = vec_at(conflicts, x0);\n x2 = iset_del(x2, p0[1]);\n vec_put(conflicts, x0, x2);\n\n x2 = vec_at(equivregs, x0);\n x2 = iset_del(x2, p0[1]);\n vec_put(equivregs, x0, x2);\n\n x0 = x0 + 1;\n };\n};\n\nequivreg_score: (p0) {\n allocate(3);\n x0 = p0[1]; (% index %);\n x1 = vec_at(equivregs, x0);\n x2 = 0;\n while (x1 != NULL) {\n if (p0[0] == OPD_PSEUDO) {\n x2 = x2 + 2;\n goto &next;\n };\n if (p0[0] == OPD_REGISTER) {\n x2 = x2 + 1;\n goto &next;\n };\n if (p0[0] == OPD_STACK) {\n x2 = x2 + 4;\n goto &next;\n };\n if (p0[0] == OPD_ARG) {\n x2 = x2 + 4;\n goto &next;\n };\n label next;\n x1 = ls_next(x1);\n };\n return x2;\n};\n\nadd_equivregs: (p0, p1) {\n allocate(1);\n if (is_constant_operand(p0)) { return; };\n if (is_constant_operand(p1)) { return; };\n x0 = vec_at(equivregs, p0[1]);\n x0 = iset_add(x0, p1[1]);\n vec_put(equivregs, p0[1], x0);\n};\n\nincr_output_count: (p0) {\n allocate(1);\n if (p0 == NULL) { return; };\n if (is_constant_operand(p0)) { return; };\n x0 = vec_at(output_count, p0[1]);\n vec_size(output_count, p0[1], x0 + 1);\n return;\n};\n\nincr_input_count: (p0) {\n allocate(1);\n if (p0 == NULL) { return; };\n if (is_constant_operand(p0)) { return; };\n x0 = vec_at(input_count, p0[1]);\n vec_size(input_count, p0[1], x0 + 1);\n return;\n};\n\n(% p0: instructions %);\ncompute_conflicts: (p0) {\n allocate(3);\n conflicts = mkvec(num_locations());\n equivregs = mkvec(num_locations());\n input_count = mkvec(num_locations());\n output_count = mkvec(num_locations());\n while (p0 != NULL) {\n x0 = ls_value(p0); (% instruction %);\n x1 = x0[INST_LIVE]; (% live locations %);\n\n add_conflicts(x1, x0[INST_OPERAND2]);\n add_conflicts(x1, x0[INST_OPERAND1]);\n\n (% live registers in x1 conflict each other %);\n x2 = x1;\n while (x2 != NULL) {\n add_conflicts(x1, get_reg(ls_value(x2)));\n x2 = ls_next(x2);\n };\n\n if (x0[INST_OPCODE] == INST_MOVL) {\n add_equivregs(x0[INST_OPERAND1], x0[INST_OPERAND2]);\n add_equivregs(x0[INST_OPERAND2], x0[INST_OPERAND1]);\n };\n incr_output_count(x0[INST_OPERAND1]);\n incr_input_count(x0[INST_OPERAND2]);\n p0 = ls_next(p0);\n };\n};\n\n(% pickup pseudo register which have maximal conflicts %);\npickup_pseudo_reg: () {\n allocate(4);\n x0 = NULL;\n x1 = num_pseudo();\n x2 = 0;\n while (x2 < x1) {\n x3 = get_pseudo(x2);\n if (x3 != NULL) {\n if (x0 == NULL) {\n x0 = x3;\n } else {\n if (compute_score(x0) < compute_score(x3)) {\n x0 = x3;\n };\n };\n };\n x2 = x2 + 1;\n };\n assert(x0 != NULL);\n return x0;\n};\n\nmove_cost: (p0) {\n if (p0[0] == OPD_PSEUDO) { return 2; };\n if (p0[0] == OPD_REGISTER) { return 1; };\n if (p0[0] == OPD_STACK) { return 3; };\n if (p0[0] == OPD_ARG) { return 3; };\n if (p0[0] == OPD_AT) { return 3; };\n fputs(stderr, \"ERROR: not reachable here\\n\");\n exit(1);\n};\n\nis_memory_access: (p0) {\n if (p0[0] == OPD_STACK) { return TRUE; };\n if (p0[0] == OPD_ARG) { return TRUE; };\n return FALSE;\n};\n\nselect_best_equivreg: (p0) {\n allocate(6);\n x0 = vec_at(conflicts, p0[1]);\n x1 = vec_at(equivregs, p0[1]);\n x2 = NULL; (% location with maximum cost %);\n x3 = NULL; (% register with maximum cost %);\n x5 = FALSE; (% TRUE if it must be a register %);\n while (x1 != NULL) {\n if (iset_contains(x0, ls_value(x1)) == FALSE) {\n if (ls_value(x1) != p0[1]) {\n x4 = get_reg(ls_value(x1));\n if (x3 == NULL) {\n if (x4[0] == OPD_REGISTER) {\n x3 = x4;\n };\n };\n if (x2 == NULL) {\n x2 = x4;\n } else {\n if (is_memory_access(x2)) {\n if (is_memory_access(x4)) {\n x5 = TRUE;\n goto &skip;\n };\n };\n if (move_cost(x2) < move_cost(x4)) {\n x2 = x4;\n };\n };\n };\n };\n label skip;\n x1 = ls_next(x1);\n };\n if (x5) { return x3; };\n if (p0[PSEUDO_TYPE] == LOCATION_REGISTER) { return x3; };\n return x2;\n};\n\nselect_location: (p0) {\n allocate(4);\n if (p0[PSEUDO_TYPE] == LOCATION_MEMORY) {\n\tgoto &alloc_stackmem;\n };\n\n x0 = vec_at(conflicts, p0[1]);\n\n (% try to allocate register from equivregs %);\n x1 = select_best_equivreg(p0);\n if (x1 != NULL) { return ls_singleton(x1); };\n\n (% try to allocation register %);\n x1 = 0;\n while (x1 < num_normal_regs()) {\n if (iset_contains(x0, x1) == FALSE) {\n if (p0[1] != x1) {\n return ls_singleton(get_reg(x1));\n };\n };\n x1 = x1 + 1;\n };\n\n if (p0[PSEUDO_TYPE] == LOCATION_REGISTER) {\n fputs(stderr, \"ERROR: failed to allocate register\\n\");\n exit(1);\n };\n\n label alloc_stackmem;\n\n if (p0[PSEUDO_LENGTH] == 1) {\n (% try to reuse stack memory %);\n x1 = 0;\n while (x1 < num_stack()) {\n x2 = get_stack(x1);\n if (iset_contains(x0, x2[1]) == FALSE) {\n return ls_singleton(x2);\n };\n x1 = x1 + 1;\n };\n\n (% allocate new stack memory %);\n (% here, we must resize working tables. %);\n vec_pushback(conflicts, NULL);\n vec_pushback(equivregs, NULL);\n vec_pushback(input_count, NULL);\n vec_pushback(output_count, NULL);\n return ls_singleton(get_stack(x1));\n } else {\n (% returns continuous memories %);\n x0 = p0[PSEUDO_LENGTH];\n x1 = get_stack_array(num_stack(), x0);\n vec_resize(conflicts, vec_size(conflicts) + x0);\n vec_resize(equivregs, vec_size(equivregs) + x0);\n vec_resize(input_count, vec_size(input_count) + x0);\n vec_resize(output_count, vec_size(output_count) + x0);\n return x1;\n };\n};\n\nassign_location: (p0) {\n allocate(5);\n x0 = select_location(p0);\n (% update register table %);\n puts(\">> assign: \");\n emit_opd(stdout, p0, 32);\n puts(\" <-\");\n x1 = x0;\n while (x1 != NULL) {\n putc(' ');\n emit_opd(stdout, ls_value(x1), 32);\n x1 = ls_next(x1);\n };\n putc('\\n');\n\n assign_pseudo(p0, x0);\n (% update conflicts\/equivregs %);\n update_tables(p0, x0);\n (%\n x1 = 0;\n x2 = num_locations();\n while (x1 < x2) {\n x4 = x0;\n while (x4 != NULL) {\n x3 = vec_at(conflicts, x1);\n if (iset_contains(x3, p0[1])) {\n x3 = iset_del(x3, p0[1]);\n x3 = iset_add(x3, (ls_value(x4))[1]);\n vec_put(conflicts, x1, x3);\n\n puts(\"update conflict: \");\n emit_opd(stdout, ls_value(x4), 32);\n puts(\" <-> \");\n emit_opd(stdout, get_reg(x1), 32);\n putc('\\n');\n };\n\n x3 = vec_at(equivregs, x1);\n if (iset_contains(x3, p0[1])) {\n x3 = iset_del(x3, p0[1]);\n x3 = iset_add(x3, (ls_value(x4))[1]);\n vec_put(equivregs, x1, x3);\n };\n x4 = ls_next(x4);\n };\n\n x1 = x1 + 1;\n };\n %);\n\n (% update output_count\/input_count %);\n while (x0 != NULL) {\n vec_put(output_count, (ls_value(x0))[1],\n vec_at(output_count, p0[1]) + vec_at(output_count, (ls_value(x0))[1]));\n vec_put(input_count, (ls_value(x0))[1],\n vec_at(input_count, p0[1]) + vec_at(input_count, (ls_value(x0))[1]));\n x0 = ls_next(x0);\n };\n};\n\nassign_locations: () {\n allocate(2);\n x0 = 0;\n x1 = num_pseudo();\n while (x0 < x1) {\n assign_location(pickup_pseudo_reg());\n\tx0 = x0 + 1;\n };\n};\n\n(% replace pseudo-reg to physical register or stack memory %);\nreplace: (p0) {\n allocate(2);\n if (p0 == NULL) { return NULL; };\n if (p0[0] == OPD_PSEUDO) {\n return replace(ls_value(p0[PSEUDO_LOCATION]));\n };\n if (p0[0] == OPD_AT) {\n x0 = p0[2];\n x1 = p0[3]; (% index %);\n if (x0[0] == OPD_STACK) {\n return get_stack(x0[STACK_OFFSET] + x1);\n };\n if (x0[0] == OPD_PSEUDO) {\n return replace(ls_at(x0[PSEUDO_LOCATION], x1));\n };\n fputs(stderr, \"ERROR: not reachable here\\n\");\n exit(1);\n };\n return p0;\n};\n\nupdate_instructions: (p0) {\n allocate(2);\n if (p0 == NULL) { return NULL; };\n x0 = ls_value(p0);\n x0[INST_OPERAND1] = replace(x0[INST_OPERAND1]);\n x0[INST_OPERAND2] = replace(x0[INST_OPERAND2]);\n\n (% eliminate meaningless move %);\n if (x0[INST_OPCODE] == INST_MOVL) {\n if (x0[INST_OPERAND1] == x0[INST_OPERAND2]) {\n return update_instructions(ls_next(p0));\n };\n };\n\n x1 = ls_cons(x0, update_instructions(ls_next(p0)));\n\n (% insert leave instruction %);\n if (x0[INST_OPCODE] == INST_RET) {\n x1 = ls_cons(mkinst(INST_LEAVE, NULL, NULL), x1);\n };\n return x1;\n};\n\nallocate_stack_frame: (p0) {\n allocate(1);\n x0 = p0;\n if (num_stack() > 0) {\n x0 = ls_cons(mkinst(INST_SUBL, mktup2(OPD_INTEGER, 4*num_stack()), get_esp()), x0);\n };\n return\n ls_cons(mkinst(INST_PUSHL, get_ebp(), NULL),\n ls_cons(mkinst(INST_MOVL, get_esp(), get_ebp()),\n x0));\n};\n\n(% p0: TCODE_FUNC object %);\nregalloc: (p0) {\n allocate(1);\n\n (% liveness analysis %);\n liveness(p0);\n\n x0 = p0[3]; (% instructions %);\n if (num_pseudo() > 0) {\n compute_conflicts(x0);\n assign_locations();\n };\n x0 = update_instructions(x0);\n x0 = allocate_stack_frame(x0);\n p0[3] = x0;\n};\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"28754c7d5e6eb196250b8927d82e604276720d8e","subject":"Treat unexpected state as such","message":"Treat unexpected state as such\n\n\u2013 Currently, the parser should not end up with \u201cboth gaps\u201d input when handling match.\n","repos":"tsnorri\/vcf2multialign,tsnorri\/vcf2multialign,tsnorri\/vcf2multialign,tsnorri\/vcf2multialign","old_file":"combine-msa-vcf\/msa_combiner_parse_msa.rl","new_file":"combine-msa-vcf\/msa_combiner_parse_msa.rl","new_contents":"\/*\n * Copyright (c) 2019 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#include \n#include \"msa_combiner.hh\"\n\n\n%% machine alignment_parser;\n%% write data;\n\n\nnamespace vcf2multialign {\n\t\n\tvoid msa_combiner::prepare_msa_parser()\n\t{\n\t\t%% write init;\n\t}\n\t\n\t\n\tvoid msa_combiner::parse_msa(aligned_character_pack const &pack)\n\t{\n\t\t%%{\n\t\t\tvariable cs\t\tm_fsm.cs;\n\t\t\tvariable p\t\tm_fsm.p;\n\t\t\tvariable pe\t\tm_fsm.pe;\n\t\t\tvariable eof\tm_fsm.pe;\n\t\t\t\n\t\t\tnt\t\t\t= [ACGTN];\t# Add [acgtn] to allow lowecase.\n\t\t\tntg\t\t\t= nt | '-';\n\t\t\t\n\t\t\ta_\t\t\t= [A];\t\t# Add [a] etc. to allow lowercase.\n\t\t\tc_\t\t\t= [C];\n\t\t\tg_\t\t\t= [G];\n\t\t\tt_\t\t\t= [T];\n\t\t\tn_\t\t\t= [N];\n\t\t\tnot_a\t\t= nt - a_;\n\t\t\tnot_c\t\t= nt - c_;\n\t\t\tnot_g\t\t= nt - g_;\n\t\t\tnot_t\t\t= nt - t_;\n\t\t\tnot_n\t\t= nt - n_;\n\t\t\t\n\t\t\tsame\t\t= \/AA\/ | \/CC\/ | \/GG\/ | \/TT\/ | \/NN\/;\t# Add \/i to allow lowercase.\n\t\t\tdiff\t\t= (a_ . not_a) | (c_ . not_c) | (g_ . not_g) | (t_ . not_t) | (n_ . not_n);\n\t\t\tboth_nt\t\t= nt{2};\t\t\t\t# Any two non-gap.\n\t\t\t\n\t\t\taction deletion_continue_r {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_deletion;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_deletion_r {\n\t\t\t\tm_current_segment.reset(pack, segment_type::DELETION);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_deletion;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_mismatch_b {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MISMATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_mixed_b {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_mixed_r {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_match_b {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction match_continue_b {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction match_continue_g {\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mismatch_continue_b {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mismatch_continue_g {\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mismatch_mark_mixed_a {\n\t\t\t\tm_current_segment.type = segment_type::MIXED;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mixed_continue_a {\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mixed_continue_g {\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mixed_continue_r {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_del_r {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::DELETION);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_deletion;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_match_b {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_mismatch_b {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MISMATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_mixed_b {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_mixed_r {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction handle_error {\n\t\t\t\tthrow std::runtime_error(\"Unexpected character\");\n\t\t\t}\n\t\t\t\n\t\t\taction handle_unexpected_state {\n\t\t\t\tthrow std::runtime_error(\"Unexpected state\");\n\t\t\t}\n\t\t\t\n\t\t\t# The following machine definitions should handle all combinations of four characters.\n\t\t\t# \u201cSame\u201d or \u201cmatching\u201d segment refers to the property that for every alt non-gap character there is a matching ref character.\n\t\t\t# Otherwise the segment is considered non-matching. In some cases, this property cannot be determined by looking ahead just one character.\n\t\t\t\n\t\t\t# Ref\tX-\tX-\tX-\tX-\n\t\t\t# Alt\tX-\tX+\tY*\t-*\n\t\t\tsame_next_both_g\t\t= (same . '--');\n\t\t\tsame_next_ref_g\t\t\t= (same . '-' . nt);\n\t\t\tdiff_next_ref_g\t\t\t= (diff . '-' . ntg);\n\t\t\talt_g_next_ref_g\t\t= (nt . '--' . ntg);\n\t\t\t\n\t\t\t# Ref\tX+\n\t\t\t# Alt\t-*\n\t\t\talt_g_next_ref_c\t\t= (nt . '-' . nt . ntg);\n\t\t\t\n\t\t\t# Ref\tX+\tX+\n\t\t\t# Alt\tX*\tY*\n\t\t\t# Non-gap alt characters consistently match \/ do not match ref.\n\t\t\tsame_next_ref_nt\t\t= (same . nt . ntg);\n\t\t\tdiff_next_ref_nt\t\t= (diff . nt . ntg);\n\t\t\t\n\t\t\t# Ref\t-\t-\n\t\t\t# Alt\t-\tX\n\t\t\t# ref_g may come after same_next_ref_g, diff_next_ref_g, alt_g_next_ref_g.\n\t\t\tboth_g\t\t\t\t\t= ('--');\n\t\t\tref_g\t\t\t\t\t= ('-' . nt);\n\t\t\t\n\t\t\t# Make a static assertion fail if there are any character combinations that were not listed above.\n\t\t\taction report_unhandled {\n\t\t\t\tstatic_assert(false, \"Found a character combination that was not handled.\");\n\t\t\t}\n\t\t\tunhandled = ((ntg{4}) - (\n\t\t\t\tsame_next_both_g\t\t|\n\t\t\t\tsame_next_ref_g\t\t\t|\n\t\t\t\tdiff_next_ref_g\t\t\t|\n\t\t\t\talt_g_next_ref_g\t\t|\n\t\t\t\t\n\t\t\t\talt_g_next_ref_c\t\t|\n\t\t\t\t\n\t\t\t\tsame_next_ref_nt\t\t|\n\t\t\t\tdiff_next_ref_nt\t\t|\n\t\t\t\t\n\t\t\t\t(both_g . ntg{2})\t\t|\t# Corresponds to both_g in the machines below but would match more without the ntg{2}.\n\t\t\t\t(ref_g . ntg{2})\t\t\t# Corresponds to ref_g in the machines below but would match more without the ntg{2}.\n\t\t\t));\n\t\t\tfail_on_unhandled_combinations := unhandled $(report_unhandled);\n\t\t\n\t\t\t# In the following cases start a new segment at the marked position b.c.\n\t\t\t# the following characters cannot be known and this reduces the number\n\t\t\t# of special cases a bit (1).\n\t\t\t# Ref\tACG-\tACG-\n\t\t\t# Alt\tACG-\tTTG-\n\t\t\t#\t\t ^\t\t ^\n\t\t\t# Action suffixes: _b: both have non-gap, _r: ref has non-gap, _a: alt has non-gap, _g: both have gap.\n\t\t\t\n\t\t\tcommon = (\n\t\t\t\t# Since the next ref character is a gap, a new segment needs to be created since we don\u2019t know the subsequent characters.\n\t\t\t\t(same_next_both_g\t@(start_new_mixed_b))\t\t|\t# We currently don\u2019t change a matching segment to mixed, so mark the segment for post-processing here.\n\t\t\t\t(same_next_ref_g\t@(start_new_mixed_b))\t\t|\n\t\t\t\t(diff_next_ref_g\t@(start_new_mismatch_b))\t|\n\t\t\t\t(alt_g_next_ref_g\t@(start_new_mixed_r))\n\t\t\t);\n\t\t\t\n\t\t\thandle_match := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(start_new_del_r))\t\t\t|\t# Deletion in alt w.r.t. ref.\n\t\t\t\t\n\t\t\t\t(same_next_ref_nt\t@(match_continue_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(start_new_mismatch_b))\t|\n\t\t\t\t\n\t\t\t\t(both_g\t\t\t\t@(handle_unexpected_state))\t|\n\t\t\t\t(ref_g\t\t\t\t@(handle_unexpected_state))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\thandle_mismatch := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(start_new_del_r))\t\t\t|\t# Deletion in alt w.r.t. ref.\n\t\n\t\t\t\t(same_next_ref_nt\t@(start_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(mismatch_continue_b))\t\t|\n\t\n\t\t\t\t(both_g\t\t\t\t@(mismatch_continue_g))\t\t|\n\t\t\t\t(ref_g\t\t\t\t@(mismatch_mark_mixed_a))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\thandle_mixed := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(start_new_del_r))\t\t\t|\t# Deletion in alt w.r.t. ref.\n\n\t\t\t\t(same_next_ref_nt\t@(start_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(start_new_mismatch_b))\t|\n\t\t\t\t\n\t\t\t\t(both_g\t\t\t\t@(mixed_continue_g))\t\t|\n\t\t\t\t(ref_g\t\t\t\t@(mixed_continue_a))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\thandle_deletion := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(deletion_continue_r))\t\t|\n\t\t\t\t\n\t\t\t\t(same_next_ref_nt\t@(start_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(start_new_mismatch_b))\t|\n\t\t\t\t\n\t\t\t\t(both_g\t\t\t\t@(handle_unexpected_state))\t|\n\t\t\t\t(ref_g\t\t\t\t@(handle_unexpected_state))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\t# Starting machines. Ref is guaranteed to be non-gap. See common.\n\t\t\t# Ref\tX-\tX-\tX-\tX-\tX+\tX+\tX+\n\t\t\t# Alt\tX-\tX+\tY*\t-*\t-*\tX*\tY*\n\t\t\t#same_next_both_g\n\t\t\t#same_next_ref_g\n\t\t\t#diff_next_ref_g\n\t\t\t#alt_g_next_ref_g\n\t\t\t#alt_g_next_ref_c\n\t\t\t#same_next_ref_nt\n\t\t\t#diff_next_ref_nt\n\t\t\tmain_unexpected = ntg{4} - (same_next_both_g | same_next_ref_g | diff_next_ref_g | alt_g_next_ref_g | alt_g_next_ref_c | same_next_ref_nt | diff_next_ref_nt);\n\t\t\t\n\t\t\tmain := (\n\t\t\t\t(same_next_both_g\t@(main_new_match_b))\t\t|\n\t\t\t\t(same_next_ref_g\t@(main_new_mixed_b))\t\t|\n\t\t\t\t(diff_next_ref_g\t@(main_new_mismatch_b))\t\t|\n\t\t\t\t(alt_g_next_ref_g\t@(main_new_mixed_r))\t\t|\n\t\t\t\t(alt_g_next_ref_c\t@(main_new_deletion_r))\t\t|\n\t\t\t\t(same_next_ref_nt\t@(main_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(main_new_mismatch_b))\t\t|\n\t\t\t\t(main_unexpected\t@(handle_unexpected_state))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\twrite exec noend;\n\t\t}%%\n\t}\n}\n","old_contents":"\/*\n * Copyright (c) 2019 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#include \n#include \"msa_combiner.hh\"\n\n\n%% machine alignment_parser;\n%% write data;\n\n\nnamespace vcf2multialign {\n\t\n\tvoid msa_combiner::prepare_msa_parser()\n\t{\n\t\t%% write init;\n\t}\n\t\n\t\n\tvoid msa_combiner::parse_msa(aligned_character_pack const &pack)\n\t{\n\t\t%%{\n\t\t\tvariable cs\t\tm_fsm.cs;\n\t\t\tvariable p\t\tm_fsm.p;\n\t\t\tvariable pe\t\tm_fsm.pe;\n\t\t\tvariable eof\tm_fsm.pe;\n\t\t\t\n\t\t\tnt\t\t\t= [ACGTN];\t# Add [acgtn] to allow lowecase.\n\t\t\tntg\t\t\t= nt | '-';\n\t\t\t\n\t\t\ta_\t\t\t= [A];\t\t# Add [a] etc. to allow lowercase.\n\t\t\tc_\t\t\t= [C];\n\t\t\tg_\t\t\t= [G];\n\t\t\tt_\t\t\t= [T];\n\t\t\tn_\t\t\t= [N];\n\t\t\tnot_a\t\t= nt - a_;\n\t\t\tnot_c\t\t= nt - c_;\n\t\t\tnot_g\t\t= nt - g_;\n\t\t\tnot_t\t\t= nt - t_;\n\t\t\tnot_n\t\t= nt - n_;\n\t\t\t\n\t\t\tsame\t\t= \/AA\/ | \/CC\/ | \/GG\/ | \/TT\/ | \/NN\/;\t# Add \/i to allow lowercase.\n\t\t\tdiff\t\t= (a_ . not_a) | (c_ . not_c) | (g_ . not_g) | (t_ . not_t) | (n_ . not_n);\n\t\t\tboth_nt\t\t= nt{2};\t\t\t\t# Any two non-gap.\n\t\t\t\n\t\t\taction deletion_continue_r {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_deletion;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_deletion_r {\n\t\t\t\tm_current_segment.reset(pack, segment_type::DELETION);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_deletion;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_mismatch_b {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MISMATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_mixed_b {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_mixed_r {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction main_new_match_b {\n\t\t\t\tm_current_segment.reset(pack, segment_type::MATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction match_continue_b {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction match_continue_g {\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mismatch_continue_b {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mismatch_continue_g {\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mismatch_mark_mixed_a {\n\t\t\t\tm_current_segment.type = segment_type::MIXED;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mixed_continue_a {\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mixed_continue_g {\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction mixed_continue_r {\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_del_r {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::DELETION);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_deletion;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_match_b {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_match;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_mismatch_b {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MISMATCH);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mismatch;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_mixed_b {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tm_current_segment.alt.string += pack.alt.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction start_new_mixed_r {\n\t\t\t\tpush_current_segment();\n\t\t\t\tm_current_segment.reset(pack, segment_type::MIXED);\n\t\t\t\tm_current_segment.ref.string += pack.ref.character;\n\t\t\t\tfnext handle_mixed;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\t\n\t\t\taction handle_error {\n\t\t\t\tthrow std::runtime_error(\"Unexpected character\");\n\t\t\t}\n\t\t\t\n\t\t\taction handle_unexpected_state {\n\t\t\t\tthrow std::runtime_error(\"Unexpected state\");\n\t\t\t}\n\t\t\t\n\t\t\t# The following machine definitions should handle all combinations of four characters.\n\t\t\t# \u201cSame\u201d or \u201cmatching\u201d segment refers to the property that for every alt non-gap character there is a matching ref character.\n\t\t\t# Otherwise the segment is considered non-matching. In some cases, this property cannot be determined by looking ahead just one character.\n\t\t\t\n\t\t\t# Ref\tX-\tX-\tX-\tX-\n\t\t\t# Alt\tX-\tX+\tY*\t-*\n\t\t\tsame_next_both_g\t\t= (same . '--');\n\t\t\tsame_next_ref_g\t\t\t= (same . '-' . nt);\n\t\t\tdiff_next_ref_g\t\t\t= (diff . '-' . ntg);\n\t\t\talt_g_next_ref_g\t\t= (nt . '--' . ntg);\n\t\t\t\n\t\t\t# Ref\tX+\n\t\t\t# Alt\t-*\n\t\t\talt_g_next_ref_c\t\t= (nt . '-' . nt . ntg);\n\t\t\t\n\t\t\t# Ref\tX+\tX+\n\t\t\t# Alt\tX*\tY*\n\t\t\t# Non-gap alt characters consistently match \/ do not match ref.\n\t\t\tsame_next_ref_nt\t\t= (same . nt . ntg);\n\t\t\tdiff_next_ref_nt\t\t= (diff . nt . ntg);\n\t\t\t\n\t\t\t# Ref\t-\t-\n\t\t\t# Alt\t-\tX\n\t\t\t# ref_g may come after same_next_ref_g, diff_next_ref_g, alt_g_next_ref_g.\n\t\t\tboth_g\t\t\t\t\t= ('--');\n\t\t\tref_g\t\t\t\t\t= ('-' . nt);\n\t\t\t\n\t\t\t# Make a static assertion fail if there are any character combinations that were not listed above.\n\t\t\taction report_unhandled {\n\t\t\t\tstatic_assert(false, \"Found a character combination that was not handled.\");\n\t\t\t}\n\t\t\tunhandled = ((ntg{4}) - (\n\t\t\t\tsame_next_both_g\t\t|\n\t\t\t\tsame_next_ref_g\t\t\t|\n\t\t\t\tdiff_next_ref_g\t\t\t|\n\t\t\t\talt_g_next_ref_g\t\t|\n\t\t\t\t\n\t\t\t\talt_g_next_ref_c\t\t|\n\t\t\t\t\n\t\t\t\tsame_next_ref_nt\t\t|\n\t\t\t\tdiff_next_ref_nt\t\t|\n\t\t\t\t\n\t\t\t\t(both_g . ntg{2})\t\t|\t# Corresponds to both_g in the machines below but would match more without the ntg{2}.\n\t\t\t\t(ref_g . ntg{2})\t\t\t# Corresponds to ref_g in the machines below but would match more without the ntg{2}.\n\t\t\t));\n\t\t\tfail_on_unhandled_combinations := unhandled $(report_unhandled);\n\t\t\n\t\t\t# In the following cases start a new segment at the marked position b.c.\n\t\t\t# the following characters cannot be known and this reduces the number\n\t\t\t# of special cases a bit (1).\n\t\t\t# Ref\tACG-\tACG-\n\t\t\t# Alt\tACG-\tTTG-\n\t\t\t#\t\t ^\t\t ^\n\t\t\t# Action suffixes: _b: both have non-gap, _r: ref has non-gap, _a: alt has non-gap, _g: both have gap.\n\t\t\t\n\t\t\tcommon = (\n\t\t\t\t# Since the next ref character is a gap, a new segment needs to be created since we don\u2019t know the subsequent characters.\n\t\t\t\t(same_next_both_g\t@(start_new_mixed_b))\t\t|\t# We currently don\u2019t change a matching segment to mixed, so mark the segment for post-processing here.\n\t\t\t\t(same_next_ref_g\t@(start_new_mixed_b))\t\t|\n\t\t\t\t(diff_next_ref_g\t@(start_new_mismatch_b))\t|\n\t\t\t\t(alt_g_next_ref_g\t@(start_new_mixed_r))\n\t\t\t);\n\t\t\t\n\t\t\thandle_match := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(start_new_del_r))\t\t\t|\t# Deletion in alt w.r.t. ref.\n\t\t\t\t\n\t\t\t\t(same_next_ref_nt\t@(match_continue_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(start_new_mismatch_b))\t|\n\t\t\t\t\n\t\t\t\t(both_g\t\t\t\t@(match_continue_g))\t\t|\n\t\t\t\t(ref_g\t\t\t\t@(handle_unexpected_state))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\thandle_mismatch := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(start_new_del_r))\t\t\t|\t# Deletion in alt w.r.t. ref.\n\t\n\t\t\t\t(same_next_ref_nt\t@(start_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(mismatch_continue_b))\t\t|\n\t\n\t\t\t\t(both_g\t\t\t\t@(mismatch_continue_g))\t\t|\n\t\t\t\t(ref_g\t\t\t\t@(mismatch_mark_mixed_a))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\thandle_mixed := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(start_new_del_r))\t\t\t|\t# Deletion in alt w.r.t. ref.\n\n\t\t\t\t(same_next_ref_nt\t@(start_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(start_new_mismatch_b))\t|\n\t\t\t\t\n\t\t\t\t(both_g\t\t\t\t@(mixed_continue_g))\t\t|\n\t\t\t\t(ref_g\t\t\t\t@(mixed_continue_a))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\thandle_deletion := common | (\n\t\t\t\t(alt_g_next_ref_c\t@(deletion_continue_r))\t\t|\n\t\t\t\t\n\t\t\t\t(same_next_ref_nt\t@(start_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(start_new_mismatch_b))\t|\n\t\t\t\t\n\t\t\t\t(both_g\t\t\t\t@(handle_unexpected_state))\t|\n\t\t\t\t(ref_g\t\t\t\t@(handle_unexpected_state))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\t# Starting machines. Ref is guaranteed to be non-gap. See common.\n\t\t\t# Ref\tX-\tX-\tX-\tX-\tX+\tX+\tX+\n\t\t\t# Alt\tX-\tX+\tY*\t-*\t-*\tX*\tY*\n\t\t\t#same_next_both_g\n\t\t\t#same_next_ref_g\n\t\t\t#diff_next_ref_g\n\t\t\t#alt_g_next_ref_g\n\t\t\t#alt_g_next_ref_c\n\t\t\t#same_next_ref_nt\n\t\t\t#diff_next_ref_nt\n\t\t\tmain_unexpected = ntg{4} - (same_next_both_g | same_next_ref_g | diff_next_ref_g | alt_g_next_ref_g | alt_g_next_ref_c | same_next_ref_nt | diff_next_ref_nt);\n\t\t\t\n\t\t\tmain := (\n\t\t\t\t(same_next_both_g\t@(main_new_match_b))\t\t|\n\t\t\t\t(same_next_ref_g\t@(main_new_mixed_b))\t\t|\n\t\t\t\t(diff_next_ref_g\t@(main_new_mismatch_b))\t\t|\n\t\t\t\t(alt_g_next_ref_g\t@(main_new_mixed_r))\t\t|\n\t\t\t\t(alt_g_next_ref_c\t@(main_new_deletion_r))\t\t|\n\t\t\t\t(same_next_ref_nt\t@(main_new_match_b))\t\t|\n\t\t\t\t(diff_next_ref_nt\t@(main_new_mismatch_b))\t\t|\n\t\t\t\t(main_unexpected\t@(handle_unexpected_state))\n\t\t\t) $err(handle_error);\n\t\t\t\n\t\t\twrite exec noend;\n\t\t}%%\n\t}\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"def316a95800446a5ccd77ced876c5b893a0d134","subject":"improved description of LX_TK_RESET","message":"improved description of LX_TK_RESET\n","repos":"thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext,thomastrapp\/hext","old_file":"src\/hext\/lexer.h.rl","new_file":"src\/hext\/lexer.h.rl","new_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/string-util.h\"\n\n\n\/\/\/ Convenience macro to create a token and push it onto the token-queue.\n#define LX_TK_START(tk_id) \\\n token tok; \\\n tok.tid = tk_id; \\\n tok.begin = p; \\\n tok.end = nullptr; \\\n tokens.push_back(tok);\n\n\/\/\/ Convenience macro to change last inserted token.\n#define LX_TK_RESET(tk_id) \\\n assert(tokens.size() > 0); \\\n tokens.back().tid = tk_id; \\\n tokens.back().end = p;\n\n\/\/\/ Convenience macro to mark the end of the last token in the token-queue.\n#define LX_TK_STOP \\\n assert(tokens.size() > 0); \\\n tokens.back().end = p;\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\n\/\/\/ lexer contains the ragel state machine and shields the user from its\n\/\/\/ details.\nclass lexer\n{\npublic:\n \/\/\/ Clang warns (-Wweak-vtables) that a vtable for lex_error may be placed\n \/\/\/ in every translation unit, because lex_error doesn't have any\n \/\/\/ 'out-of-line virtual method definitions', where it would normally put\n \/\/\/ the vtable. But http:\/\/stackoverflow.com\/a\/23749273 suggests that this\n \/\/\/ is a non-issue; the linker will clean it up.\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg);\n };\n\n \/\/\/ Setup ragel\n lexer(const char * begin, const char * end);\n\n \/\/\/ Throws lexer::lex_error on invalid input (by calling lexer::throw_error)\n std::vector lex();\n\nprivate:\n \/\/\/ Print diagnostics and throw lexer::lex_error.\n void throw_error() const;\n\n \/\/\/ A pointer to the beginning of the overall input is needed to provide\n \/\/\/ good error diagnostics.\n const char * p_begin;\n\n \/\/\/ ragel's runtime state\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","old_contents":"#ifndef HEXT_LEXER_H\n#define HEXT_LEXER_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hext\/token.h\"\n#include \"hext\/string-util.h\"\n\n\n\/\/\/ Convenience macro to create a token and push it onto the token-queue.\n#define LX_TK_START(tk_id) \\\n token tok; \\\n tok.tid = tk_id; \\\n tok.begin = p; \\\n tok.end = nullptr; \\\n tokens.push_back(tok);\n\n\/\/\/ Convenience macro to reset last inserted token.\n#define LX_TK_RESET(tk_id) \\\n assert(tokens.size() > 0); \\\n tokens.back().tid = tk_id; \\\n tokens.back().end = p;\n\n\/\/\/ Convenience macro to mark the end of the last token in the token-queue.\n#define LX_TK_STOP \\\n assert(tokens.size() > 0); \\\n tokens.back().end = p;\n\n\nnamespace hext {\n\n\nnamespace ragel {\n %%{\n machine hext;\n include \"hext.rl\";\n write data;\n }%%\n} \/\/ namespace ragel\n\n\n\/\/\/ lexer contains the ragel state machine and shields the user from its\n\/\/\/ details.\nclass lexer\n{\npublic:\n \/\/\/ Clang warns (-Wweak-vtables) that a vtable for lex_error may be placed\n \/\/\/ in every translation unit, because lex_error doesn't have any\n \/\/\/ 'out-of-line virtual method definitions', where it would normally put\n \/\/\/ the vtable. But http:\/\/stackoverflow.com\/a\/23749273 suggests that this\n \/\/\/ is a non-issue; the linker will clean it up.\n class lex_error : public std::runtime_error\n {\n public:\n explicit lex_error(const std::string& msg);\n };\n\n \/\/\/ Setup ragel\n lexer(const char * begin, const char * end);\n\n \/\/\/ Throws lexer::lex_error on invalid input (by calling lexer::throw_error)\n std::vector lex();\n\nprivate:\n \/\/\/ Print diagnostics and throw lexer::lex_error.\n void throw_error() const;\n\n \/\/\/ A pointer to the beginning of the overall input is needed to provide\n \/\/\/ good error diagnostics.\n const char * p_begin;\n\n \/\/\/ ragel's runtime state\n const char * p;\n const char * pe;\n const char * eof;\n int cs;\n};\n\n\n} \/\/ namespace hext\n\n\n#endif \/\/ HEXT_LEXER_H\n\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"4a673d4b9de9d0719201707d41f995bfc8f8017f","subject":"minor cleanup","message":"minor cleanup\n","repos":"mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp,mdrohmann\/mtocpp","old_file":"src\/mfilescanner.rl","new_file":"src\/mfilescanner.rl","new_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n for (unsigned int i = 0; i < defaultprop_.length(); ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = '\\\\';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n }\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n std::string defvalue;\n get_default(paramlist_[i], defvalue);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"COPY_TYPIFIED_FIELD_DOCU\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"COPY_TYPIFIED_FIELD_DOCU\")][0] == string(\"true\"))\n {\n runMode_.copy_typified_field_docu = true;\n }\n else\n {\n runMode_.copy_typified_field_docu = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOCPP:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n std::string name = (*lit).first;\n if (name.substr(0, 6) == std::string(\"unused\")\n && name.find_first_not_of(\"0123456789\", 7) == std::string::npos)\n continue;\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << name << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty() && runMode_.copy_typified_field_docu)\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n string defval;\n extract_default(docubody_, defval);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n \/* param_defaults_.clear(); *\/\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams\n && docuheader_.empty()\n && !methodparams_.abstr)\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No definition for function \" << cfuncname_\n << \" found in class \" << classname_ << \"!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::extract_default(DocuBlock & db, std::string & defvalue)\n{\n typedef DocuBlock :: iterator DBIt;\n\n for(DBIt dit = db.begin(); dit != db.end(); ++dit)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t deflength = std::string(\"(default\").length();\n found = line.find(\"(default\");\n if(found != std::string::npos)\n {\n size_t tmp;\n if(line[found+1] == '=')\n tmp = found + deflength + 1;\n else if (line[found+2] == '=')\n tmp = found + deflength + 2;\n else\n found = std::string::npos;\n\n if (found != std::string::npos)\n {\n defvalue = line.substr(tmp+1);\n defvalue = defvalue.substr(0, defvalue.length() - 1);\n }\n }\n if(found == std::string::npos)\n {\n deflength = string(\"@default \").length();\n found = line.find(\"@default \");\n if (found != std::string::npos)\n {\n size_t end = line.find(\"@\", found+1);\n if (end == std::string::npos)\n end = line.find(\"of type\");\n if (end == std::string::npos)\n end = line.length();\n end = end - 1;\n size_t start = found + deflength + 1;\n defvalue = line.substr(start, end - start);\n line[found] = '(';\n line[found+8] = '=';\n line = line.substr(0, found) + \"( @b default = \"\n + line.substr(found+9,end-found-9) + \" )\" + line.substr(end);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n }\n }\n}\n\nvoid MFileScanner::get_default(const std::string & paramname, std::string & defvalue)\n{\n typedef DocuList :: iterator DLIt;\n DLIt it = param_list_.find(paramname);\n if(it != param_list_.end() && !(it->second).empty())\n {\n DocuBlock & db = it->second;\n extract_default(db, defvalue);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\\n\\0\", typenstart );\n if (typenstart == std::string::npos)\n {\n \/\/ read in next line\n if (remove)\n (*dit).erase(found, line.length() - found - 1);\n\n ++dit;\n if (dit == db.end())\n break;\n line = *dit;\n found = 0;\n typenstart = line.find_first_not_of( \" \\t\");\n }\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ (*dit).replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n (*dit).erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess + \", \"\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nvoid MFileScanner::postprocess_unused_params(std::string & param, DocuList & doculist)\n{\n if (param == std::string(\"~\"))\n {\n int counter = 1;\n bool found = true;\n while ( found )\n {\n std::ostringstream oss;\n oss << \"unused\" << counter;\n if (doculist.find(oss.str()) == doculist.end())\n {\n param = oss.str();\n found = false;\n }\n ++counter;\n }\n }\n}\n\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","old_contents":"#include \"mfilescanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::list;\nusing std::copy;\nusing std::map;\nusing std::set;\nusing std::istream;\nusing std::ifstream;\nusing std::ostream;\nusing std::ostream_iterator;\nusing std::ostringstream;\n\nconst char * AccessEnumNames[] =\n{\n stringify( Public ),\n stringify( Protected ),\n stringify( Private )\n};\n\nconst char * ClassPartNames[] =\n{\n stringify( InClassComment ),\n stringify( Header ),\n stringify( Method ),\n stringify( AtMethod ),\n stringify( MethodDeclaration ),\n stringify( Property ),\n stringify( Event )\n};\n\n\n%%{\n machine MFileScanner;\n write data;\n\n # end of file character\n EOF = 0;\n\n # any character other than end of file\n default = ^0;\n\n # end of line character\n EOL = ('\\r'? . '\\n') @{line++;};\n\n # scanner for comment blocks\n in_comment_block :=\n (\n # comment line begins with a percent sign\n '%'\n @{ tmp_p = p+1; fout_ << \" *\"; }\n # and then some default characters\n . (default - '\\n')* . EOL\n @{ fout_.write(tmp_p, p - tmp_p+1); }\n )*\n $!{\n fout_ << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n fhold;\n fhold;\n fret;\n };\n\n action end_doxy_block\n {\n if(!docline)\n {\n p = ts-1;\n \/* go backward until first non-whitespace is found *\/\n for(p=p-1; *p==' ' || *p == '\\t'; --p)\n ;\n\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n cerr << \"MTOCPP: missing class part handling for class part: \" << ClassPartNames[class_part_] << endl;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n }\n\n # executed when end of file is reached\n action end_of_file\n {\n end_function();\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"};\\n\";\n }\n }\n\n # executed when we reached a comment block\n action in_c_block\n {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p-tmp_p+1);\n fcall in_comment_block;\n }\n\n action echo { fout_ << fc; }\n\n action st_tok { tmp_p = p; }\n\n action echo_tok {\n assert (p >= tmp_p);\n fout_.write(tmp_p, p - tmp_p);\n }\n\n action string_tok {\n assert ( p >= tmp_p );\n tmp_string.assign(tmp_p, p-tmp_p);\n }\n\n # common definitions {{{2\n\n # comment in function body that might also be added to the doxygen block for\n # the function description\n is_doxy_comment =\n (\n # if percent character is followed by a bar we make the comment a doxygen\n # comment\n '|' @{ if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/**\"; tmp_p = p+1;\n }\n . (default - '\\n')*\n . ( EOL . [ \\t]*\n . '%' @{\n assert(p >= tmp_p -1);\n fout_.write(tmp_p, p - tmp_p);\n fout_ << \" * \";\n tmp_p = p+1;\n }\n . (default - '\\n')* )* . EOL\n |\n # else: a regular comment\n ( (default - '|')\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n tmp_p = p;\n } )\n . (default - '\\n')* . EOL\n );\n\n # comment block in function body\n comment_block = [ \\t]* . '%' . is_doxy_comment;\n\n # an empty line\n empty_line = [\\t ]* . EOL;\n\n # documentation line begin\n doc_begin = [\\t ]* . '%' @{ tmp_p = p + 1; };\n\n # swallow a comment line till the end of the line (make it a c comment)\n garble_comment_line =\n ( (default - [\\r\\n])* . EOL )\n @{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"*\/\";\n }\n fout_ << \"\/* \";\n assert( p >= tmp_p );\n fout_.write(tmp_p, p - tmp_p) << \"*\/\\n\";\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \";\n }\n };\n garble_comment_line_wo_eol =\n (default - [\\r\\n])*;\n\n # white space or comment\n WSOC =\n ( [ \\t]+\n | ('%' @{ tmp_p = p+1; } . garble_comment_line)\n | ('...'.[ \\t]*.EOL)\n );\n\n # matlab identifier\n IDENTEND = [A-Za-z0-9_];\n IDENT = [A-Za-z_]IDENTEND**;\n\n\n # matlab identifier with .\n IDENT_W_DOT = [A-Za-z_][A-Za-z0-9_.]**;\n\n # default arguments in function declarations\n default_arg = [^,)]** @echo;\n\n #}}}2\n\n # parameter list for functions {{{2\n paramlist =\n (\n (WSOC | [,\\n]\n# @{if(*p=='\\n' || paramlist_.size() != 1 || paramlist_[0] != string(\"this\" )) {\n# \/\/buffer_.append(std::string(*p));\n# } }\n | ( '=' . default_arg ) )+\n |\n # matlab identifier (parameter)\n (IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n bool addBlock = true;\n \/\/ do not print this pointer\n if( is_class_ && ( !methodparams_.statical\n && (\n ( class_part_ == Method\n && cfuncname_ != classname_\n )\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration\n )\n )\n && ( ! (\n methodparams_.abstr\n && !runMode_.remove_first_arg_in_abstract_methods\n )\n )\n )\n {\n if(paramlist_.empty())\n {\n addBlock = false;\n paramlist_.push_back(string(\"this\"));\n }\n else if(paramlist_.size() == 1 && paramlist_[0] == string(\"this\"))\n paramlist_.clear();\n }\n\n if(addBlock) {\n\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"found parameter: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n postprocess_unused_params(s, param_list_);\n \/\/ add an empty docu block for parameter \\a s\n if(param_list_.find(s) == param_list_.end())\n {\n param_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n{\n ostringstream oss;\n oss << \"in paramlist: add to paramlist: \" << s;\n debug_output(oss.str(), p);\n}\n#endif\n paramlist_.push_back(s);\n }\n }\n )**;\n\n # return parameter list for functions\n lparamlist =\n ( (WSOC | [\\n])+\n | ','\n # matlab identifier (return value)\n | ( (IDENT | '~') > st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for return value \\a s\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n }\n )\n )**;\n\n # return parameter or return parameter list\n lparams =\n (\n (\n (\n # matlab identifier\n ( IDENT | '~' )\n >st_tok\n %{\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p);\n postprocess_unused_params(s, return_list_);\n returnlist_.push_back(s);\n \/\/ add an empty docu block for single return value \\a s\n\n if(return_list_.find(s) == return_list_.end())\n {\n return_list_[s] = DocuBlock();\n }\n#ifdef DEBUG\n cerr << \"\\n In return list: \" << endl;\n#endif\n }\n )\n | ( '['\n . lparamlist\n . ']'\n )\n )\n . ( [ \\t]+ | ([ \\t].'...'.[ \\t]*.EOL))*\n :> '=' . WSOC*\n );\n # }}}2\n\n # a line in the function body {{{2\n funcline := |*\n # empty line\n ([ \\t]+)\n => { fout_.write(ts, te-ts); };\n\n # line continuation\n ('...' . [ \\t]* . EOL)\n => { fout_.write(ts, te-ts); };\n\n # two single quote in a row need to be changed to nothing\n ('\\'\\'');\n\n # a string should not be parsed for comment blocks, so we handle it separately.\n ('\\'' . [^'\\n]+ . '\\'')\n => {\n \/\/ change double quotes to quotes and vice versa...\n fout_ << \"\\\" \";\n string s(ts+1, te-ts-2);\n std::replace(s.begin(), s.end(), '\\\"', '\\'');\n fout_ << s;\n fout_ << \" \\\"\";\n };\n\n # ('%' @{ tmp_p = p + 1; } . garble_comment_line);\n (comment_block)\n => {\n assert(p >= tmp_p-1);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # automatically add return value fields to retval_list_\n (\n # matlab identifier (which can be a return value and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT >(st_tok) %{tmp_p2 = p;} )\n # if a value is assigned to this field, the field is generated\/modified\n . [ \\t]* . '=' . (^'=')\n )\n => {\n fhold;\n \/\/ store fieldname\n assert(tmp_p2 >= tmp_p);\n string s(tmp_p, tmp_p2 - tmp_p);\n fout_ << tmp_string << \".\" << s << \"=\";\n \/\/ typedef of iterators\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a return value\n iterator it = find(returnlist_.begin(), returnlist_.end(), tmp_string);\n if(it != returnlist_.end())\n {\n \/\/ if it is a return value...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ retval list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n \/\/ if it is missing, add an empty docu block\n if(missing)\n {\n retval_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # automatically add parameter fields to required_list_\n (\n # matlab identifier (which can be a parameter and a structure)\n (IDENT\n %{tmp_string.assign(ts,p-ts);})\n . '.'\n # matlab identifer (fieldname)\n . (IDENT_W_DOT\n >(st_tok)\n )\n )\n => {\n \/\/ store fieldname\n assert(p >= tmp_p);\n string s(tmp_p, p - tmp_p+1);\n fout_ << tmp_string << \".\" << s;\n typedef DocuList :: iterator list_iterator;\n typedef DocuListMap :: iterator map_iterator;\n typedef DocuBlock :: iterator iterator;\n\n \/\/ check wether first IDENT is a parameter\n iterator it = find(paramlist_.begin(), paramlist_.end(), tmp_string);\n if(it != paramlist_.end())\n {\n \/\/ if it is a parameter ...\n \/\/ ... check wether its found field is still missing a DocuBlock in the\n \/\/ return, optional and the required list.\n bool missing = true;\n map_iterator rvoit = retval_list_.find(tmp_string);\n if(rvoit != retval_list_.end())\n {\n list_iterator lit = (*rvoit).second.find(s);\n \/\/ found match in retval list\n if(lit != (*rvoit).second.end())\n missing = false;\n }\n map_iterator moit = optional_list_.find(tmp_string);\n if(moit != optional_list_.end())\n {\n \/\/ found match in optional list\n list_iterator lit = (*moit).second.find(s);\n if(lit != (*moit).second.end())\n missing = false;\n }\n map_iterator roit = required_list_.find(tmp_string);\n if(roit != required_list_.end())\n {\n \/\/ found match in required list\n list_iterator lit = (*roit).second.find(s);\n if(lit != (*roit).second.end())\n missing = false;\n }\n \/\/ in case it IS missing, add an empty field to the required block.\n if(missing)\n {\n required_list_[tmp_string][s] = DocuBlock();\n }\n }\n };\n\n # add a @deprecated command to function declaration if disp_deprecated is\n # used in function body\n ('disp_deprecated' . [ \\t]*\n . (\n ';'\n @{tmp_string.assign(\"\");}\n |\n '(' . [\\t ]* . \"'\"\n . ([^\\n']*\n >(st_tok)\n %(string_tok)\n )\n . \"'\" . [\\t ]* . ')' . [\\t ]* . ';'\n )\n . [\\t ]* . EOL\n )\n => {\n string s;\n if(tmp_string.empty())\n {\n s.assign(\"@deprecated function deprecated\\n\");\n }\n else\n {\n s.assign(\"@deprecated method deprecated, use \\'\" + tmp_string + \"\\' instead.\\n\");\n }\n docuextra_.push_back(s);\n fhold;\n };\n\n # simple matlab identifier\n (IDENT)\n => { fout_.write(ts, te-ts); };\n\n # translate curly brackets in edgy brackets, because otherwise the doxygen\n # parser breaks.\n ('{')\n => { fout_ << '['; };\n\n ('}')\n => { fout_ << ']'; };\n\n # simply output all other characters\n (default - [\\n{}])\n => { fout_ << fc; };\n\n # after EOL try to check for new function\n EOL\n => { fout_ << fc; fgoto funcbody; };\n\n *|;\n # }}}2\n\n # function body {{{2\n funcbody := |*\n\n # things that got replaced in function body {{{4\n ('% TO BE ADJUSTED TO NEW SYNTAX\\n')\n => {\n new_syntax_ = true;\n fout_ << \"*\/\\n\"; \/\/fout_ << \"add to special group *\/\\n\";\n };\n\n # a comment block\n (comment_block)\n => {\n assert(p+1 >= tmp_p);\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n # empty line\n ([ \\t]* . EOL)\n => { fout_ << '\\n'; };\n\n #}}}4\n\n # things that could end the function body {{{4\n # line not beginning with words 'function' or 'end'\n ([ \\t]*\n . ( (default - [ \\r\\t\\n%])+ - ('function'|'end') )\n )\n => {\n p = ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline\", p);\n#endif\n fgoto funcline;\n };\n\n # line only containing word 'end'\n # the keyword needs to be in the same indentation level as beginning function\n ([ \\t]* . 'end' . ';'* . (WSOC | EOL ) )\n => {\n if(is_class_ && class_part_ == Method)\n {\n tmp_string.assign(ts,p-ts+1);\n\n if(tmp_string.find(\"e\") == funcindent_)\n {\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto methods\", p);\n#endif\n fgoto methods;\n }\n }\n \/\/ else\n p=ts-1;\n \/\/ further parse the function body line\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto funcline 2\", p);\n#endif\n fgoto funcline;\n };\n\n # line beginning with word 'function'\n ([ \\t]*. 'function ')\n {\n p = ts-1;\n if (!is_class_)\n {\n \/\/ end the previous function if existent\n end_function();\n#ifdef DEBUG\ndebug_output(\"in funcbody: goto main\", p);\n#endif\n fgoto main;\n }\n else\n {\n fgoto funcline;\n }\n };\n\n (EOF) $eof(end_of_file);\n\n # }}}4\n\n *|;\n # }}}2\n\n # fill a docublock list with input {{{2\n fill_list := |*\n\n # match an argument\n ( doc_begin . [ \\t]*\n . \"'\"? . ( ([A-Za-z][A-Za-z0-9_{},()[\\].]*) >{tmp_p3 = p;} %{tmp_p2 = p;} ) . \"'\"? . [ \\t]* . \":\" @(st_tok)\n . ( default - '\\n' )* . EOL\n )\n => {\n assert(tmp_p2 >= tmp_p3);\n tmp_string.assign(tmp_p3, tmp_p2 - tmp_p3);\n \/\/ std::fout_ << tmp_string << '\\n';\n assert(p >= tmp_p);\n (*clist_)[tmp_string].push_back(string(tmp_p+1, p - tmp_p));\n };\n\n # expand the paragraph for last argument matched\n ( doc_begin . [ \\t]*\n # at least one word (non white-space characters and no double-colon)\n . ( default - [ \\r\\t:\\n] )+ .\n # followed by something that is a white-space or a new-line, i.e *no*\n # double-colon\n (\n EOL\n |\n [ \\t]+ . (EOL | [^ \\r\\n\\t:] . (default - '\\n')* . EOL)\n # [ \\t] . (default - '\\n')* . EOL\n )\n )\n => {\n assert(p+1 >= tmp_p);\n string s(tmp_p, p - tmp_p + 1);\n (*clist_)[tmp_string].push_back(s);\n \/*fout_ << \"add something results in\\n\" << (*clist_)[tmp_string];*\/\n };\n\n # return on empty line\n ( doc_begin . [ \\t]* . EOL )\n => { \/*fout_ << \"empty line\\n\";*\/ fret; };\n\n # end of comment block\n ( [\\t ]* . ( (default - '%') | EOL) )\n => {\n p =ts-1;\n \/\/ fout_ << \"*\/\\n\";\n fret;\n };\n\n *|; #}}}2\n\n # parse body of documentation block {{{2\n doxy_get_body := |*\n\n # special lists {{{4\n\n # begin required_list\n ( doc_begin . [ \\t]*\n . \/required fields of \/i\n . (IDENT >(st_tok) %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL\n )\n => {\n \/\/fout_ << tmp_string << '\\n';\n clist_ = &(required_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/optional fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(optional_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin optional_list\n ( doc_begin . [ \\t]*\n . \/generated fields of \/i\n . (IDENT\n >(st_tok)\n %(string_tok) )\n . [ \\t]* . ':' . [ \\t]* . EOL )\n => {\n clist_ = &(retval_list_[tmp_string]);\n docline = false;\n fcall fill_list;\n };\n\n # begin parameter list\n ( doc_begin . [ \\t]*\n . \/parameters\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = ¶m_list_;\n docline = false;\n fcall fill_list;\n };\n\n # begin return list\n ( doc_begin . [ \\t]*\n . \/return values\/i . [ \\t]* . ':'\n . [ \\t]* . EOL )\n => {\n clist_ = &return_list_;\n docline = false;\n fcall fill_list;\n };\n #}}}4\n\n # default substitutions {{{4\n\n # empty line\n ( doc_begin . [ \\t]* . EOL )\n => {\n \/*fout_ << \"*\\n \";*\/\n docubody_.push_back(\"\\n\");\n docline = false;\n };\n\n # paragraph line\n ( [ \\t]* . '%' )\n => {\n if(!docline)\n {\n docline = true;\n tmp_p = p;\n }\n };\n\n # paragraph line with \"see also\" substituted by \"@sa\"\n ( \/see also\/i . ':'? )\n => {\n string s;\n assert(ts > tmp_p);\n s.assign(tmp_p+1, ts - tmp_p-1);\n docubody_.push_back(s+\"@sa\");\n tmp_p = p;\n };\n\n # lines that could end doxyblock {{{6\n # words\n # ( default - [ \\t:%'`\\n] )+\n ( default - [ \\t:%\\r\\n] )+ @(end_doxy_block);\n\n # non-words\/non-whitespace\n # ([:'`]) => {\n (':') @(end_doxy_block) ;\n\n\n # whitespace only\n ( [ \\t] );\n\n # titled paragraph\n ( ':' . EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n assert(ts > tmp_p);\n docubody_.push_back(\"@par \" + string(tmp_p+1, ts - tmp_p-1)+\"\\n\");\n docline = false;\n }\n };\n # }}}6\n # }}}4\n\n # end of line {{{4\n ( EOL )\n @(end_doxy_block)\n @{ if(docline)\n {\n int offset = ( latex_begin ? 0 : 1 );\n assert(p >= tmp_p + offset);\n docubody_.push_back(string(tmp_p+1, p - tmp_p - offset));\n docline = false;\n }\n };\n # }}}4\n\n *|;\n #}}}2\n\n # doxy header parsing {{{2\n # swallow the synopsis line\n doxyfunction_garble := |*\n garbage = ( (default - '\\n' )* -- '...' );\n\n ( doc_begin . (garbage . '...')+ . [\\t ]* . EOL );\n\n ( doc_begin . (garbage . '...')* . garbage . EOL )\n => { fgoto doxy_get_brief; };\n *|;\n\n\n # read first paragraph\n doxy_get_brief := |*\n\n # read in one comment line\n ( doc_begin . [\\t ]*\n . (default - [\\r\\n\\t ]) . (default - '\\n')* . EOL\n )\n => {\n \/* fout_ << \"*\"; fout_.write(tmp_p, p - tmp_p+1); *\/\n assert(p >= tmp_p);\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n };\n\n # empty line\n ( doc_begin . [\\t ]* . EOL )\n => {\n \/*fout_ << \"*\\n\";*\/\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: goto: doxy_get_body\", p);\n#endif\n fgoto doxy_get_body;\n };\n\n # end of comment block;\n ( [\\t ]* . [^%] )\n => {\n p=ts-1;\n#ifdef DEBUG\n debug_output(\"in doxy_get_brief: end!!\", p);\n#endif\n \/\/fout_ << \"*\/\\n\";\n if(is_class_)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: this is a class\",p);\n#endif\n\n if(class_part_ == Header)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto classbody\",p);\n#endif\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcbody\",p);\n#endif\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n else if(class_part_ == MethodDeclaration)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto funcdef\",p);\n#endif\n fgoto funcdef;\n }\n else if(class_part_ == Property)\n {\n#ifdef DEBUG\n debug_output(\" in_doxy_get_brief: method: goto propertybody\",p);\n#endif\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment)\n {\n class_part_ = Method;\n fgoto methods;\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n\n *|;\n # }}}2\n\n # garble synopsis line and then parse the documentation header {{{2\n doxyheader := (\n '%' . [ \\t]* .\n (\n ('function '|'classdef ') @{ p = tmp_p-2; fgoto doxyfunction_garble; }\n )\n $!{\n#ifdef DEBUG\n debug_output(\"doxy_get_brief\",p);\n#endif\n p = tmp_p - 2;\n fgoto doxy_get_brief;\n }\n ); #}}}2\n\n # helper for setting the access specifier {{{2\n paramaccess =\n ( ('SetAccess' . WSOC* . '=' . WSOC*\n . ( (\/public\/i\n @{ access_.full = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.get == Public ? Public : Protected );\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.get;\n access_.set = Private;\n } )\n )\n )\n | ( 'GetAccess' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n } )\n | ( \/protected\/i\n @{ access_.full =\n (access_.set == Public ? Public : Protected );\n access_.get = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = access_.set;\n access_.get = Private;\n } )\n )\n )\n | ( 'Access' . WSOC* . '=' . WSOC*\n . ( ( \/public\/i\n @{ access_.full = Public;\n access_.get = Public;\n access_.set = Public;\n } )\n | ( \/protected\/i\n @{ access_.full = Protected;\n access_.get = Protected;\n access_.set = Protected;\n } )\n | ( \/private\/i\n @{ access_.full = Private;\n access_.get = Private;\n access_.set = Private;\n } )\n )\n )\n ); #}}}2\n\n # method and property params {{{2\n methodparam =\n (\n ( paramaccess )\n | ( ( 'Abstract' . [^,)]* )\n @{\n methodparams_.abstr = true;\n } )\n | ( ( 'Static' . [^,)]* )\n @{\n methodparams_.statical = true;\n } )\n | ( ('Hidden' . [^,)]* )\n @{\n methodparams_.hidden = true;\n } )\n | ( ( 'Sealed' . [^,)]* )\n @{\n methodparams_.sealed = true;\n } )\n );\n\n propertyparam =\n (\n ( paramaccess )\n | ( ( 'Constant' . [^,)]* )\n @{\n propertyparams_.constant = true;\n } )\n | ( ( 'Transient' . [^,)]* )\n @{\n propertyparams_.transient = true;\n } )\n | ( ( 'Dependent' . [^,)]* )\n @{\n propertyparams_.dependent = true;\n } )\n | ( ( 'Hidden' . [^,)]* )\n @{\n propertyparams_.hidden = true;\n } )\n | ( ( 'SetObservable' . [^,)]* )\n @{\n propertyparams_.setObservable = true;\n } )\n | ( ( 'Abstract' . [^,)]* )\n @{\n propertyparams_.abstr = true;\n } )\n );\n\n methodparams =\n (\n '(' . WSOC*\n . methodparam\n . ( WSOC* . ',' . WSOC* . methodparam )* . WSOC* . ')'\n );\n\n propertyparams =\n (\n '(' . WSOC*\n . propertyparam\n . ( WSOC* . ',' . WSOC* . propertyparam )* . WSOC* . ')'\n ); #}}}2\n\n # swallowing events {{{2\n events := (\n ( ([ \\t]* . 'e') >st_tok\n . 'nd' . [ \\t;]* . EOL\n @{ tmp_string.assign(tmp_p, p - tmp_p);\n if(tmp_string.find(\"e\") == eventindent_)\n {\n fgoto classbody;\n }\n }\n | (default* - 'end') . EOL )*\n ); #}}}2\n\n # methods and properties {{{2\n # methods {{{4\n methods := |*\n# kommentare, newlines\n# nur bei keyword 'function' => goto funcdef\n# abstrakter fall, eine weitere Regel wird ben\u00f6tigt.\n# end => classbody\n (empty_line) => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n fout_ << \"\\n\";\n }\n };\n\n # default: method definition\n ([ \\t]* . 'function' )\n => {\n tmp_string.assign(ts, te - ts+1);\n funcindent_ = tmp_string.find_first_not_of(\" \\t\");\n #if DEBUG\n {\n ostringstream oss;\n oss << \"in methods: funcindent: \" << funcindent_;\n debug_output(oss.str(), p);\n }\n #endif\n p=ts+funcindent_-1;\n fgoto funct;\n };\n\n # end of methods block\n ([ \\t]* . 'end' . [ \\t;]* . ('%' . garble_comment_line_wo_eol)? . EOL )\n => {\n if(runMode_.mode != RunMode::ParseMethodParams)\n {\n end_method();\n #if DEBUG\n debug_output(\"in methods: found end keyword, goto classbody\",p);\n #endif\n }\n fgoto classbody;\n };\n\n # comment between two methods\n ([ \\t]* . '%' ) => {\n #if DEBUG\n debug_output(\"in methods: garble comment line\",p);\n #endif\n\n p = ts-1;\n class_part_ = InClassComment;\n\/* fcall in_comment_block; *\/\n fgoto expect_doxyblock;\n };\n\n # if we reach this: method declaration without definition is found\n ([ \\t]* . [^% \\t\\n]) =>\n {\n #if DEBUG\n debug_output(\"in methods: found method declaration, going to funcdef\",p);\n #endif\n class_part_ = MethodDeclaration;\n p = ts-1;\n fgoto funcdef;\n };\n\n *|;\n\n\n methodsheader := (\n [ \\t]* . methodparams? . [ \\t;]* . ( '%' . garble_comment_line_wo_eol )? . EOL\n @{\n print_access_specifier(access_.full);\n fgoto methods;\n }\n );\n\n #}}}4\n\n matrix_or_cell := (\n '[' . ( [^[{\\]] | [[{] @{fhold; fcall matrix_or_cell;} )* . ']' @{ fret; }\n |\n '{' . ( [^[{}] | [[{] @{fhold; fcall matrix_or_cell;} )* . '}' @{ fret; }\n );\n\n matrix = ([[{] @{fhold; fcall matrix_or_cell;} );\n\n\n # single property {{{4\n prop = ( ( [ \\t]* . (IDENT) >st_tok\n %{\n string s(tmp_p, p - tmp_p);\n property_list_.push_back(s);\n\/\/ fout_ << propertyparams_.ccprefix() << \" \" << s;\n }\n )\n . ( ';' @{defaultprop_ = \"\";}\n |\n ([ =]+ %st_tok . ( matrix | [^[{;])* .';')\n @{\n defaultprop_ = string(tmp_p, p - tmp_p);\n for (int i = 0; i < defaultprop_.length(); ++i)\n {\n if(defaultprop_[i] == '.' && defaultprop_[i+1] == '.' && defaultprop_[i+2] == '.')\n {\n defaultprop_[i] = ' ';\n defaultprop_[i+1] = ' ';\n defaultprop_[i+2] = '\\\\';\n }\n\/* else if(defaultprop_[i] == '[')\n defaultprop_[i] = '{';\n else if(defaultprop_[i] == ']')\n defaultprop_[i] = '}'; *\/\n else if(defaultprop_[i] == ';' && i < defaultprop_.length() - 1)\n defaultprop_[i] = ',';\n }\n }\n )\n . [ \\t]* .\n ( '%' %st_tok . ( default - [\\r\\n] )*\n . EOL\n @{\n docuheader_.push_back(string(tmp_p, p - tmp_p+1));\n end_of_property_doc();\n } | EOL @{ end_of_property_doc(); }\n )\n );\n\n #}}}4\n\n property := ( prop* );\n\n #property body {{{4\n propertybody = (\n ( [ \\t]* . ( 'end' . [ \\t;]* ) . ('%' . garble_comment_line_wo_eol )? . EOL )\n @{\n fgoto classbody;\n }\n |\n (prop)\n |\n ( (empty_line) @{ fout_ << \"\\n\";} )\n |\n ( ([ \\t]* . '%') @{ fhold; fgoto expect_doxyblock; } )\n );\n\n properties := ( (\n WSOC* . propertyparams? . [ \\t;]* . ('%' . garble_comment_line_wo_eol )? . EOL @{\n print_access_specifier(access_.full);\n }\n . propertybody* )\n );\n #}}}4\n\n #}}}2\n\n # class body {{{2\n classbody := |*\n\n # a comment block\n (comment_block)\n => {\n fout_.write(tmp_p, p - tmp_p+1);\n fcall in_comment_block;\n };\n\n (WSOC) => { fout_.write(ts, te-ts); };\n\n (EOL) => { fout_ << \"\\n\"; };\n\n ('end' . [ \\t]* ';'?) => {\n fout_ << \"\\n};\\n\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n fout_ << \"}\\n\";\n }\n };\n\n ([ \\t]* . 'properties')\n => {\n propertyparams_ = PropParams();\n access_ = AccessStruct();\n class_part_ = Property;\n fgoto properties;\n };\n ([ \\t]* . 'methods')\n => {\n methodparams_ = MethodParams();\n access_ = AccessStruct();\n class_part_ = Method;\n fgoto methodsheader;\n };\n ([ \\t]* . 'events')\n => {\n std::string tmp_string(ts, te-ts);\n eventindent_ = tmp_string.find(\"e\");\n class_part_ = Event;\n fgoto events;\n };\n *|; #}}}2\n\n # doxyblock expect {{{2\n # after function declaration expect a documentation block or the function\n # body\n expect_doxyblock :=\n (\n doc_begin\n @{\n \/\/fout_ << \"\/*\";\n p--;\n fgoto doxyheader;\n }\n )\n $!{\n fhold;\n#ifdef DEBUG\n debug_output(\"stopping expect_doxyblock\", p);\n#endif\n if(is_class_)\n {\n if(class_part_ == Header)\n {\n end_of_class_doc();\n fgoto classbody;\n } else if(class_part_ == Method || class_part_ == AtMethod)\n {\n string endstringtest;\n endstringtest.assign(p, 100);\n string::size_type first_char = endstringtest.find_first_not_of(\" \\t\");\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n if (endstringtest.substr(first_char, 3) == \"end\")\n {\n p += first_char+4;\n print_function_synopsis();\n end_function();\n fgoto methods;\n }\n else\n {\n print_function_synopsis();\n fgoto funcbody;\n }\n }\n else if(class_part_ == Property)\n {\n fgoto propertybody;\n }\n else if(class_part_ == InClassComment || class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else{\n cerr << \"MTOCPP: Do not know where to go from here. Classpart \" << ClassPartNames[class_part_] << \" is not handled.\\n\";\n }\n }\n else\n {\n if(runMode_.mode == RunMode::ParseParams)\n return 1;\n print_function_synopsis();\n fgoto funcbody;\n }\n };\n #}}}2\n\n # function declaration {{{2\n funcdef = (\n (WSOC)* .\n # return values (if found opt = true)\n (lparams)? .\n # matlab identifier (function name stored in cfuncname_)\n ( ('get.' @{is_getter_ = true;} | 'set.' @{is_setter_=true;} )? .\n IDENT\n >st_tok\n %{\n cfuncname_.assign(tmp_p, p - tmp_p);\n #ifdef DEBUG\n cerr << \"\\n Identifier of function: \" << cfuncname_ << endl;\n #endif\n \/\/ in ParseMethodParams mode, we only check for the method\n \/\/ parameters of a specific method.\n if(is_class_ && class_part_ == MethodDeclaration\n && runMode_.mode == RunMode::ParseMethodParams)\n {\n if(runMode_.methodname == cfuncname_)\n {\n return 0;\n }\n }\n if(runMode_.mode == RunMode::Normal\n && is_class_ && class_part_ == AtMethod)\n {\n update_method_params(cfuncname_);\n }\n is_script_ = false;\n }\n )\n . WSOC*\n . (\n '('\n # parameter list\n . ( paramlist\n %{\n if(paramlist_.size() == 1 && paramlist_[0] == \"this\")\n { paramlist_.clear(); }\n }\n )\n . ')' . ( [ \\t] | ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )*\n . EOL\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n if(is_class_ && class_part_ == MethodDeclaration )\n {\n class_part_ = Method;\n #if DEBUG\n debug_output(\"in funcdef: end of method declaration, returning to methods\",p);\n #endif\n fgoto methods;\n }\n else\n {\n \/\/ fout_ << tmp_string << \"{\\n\";\n \/\/ check for documentation block\n fgoto expect_doxyblock;\n }\n }\n # no parameter list && first function => ( script || method )\n | (( [ \\t]\n |\n ('%' @{ tmp_p=p; comment_found=true; }\n . garble_comment_line_wo_eol) | ( ';' ) )* . EOL)\n @{\n if(comment_found)\n {\n tmp_string.assign(tmp_p+1, p - tmp_p-1);\n tmp_string = string(\"\/* \") + tmp_string + string(\"*\/\");\n }\n else\n {\n tmp_string = \"\";\n }\n comment_found = false;\n #if DEBUG\n debug_output(\"in funcdef: script && no parameters: expect doxyblock\",p);\n #endif\n if(is_class_ && class_part_ == MethodDeclaration)\n {\n class_part_ = Method;\n fgoto methods;\n }\n else\n {\n fgoto expect_doxyblock;\n }\n }\n )\n );\n\n funct :=\n (\n (\n comment_block @in_c_block\n | [ \\t]*. EOL\n )*\n . [\\t]* . 'function'\n . funcdef\n ) $eof( end_of_file ) ; #}}}2\n\n # no function definition => a script {{{2\n script := (default)\n @{\n string :: size_type found = filename_.rfind(\"\/\");\n if(found == string :: npos)\n found = -1;\n string funcname = filename_.substr(found+1, filename_.size()-3-found);\n cfuncname_.assign( funcname );\n \/* fout_ << \"noret::substitute \";\n if(!is_first_function_)\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n fout_ << funcname << \"() {\\n\";*\/\n is_script_ = true;\n fhold;\n fgoto expect_doxyblock;\n }; #}}}2\n\n # class definitions {{{2\n classparams =\n '(' . [^)]* . ')';\n\n superclass =\n ( ( IDENT_W_DOT ) >{ fout_ << \"public ::\"; }\n @{ if(*p == '.')\n fout_ << \"::\";\n else fout_ << *p; } );\n\n superclasses = (\n '<' @{ fout_ << \"\\n :\"; } . WSOC* . superclass . WSOC*\n . ('&' @{ fout_ << \",\\n \"; } . WSOC* . superclass . WSOC*)* );\n\n classdef := (\n 'classdef' . WSOC* . ('(' . WSOC*\n . ( 'Sealed'\n @{\n docuextra_.push_back(std::string(\"@note This class has the class property 'Sealed' and cannot be derived from.\"));\n }\n ) . [^)]* . ')')? . WSOC* .\n # matlab identifier (class name stored in classname_)\n ( IDENT\n >st_tok\n %{\n classname_.assign(tmp_p, p - tmp_p);\n is_class_ = true;\n fout_ << \"class \" << classname_;\n }\n )\n . WSOC*\n . classparams?\n . WSOC*\n . superclasses?\n . [ \\t;]*\n . ( '%'. garble_comment_line_wo_eol )?\n EOL\n @{\n fout_ << \" {\\n\";\n fgoto expect_doxyblock;\n } );\n\n # }}}2\n\n # main loop {{{2\n expect_function_script_or_class =\n (\n # either we find a function or classdef definition with a possibly\n # preceding comment block or we have a script\n ( any @{ fhold; tmp_p = p; } .\n (\n [ \\t]*. '%' . (any - '\\n')* . EOL\n | [ \\t]*. EOL\n )*\n . [\\t]*\n . ( 'function' @{\n p=tmp_p;\n if(is_class_ && class_part_ == Header)\n class_part_ = AtMethod;\n fgoto funct;\n }\n | 'classdef' @{\n p=tmp_p;\n fgoto classdef;\n }\n ) )\n $!{\n#ifdef DEBUG\n debug_output(\"goto script\",p);\n#endif\n p=tmp_p;\n fgoto script;\n }\n );\n\n main := expect_function_script_or_class*;\n # }}}2\n\n}%%\n\nvoid MFileScanner :: update_method_params(const std::string & methodname)\n{\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + classname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode methodParamsMode = runMode_;\n methodParamsMode.mode = RunMode::ParseMethodParams;\n methodParamsMode.methodname = methodname;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), methodParamsMode);\n scanner.execute();\n methodparams_ = scanner.getMethodParams();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No method params for @-function \" << methodname << \" found!\\n\";\n }\n}\n\nvoid MFileScanner :: print_pure_function_synopsis()\n{\n \/\/ do we have a constructor?\n if(is_class_ && (cfuncname_ == classname_))\n returnlist_.clear();\n else{\n if(returnlist_.size() == 0)\n fout_ << \"noret::substitute \";\n else\n {\n if(returnlist_.size() > 1)\n fout_ << \"mlhsSubst<\";\n for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\n if(runMode_.void_type_in_return_values)\n get_typename(returnlist_[i], typen, \"void\");\n else\n get_typename(returnlist_[i], typen);\n\n fout_ << \"mlhsInnerSubst<\" << typen;\n if (runMode_.print_return_value_name - (returnlist_.size() == 1) > 0)\n fout_ << \",\" << returnlist_[i];\n fout_ << \"> \";\n if (i < returnlist_.size() - 1)\n fout_ << \",\";\n }\n if(returnlist_.size() > 1)\n fout_ << \"> \";\n }\n }\n\n bool first = true;\n if(is_first_function_)\n {\n if(is_class_ && class_part_ == AtMethod)\n fout_ << namespace_string() << classname_ << \"::\";\n }\n else\n fout_ << \"mtoc_subst_\" << fnname_ << \"_tsbus_cotm_\";\n\n fout_ << cfuncname_;\n\n if(paramlist_.size() == 0)\n fout_ << \"()\\n \";\n else\n {\n#if DEBUG\n cerr << \"paramlist size of \" << cfuncname_ << \": \" << paramlist_.size() << \" first element: \" << paramlist_[0] << endl;\n#endif\n fout_ << \"(\";\n for(unsigned int i=0; i < paramlist_.size(); ++i)\n {\n if(!first)\n fout_ << \",\";\n else\n first = false;\n\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(paramlist_[i], typen);\n std::string defvalue;\n get_default(paramlist_[i], defvalue);\n fout_ << typen << \" \" << paramlist_[i];\n }\n\/* for(unsigned int i=0; i < returnlist_.size(); ++i)\n {\n std::string typen;\/\/ = \"matlabtypesubstitute\";\n get_typename(returnlist_[i], typen);\n }\n*\/\n fout_ << \")\";\n }\n}\n\nvoid MFileScanner :: print_function_synopsis()\n{\n if(is_getter_ || is_setter_)\n {\n fout_ << \"\/* \\n\";\n }\n if(is_class_ && (class_part_ == Method\n || class_part_ == AtMethod\n || class_part_ == MethodDeclaration)\n )\n {\n fout_ << methodparams_.ccprefix();\n }\n\n print_pure_function_synopsis();\n\n if(is_class_ && class_part_ == MethodDeclaration )\n fout_ << methodparams_.ccpostfix() << \"\\n\";\n else\n fout_ << \" {\\n\";\n}\n\nstd::string MFileScanner :: access_specifier_string(AccessEnum & access)\n{\n if(access == Public)\n return \"public\";\n else if(access == Protected)\n return \"protected\";\n else if(access == Private)\n return \"private\";\n return \"\";\n}\n\nvoid MFileScanner :: print_access_specifier(AccessEnum & access)\n{\n const std::string ass = access_specifier_string(access);\n fout_ << ass << \":\\n\";\n}\n\n\/\/ constructor\nMFileScanner :: MFileScanner(istream & fin, ostream & fout,\n const std::string & filename,\n const std::string & conffilename,\n RunMode runMode = RunMode()\n ) :\n fin_(fin), fout_(fout), filename_(filename),\n cscan_(filename_, conffilename),\n fnname_(filename), namespaces_(),\n buf(new char[BUFSIZE]), line(1),\n ts(0), have(0), top(0),\n opt(false), new_syntax_(false),\n is_script_(false), is_first_function_(true),\n is_class_(false), is_setter_(false), is_getter_(false),\n classname_(), funcindent_(0), eventindent_(0),\n class_part_(Header),\n access_(), propertyparams_(), methodparams_(), property_list_(),\n runMode_(runMode)\n{\n string::size_type found = fnname_.find_last_of('\/');\n if(found != string::npos)\n dirname_ = filename.substr(0, found);\n\n list namespaces;\n string classname;\n string::size_type enddir = dirname_.size();\n string::size_type ppos = 0;\n while (ppos != string::npos)\n {\n ppos = dirname_.find_last_of('\/', enddir);\n string directory;\n if(ppos == string::npos)\n directory = dirname_.substr(0, enddir+1);\n else\n directory = dirname_.substr(ppos+1, enddir-ppos);\n\n if(directory[0] == '+')\n {\n namespaces_.push_front(directory.substr(1));\n }\n else if(directory[0] == '@')\n {\n classname_ = directory.substr(1);\n is_class_ = true;\n if(classname_\n != fnname_.substr(fnname_.find_last_of('\/')+1, classname_.size()))\n {\n class_part_ = AtMethod;\n fout_ << \"#include \\\"\" << classname_ << \".m\\\"\" << endl;\n }\n }\n else\n break;\n enddir = ppos - 1;\n }\n for (list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n fout_ << \"namespace \" << *it << \"{\" << endl;\n\n found = fnname_.rfind(\"\/\");\n if(found != string::npos)\n fnname_ = fnname_.substr(found+1);\n for( std::string::size_type i = 0; i < fnname_.size(); ++i )\n {\n if(fnname_[i] == '@')\n fnname_[i] = '_';\n else if(fnname_[i] == '.')\n fnname_[i] = '_';\n }\n\n cscan_.execute();\n if(cscan_.vars_.find(string(\"LATEX_OUTPUT\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"LATEX_OUTPUT\")][0] == string(\"true\"))\n {\n runMode_.latex_output = true;\n }\n else\n {\n runMode_.latex_output = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"PRINT_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.print_fields = true;\n }\n else\n {\n runMode_.print_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"COPY_TYPIFIED_FIELD_DOCU\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"COPY_TYPIFIED_FIELD_DOCU\")][0] == string(\"true\"))\n {\n runMode_.copy_typified_field_docu = true;\n }\n else\n {\n runMode_.copy_typified_field_docu = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_FIELDS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_FIELDS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_fields = true;\n }\n else\n {\n runMode_.auto_add_fields = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_PARAMETERS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_PARAMETERS\")][0] == string(\"true\"))\n {\n runMode_.auto_add_params = true;\n }\n else\n {\n runMode_.auto_add_params = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASS_PROPERTIES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASS_PROPERTIES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class_properties = true;\n }\n else\n {\n runMode_.auto_add_class_properties = false;\n }\n }\n if(cscan_.vars_.find(string(\"AUTO_ADD_CLASSES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"AUTO_ADD_CLASSES\")][0] == string(\"true\"))\n {\n runMode_.auto_add_class = true;\n }\n else\n {\n runMode_.auto_add_class = false;\n }\n }\n if(cscan_.vars_.find(string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"REMOVE_FIRST_ARG_IN_ABSTRACT_METHODS\")][0] == string(\"true\"))\n {\n runMode_.remove_first_arg_in_abstract_methods = true;\n }\n else\n {\n runMode_.remove_first_arg_in_abstract_methods = false;\n }\n }\n if(cscan_.vars_.find(string(\"ENABLE_OF_TYPE_PARSING\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"ENABLE_OF_TYPE_PARSING\")][0] == string(\"true\"))\n {\n runMode_.parse_of_type = true;\n }\n else\n {\n runMode_.parse_of_type = false;\n }\n }\n if(cscan_.vars_.find(string(\"VOID_TYPE_IN_RETURN_VALUES\"))!=cscan_.vars_.end())\n {\n if(cscan_.vars_[string(\"VOID_TYPE_IN_RETURN_VALUES\")][0] == string(\"true\"))\n {\n runMode_.void_type_in_return_values = true;\n }\n else\n {\n runMode_.void_type_in_return_values = false;\n }\n }\n if(cscan_.vars_.find(string(\"PRINT_RETURN_VALUE_NAME\"))!=cscan_.vars_.end())\n {\n string tmp = cscan_.vars_[string(\"PRINT_RETURN_VALUE_NAME\")][0];\n if(tmp == string(\"0\"))\n {\n runMode_.print_return_value_name = 0;\n }\n else if(tmp == string(\"1\"))\n {\n runMode_.print_return_value_name = 1;\n }\n else\n {\n runMode_.print_return_value_name = 2;\n }\n }\n};\n\n\/\/ run the scanner\nint MFileScanner :: execute()\n{\n std::ios::sync_with_stdio(false);\n\n %% write init;\n\n \/* Do the first read. *\/\n bool done = false;\n while ( !done )\n {\n char *p = buf + have;\n char *tmp_p = p, *tmp_p2 = p, *tmp_p3 = p;\n string tmp_string;\n bool docline = false;\n bool latex_begin = true;\n bool comment_found = false;\n int space = BUFSIZE - have;\n\n if ( space == 0 )\n {\n \/* We filled up the buffer trying to scan a token. *\/\n cerr << \"MTOCPP: OUT OF BUFFER SPACE\" << endl;\n exit(-1);\n }\n\n fin_.read( p, space );\n int len = fin_.gcount();\n char *pe = p + len;\n char *rpe = pe;\n char *eof = 0;\n\n \/* If we see eof then append the EOF char. *\/\n if ( fin_.eof() )\n {\n char eof_c = *pe;\n *pe = '\\n';\n pe++;\n *pe = eof_c;\n eof = pe;\n rpe = pe;\n\n done = true;\n }\n else\n {\n \/* Find the last newline by searching backwards. This is where\n * we will stop processing on this iteration. *\/\n while ( pe >= p )\n {\n if( *pe != '\\n')\n pe--;\n else\n {\n if(pe >= p+3\n && *(pe-1) == '.' && *(pe-2) == '.' && *(pe-3) == '.')\n pe-=3;\n else\n break;\n }\n }\n }\n\n %% write exec;\n\n \/* Check if we failed. *\/\n if ( cs == MFileScanner_error )\n {\n \/* Machine failed before finding a token. *\/\n cerr << \"MTOCPP:\" << std::string(filename_) << \": PARSE ERROR in line \" << line << endl;\n debug_output(\"Grrrr!!!!\", p);\n exit(-1);\n }\n\n \/* Now set up the prefix. *\/\n if ( ts == 0 )\n {\n have = rpe - pe;\n \/* cerr << \"memmove by \" << have << \"bytes\\n\";*\/\n memmove( buf, pe, have );\n }\n else\n {\n have = rpe - ts;\n \/* cerr << \"memmove by \" << have << \"bytes to ts\\n\";*\/\n memmove( buf, ts, have );\n }\n\n if ( ts != 0 )\n {\n te -= (ts-buf);\n ts = buf;\n }\n }\n\n return 0;\n}\n\n\/\/ escape '@' and '\\' characters in string \\a s\nconst string & MFileScanner::escape_chars(std::string & s)\n{\n string::size_type found = s.find_first_of(\"@\\\\\");\n while(found != string::npos )\n {\n s.insert(found, \"\\\\\");\n found = s.find_first_of(\"@\\\\\",found+2);\n }\n return s;\n}\n\n\/\/ standard brief text (replace '_' -> ' ' in s)\nconst string & MFileScanner::replace_underscore(std::string & s)\n{\n string::size_type found = s.find(\"_\");\n while(found != string::npos )\n {\n s[found] = ' ';\n found = s.find(\"_\", found+1);\n }\n return s;\n}\n\n\/\/ pretty print the documentation block \\a block\nvoid MFileScanner::write_docu_block(const DocuBlock & block_orig)\n{\n\n DocuBlock block = block_orig;\n std::string temp;\n extract_typen(block, temp, true);\n\n bool add_prefix = false;\n bool latex_begin = true;\n bool not_verbatim = true;\n for( unsigned int i = 0; i < block.size(); i += 1 )\n {\n \/\/ begin all documentation lines after the first one with an asterisk (unless in verbatim mode)\n if(add_prefix)\n {\n if(not_verbatim)\n fout_ << \"* \";\n else\n fout_ << \" \";\n }\n\n add_prefix = false;\n \/\/ read in new line of docu block\n const string & s = block[i];\n\n \/\/ parse for special comments\n string::size_type j=0;\n const char * tokens = \"\\'`@\\n\";\n bool last_char_escaped = false;\n for( string::size_type i = 0; j < s.size(); i=j )\n {\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n if(s[j-1] == '\\\\' && not_verbatim && latex_begin)\n --j;\n \/\/ respect @code and @verbatim blocks\n if(s[i] == '@')\n {\n if(s.substr(i+1,4) == \"code\" || s.substr(i+1,8) == \"verbatim\")\n not_verbatim = false;\n else if(s.substr(i+1,7) == \"endcode\" || s.substr(i+1,11) == \"endverbatim\")\n not_verbatim = true;\n fout_ << s.substr(i,j-i);\n }\n \/\/ use typewriter fonts for words in single quotes\n else if(s[i] == '\\'' && not_verbatim && latex_begin)\n {\n if(j != s.size() && s[j] == '\\'' && !last_char_escaped)\n {\n if(j==i+1)\n fout_ << '\\'';\n else\n fout_ << \"\" << s.substr(i+1, j-i-1) << \"<\/tt>\";\n ++j;\n }\n else\n fout_ << s.substr(i,j-i);\n }\n \/\/ use latex output for words in backtick quotes\n else if(s[i] == '`' && not_verbatim)\n {\n string lout;\n if(!last_char_escaped)\n {\n \/\/ in case of double backtick quotes, use latex block\n if(s[i+1] == '`')\n {\n if(latex_begin)\n lout = \"@f[\";\n else\n lout = \"@f]\";\n ++i;\n j=s.find_first_of(tokens,i+1);\n if(j==string::npos)\n j=s.size();\n }\n else\n lout = \"@f$\";\n if(latex_begin)\n latex_begin = false;\n else\n latex_begin = true;\n ++i;\n }\n else\n {\n lout = \"\";\n }\n fout_ << lout << s.substr(i, j-i);\n }\n \/\/ new line\n else if(s[i] == '\\n')\n {\n fout_ << \"\\n \";\n if(latex_begin)\n add_prefix = true;\n else\n {\n fout_ << \" \";\n add_prefix = false;\n }\n }\n else\n {\n fout_ << s.substr(i,j-i);\n }\n if(s[j-1] != '\\\\' && s[j] == '\\\\')\n {\n last_char_escaped = true;\n }\n else\n last_char_escaped = false;\n if(s[j] == '\\\\')\n ++j;\n }\n }\n}\n\n\/\/ pretty print the documentation block list \\a list for the list item named \\a\n\/\/ item_text. If docu blocks are empty, \\a alternative is used. The alternative\n\/\/ is normally read in by the confscanner.\nvoid MFileScanner::write_docu_list(const DocuList & list,\n const string & item_text,\n const AltDocuList & alternative,\n bool add_undocumented = false,\n const string separator = string(),\n const string docu_list_name = string())\n{\n typedef DocuList :: const_iterator list_iterator;\n typedef AltDocuList :: const_iterator alt_list_iterator;\n list_iterator lit = list.begin();\n \/\/ iterate over documentation blocks\n for(; lit != list.end(); ++lit)\n {\n std::string name = (*lit).first;\n if (name.substr(0, 6) == std::string(\"unused\")\n && name.find_first_not_of(\"0123456789\", 7) == std::string::npos)\n continue;\n ostringstream oss;\n oss << \"* \" << item_text << \" \" << name << separator << \" \";\n const DocuBlock & block = (*lit).second;\n\n bool use_alternative = false;\n if(block.size() == 1)\n {\n size_t typeof_length = 0;\n if (block[0].substr(0, 9) == std::string(\" of type \"))\n typeof_length = 9;\n else if (block[0].substr(0, 7) == std::string(\" @type \"))\n typeof_length = 7;\n\n if (typeof_length > 0\n && block[0].find_first_of(\" \", typeof_length) == std::string::npos)\n use_alternative = true;\n }\n\n if(block.empty() || use_alternative)\n {\n \/\/ then look for alternative documentation block from global\n \/\/ configuration file ...\n alt_list_iterator alit = alternative.find((*lit).first);\n if(alit == alternative.end() || (*alit).second.empty())\n {\n string s((*lit).first);\n typedef map< string, string > :: iterator MapIterator;\n MapIterator param_type_map_entry = param_type_map_.end();\n if(!docu_list_name.empty() && runMode_.copy_typified_field_docu)\n {\n param_type_map_entry = param_type_map_.find(docu_list_name);\n }\n\n if(param_type_map_entry != param_type_map_.end())\n {\n \/\/ ... or copy documentation brief text from class documentation ...\n string temp = s.substr(0, s.find_first_of(\".\"));\n fout_ << oss.str() << \"@copybrief \" << (*param_type_map_entry).second << \"::\" << temp << \"\\n \";\n }\n else\n {\n if (add_undocumented)\n {\n \/\/ ... or use default text generated from variable name.\n fout_ << oss.str() << replace_underscore(s) << \"\\n \";\n }\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block((*alit).second);\n }\n }\n else\n {\n fout_ << oss.str();\n write_docu_block(block);\n }\n }\n}\n\n\/\/ pretty print a documentation block list map \\a listmap with prepended title\n\/\/ \\a text. If listmap entry is empty, \\a altlistmap is used instead.\nvoid MFileScanner::write_docu_listmap(const DocuListMap & listmap,\n const string & text,\n const AltDocuListMap & altlistmap)\n{\n typedef DocuListMap :: const_iterator map_iterator;\n typedef AltDocuListMap :: const_iterator alt_map_iterator;\n if(!listmap.empty())\n {\n map_iterator mit = listmap.begin();\n for(; mit != listmap.end(); ++mit)\n {\n fout_ << \"*\\n \";\n fout_ << \"* \" << text << (*mit).first << \":\\n \";\n alt_map_iterator amit = altlistmap.find((*mit).first);\n write_docu_list((*mit).second,\n \"@arg \\\\c\",\n ( amit != altlistmap.end() ? (*amit).second : AltDocuList() ),\n runMode_.auto_add_fields,\n \" — \",\n (*mit).first );\n }\n\/\/ fout_ << \"* <\/TABLE>\\n \";\n\n }\n}\n\nstring MFileScanner::namespace_string()\n{\n ostringstream oss;\n oss << \"\";\n for( list::iterator it = namespaces_.begin();\n it != namespaces_.end(); ++it)\n {\n oss << *it << \"::\";\n }\n return oss.str();\n}\n\nvoid MFileScanner::end_of_class_doc()\n{\n if (!docuheader_.empty() || runMode_.auto_add_class)\n {\n fout_ << \"\/** @class \\\"\" << namespace_string() << classname_ << \"\\\"\\n \";\n\n cout_ingroup();\n\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n}\n\n\nvoid MFileScanner::end_of_property_doc()\n{\n add_property_params_info();\n typedef DocuBlock :: iterator DBIt;\n string typen;\n extract_typen(docuheader_, typen);\n if(typen.empty())\n extract_typen(docubody_, typen);\n\n string defval;\n extract_default(docubody_, defval);\n\n if(typen.empty())\n typen = \"matlabtypesubstitute\";\n\n fout_ << propertyparams_.ccprefix() << typen << \" \" << property_list_.back();\n if(defaultprop_.empty())\n fout_ << \";\\n\";\n else\n fout_ << \" = \" << defaultprop_ << \";\\n\";\n\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n fout_ << \"\/** @var \" << property_list_.back() << \"\\n \";\n fout_ << \"* @brief \";\n cout_docuheader(property_list_.back());\n fout_ << \"*\\n \";\n cout_docubody();\n fout_ << \"*\\n \";\n cout_docuextra();\n fout_ << \"*\/\\n\";\n }\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::cout_docuheader(string altheader, bool clear)\n{\n if(docuheader_.empty() && cscan_.docuheader_.empty())\n {\n fout_ << replace_underscore(altheader) << \"\\n \";\n }\n else\n {\n if(! docuheader_.empty())\n {\n write_docu_block(docuheader_);\n }\n if(! cscan_.docuheader_.empty())\n {\n write_docu_block(cscan_.docuheader_);\n }\n }\n if(clear)\n docuheader_.clear();\n}\n\nvoid MFileScanner :: cout_docubody()\n{\n if(!docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docubody_);\n }\n docubody_.clear();\n if(!cscan_.docubody_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docubody_);\n }\n}\n\nvoid MFileScanner :: cout_docuextra()\n{\n if(! cscan_.docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(cscan_.docuextra_);\n }\n if(! docuextra_.empty())\n {\n fout_ << \"*\\n * \";\n write_docu_block(docuextra_);\n }\n docuextra_.clear();\n}\n\nvoid MFileScanner :: cout_ingroup()\n{\n typedef GroupSet :: iterator group_iterator;\n \/\/ add @ingroup commands from the configuration file\n if((! groupset_.empty() || ! cscan_.groupset_.empty() ))\n {\n fout_ << \"* @ingroup \";\n bool not_first = false;\n group_iterator git = cscan_.groupset_.begin();\n for(; git != cscan_.groupset_.end(); ++git)\n {\n if(not_first)\n fout_ << \" \";\n else\n not_first = true;\n\n fout_ << *git;\n }\n groupset_.clear();\n fout_ << \"\\n \";\n }\n}\n\nvoid MFileScanner::clear_lists()\n{\n#ifdef DEBUG\n std::cerr << \"clear lists\" << endl;\n#endif\n paramlist_.clear();\n \/* param_defaults_.clear(); *\/\n returnlist_.clear();\n param_list_.clear();\n return_list_.clear();\n required_list_.clear();\n optional_list_.clear();\n retval_list_.clear();\n param_type_map_.clear();\n}\n\n\/* we come here, from an empty line in a methods block or the end of a\n * methods block\n *\/\nvoid MFileScanner::end_method()\n{\n if (!cfuncname_.empty())\n {\n\n if(runMode_.mode != RunMode::ParseMethodParams\n && docuheader_.empty()\n && !methodparams_.abstr)\n {\n istream *fcin;\n ifstream fin;\n try\n {\n std::string filename(dirname_ + \"\/\" + cfuncname_ + \".m\");\n std::ios_base::iostate oldstate = fin.exceptions();\n fin.exceptions ( ifstream::failbit | ifstream::badbit );\n fin.open(filename.c_str());\n fin.exceptions(oldstate);\n fcin = &fin;\n ostringstream oss;\n RunMode paramsMode = runMode_;\n paramsMode.mode = RunMode::ParseParams;\n MFileScanner scanner(*fcin, oss, filename, cscan_.get_conffile(), paramsMode);\n scanner.execute();\n param_list_ = scanner.getParamList();\n }\n catch (ifstream::failure e)\n {\n std::cerr << \"MTOCPP Warning: No definition for function \" << cfuncname_\n << \" found in class \" << classname_ << \"!\\n\";\n }\n }\n\n class_part_ = MethodDeclaration;\n print_function_synopsis();\n class_part_ = Method;\n\n \/\/ for abstract methods: print out documentation of the abstract method\n \/\/ declaration\n if(methodparams_.abstr)\n end_function();\n else\n \/\/ otherwise: all the following comments are not related to this function\n \/\/ anymore, so we delete traces of the method name...\n {\n cfuncname_.clear();\n clear_lists();\n }\n }\n \/\/ free documentation block variables\n docuheader_.clear();\n docubody_.clear();\n docuextra_.clear();\n}\n\nvoid MFileScanner::extract_default(DocuBlock & db, std::string & defvalue)\n{\n typedef DocuBlock :: iterator DBIt;\n\n for(DBIt dit = db.begin(); dit != db.end(); ++dit)\n {\n std::string & line = *dit;\n size_t found = std::string::npos;\n size_t deflength = std::string(\"(default\").length();\n found = line.find(\"(default\");\n if(found != std::string::npos)\n {\n size_t tmp;\n if(line[found+1] == '=')\n tmp = found + deflength + 1;\n else if (line[found+2] == '=')\n tmp = found + deflength + 2;\n else\n found = std::string::npos;\n\n if (found != std::string::npos)\n {\n defvalue = line.substr(tmp+1);\n defvalue = defvalue.substr(0, defvalue.length() - 1);\n }\n }\n if(found == std::string::npos)\n {\n deflength = string(\"@default \").length();\n found = line.find(\"@default \");\n if (found != std::string::npos)\n {\n size_t end = line.find(\"@\", found+1);\n if (end == std::string::npos)\n end = line.find(\"of type\");\n if (end == std::string::npos)\n end = line.length();\n end = end - 1;\n size_t start = found + deflength + 1;\n defvalue = line.substr(start, end - start);\n line[found] = '(';\n line[found+8] = '=';\n line = line.substr(0, found) + \"( @b default = \"\n + line.substr(found+9,end-found-9) + \" )\" + line.substr(end);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n }\n }\n}\n\nvoid MFileScanner::get_default(const std::string & paramname, std::string & defvalue)\n{\n typedef DocuList :: iterator DLIt;\n DLIt it = param_list_.find(paramname);\n if(it != param_list_.end() && !(it->second).empty())\n {\n DocuBlock & db = it->second;\n extract_default(db, defvalue);\n }\n else\n {\n defvalue = std::string(\"\");\n }\n}\n\nvoid MFileScanner::get_typename(const std::string & paramname, std::string & typen, std::string voidtype)\n{\n typedef DocuList :: iterator DLIt;\n typedef AltDocuList :: iterator ADLIt;\n typedef DocuBlock :: iterator DBIt;\n DLIt it = param_list_.find(paramname);\n DocuBlock * pdb;\n if(it != param_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n it = return_list_.find(paramname);\n if(it != return_list_.end() && !(it->second).empty())\n pdb = &(it->second);\n else\n {\n ADLIt ait = cscan_.param_list_.find(paramname);\n if(ait != cscan_.param_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n ait = cscan_.return_list_.find(paramname);\n if(ait != cscan_.return_list_.end() && !(ait->second).empty())\n pdb = &(ait->second);\n else\n {\n typen=voidtype;\n return;\n }\n }\n }\n }\n\n DocuBlock & db = *pdb;\n extract_typen(db, typen);\n\n if(typen.empty())\n typen = voidtype;\n else\n param_type_map_[paramname] = typen;\n}\n\n\/\/ ATTENTION: The get_typename method changes the docublock and removes the\n\/\/ \"@type \" respectively \"of type\" strings if remove is set to true.\nvoid MFileScanner::extract_typen(DocuBlock & db, std::string & typen, bool remove)\n{\n int linenr = 1;\n typedef DocuBlock :: iterator DBIt;\n for(DBIt dit = db.begin(); dit != db.end(); ++dit, ++linenr)\n {\n std::string line = *dit;\n size_t found = std::string::npos;\n size_t typeof_length = 0; \/\/ length of string \"of type\" respectively \"@type\"\n if(runMode_.parse_of_type && linenr < 2)\n {\n found = line.find(\"of type\");\n typeof_length = string(\"of type\").length();\n }\n if(found == std::string::npos)\n {\n found = line.find(\"@type\");\n typeof_length = string(\"@type\").length();\n }\n if(found != std::string::npos)\n {\n size_t typenstart = found + typeof_length;\n \/\/ find start of type name\n typenstart=line.find_first_not_of( \" \\t\\n\\0\", typenstart );\n if (typenstart == std::string::npos)\n {\n \/\/ read in next line\n if (remove)\n (*dit).erase(found, line.length() - found - 1);\n\n ++dit;\n if (dit == db.end())\n break;\n line = *dit;\n found = 0;\n typenstart = line.find_first_not_of( \" \\t\");\n }\n \/\/ find end of type name\n size_t typenend =\n line.find_first_of( \" \\n\\0\", typenstart );\n typen = line.substr(typenstart, typenend - typenstart);\n \/\/ remove trailing '.' if necessary\n if (typen[typen.length()-1] == '.')\n {\n typen = typen.substr(0, typen.length() - 1);\n }\n \/\/ add leading '::' just to make sure, we only have global scope variables.\n if(typen[0] != ':')\n {\n for(size_t i=0; i < typen.length(); ++i)\n if(typen.at(i) == '.')\n typen.replace(i,1,std::string(\"::\"));\n typen = string(\"::\") + typen;\n\n\/\/ (*dit).replace(typenstart, typenend - typenstart, typen);\n }\n if (remove)\n {\n (*dit).erase(found, typenend - found);\n }\n }\n }\n}\n\nvoid MFileScanner::add_access_info(std::string what)\n{\n if (access_.get != access_.set)\n {\n docuextra_.push_back(std::string(\"@note This \") + what + std::string(\" has non-unique access specifier: \"));\n std::string setAccess = access_specifier_string(access_.set);\n std::string getAccess = access_specifier_string(access_.get);\n docuextra_.push_back(std::string(\"SetAccess = \") + setAccess + \", \"\n + std::string(\"GetAccess = \") + getAccess + std::string(\"\\n\"));\n }\n}\n\nvoid MFileScanner::add_property_params_info()\n{\n if (propertyparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Hidden' set to true.\\n\"));\n }\n if (propertyparams_.transient)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Transient' set to true.\\n\"));\n }\n if (propertyparams_.dependent)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'Dependent' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property has the MATLAB parameter 'SetObservable' set to true.\\n\"));\n }\n if (propertyparams_.setObservable)\n {\n docuextra_.push_back(std::string(\"@note This property is an @em abstract property without implementation.\\n\"));\n }\n\n add_access_info(\"property\");\n}\n\nvoid MFileScanner::add_method_params_info()\n{\n if (methodparams_.hidden)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Hidden' set to true.\\n\"));\n }\n if (methodparams_.sealed)\n {\n docuextra_.push_back(std::string(\"@note This method has the MATLAB method property 'Sealed' set to true. It cannot be overwritten.\\n\"));\n }\n add_access_info(\"method\");\n}\n\n\/\/ end a function and pretty print the documentation for this function\nvoid MFileScanner::end_function()\n{\n bool is_constructor = false;\n bool is_method = false;\n bool skip_parameters = false;\n \/* If copydoc or copydetails is used in the documentation body or the\n * documentation header, the automatic parameter doc strings need to be\n * skipped. *\/\n if (! docuheader_.empty()\n && docuheader_[0].find(\"copydoc\") != std::string::npos)\n {\n skip_parameters = true;\n }\n if (! docubody_.empty())\n {\n for (unsigned int i = 0; i < docubody_.size(); ++i)\n {\n size_t pos_begin_copy = docubody_[i].find(\"copydoc\");\n if(pos_begin_copy == std::string::npos)\n {\n pos_begin_copy = docubody_[i].find(\"copydetails\");\n }\n if(pos_begin_copy != std::string::npos)\n {\n size_t pos_word_begin = docubody_[i].find_first_of(\" \\n\", pos_begin_copy + 1);\n pos_word_begin = docubody_[i].find_first_not_of(\" \\n\", pos_word_begin);\n if(pos_word_begin != std::string::npos)\n {\n size_t pos_word_end = docubody_[i].find_first_of(\"(\", pos_word_begin);\n if(pos_word_end != std::string::npos)\n {\n std::string func = docubody_[i].substr(pos_word_begin, pos_word_end-pos_word_begin);\n size_t pos_func_beg = func.find_last_of(\":. \");\n func = func.substr(pos_func_beg+1);\n if(func == cfuncname_)\n {\n skip_parameters = true;\n }\n }\n }\n }\n }\n }\n if(is_class_)\n {\n if(class_part_ == Property)\n return;\n\n add_method_params_info();\n\n if(cfuncname_ == classname_)\n is_constructor = true;\n if(class_part_ == Method)\n is_method = true;\n }\n \/\/ end function\n if(!is_method || !methodparams_.abstr)\n fout_ << \"}\\n\";\n if(is_getter_ || is_setter_)\n fout_ << \"*\/\\n\";\n if (!docuheader_.empty() || runMode_.auto_add_class_properties)\n {\n \/\/ is the first function?\n if(is_first_function_)\n {\n if(! runMode_.latex_output && ! is_class_)\n {\n \/\/ Then make a file documentation block\n fout_ << \"\/** @file \\\"\" << filename_ << \"\\\"\\n \";\n cout_ingroup();\n fout_ << \"* @brief \";\n cout_docuheader(cfuncname_, false);\n fout_ << \"*\/\\n\";\n }\n }\n fout_ << \"\/*\";\n if(runMode_.latex_output && !is_class_)\n {\n cout_ingroup();\n fout_ << \"\\n \";\n }\n if(is_setter_ || is_getter_)\n {\n fout_ << \"* @var \" << cfuncname_ << \"\\n \";\n string temp = (is_setter_ ? \"Setter\" : \"Getter\");\n fout_ << \"* @par \" << temp << \" is implemented\\n *\";\n }\n else\n {\n \/\/ specify the @fn part\n fout_ << \"* @fn \";\n print_pure_function_synopsis();\n\n \/\/ specify the @brief part\n fout_ << \"\\n * @brief \";\n }\n cout_docuheader(cfuncname_);\n fout_ << \"*\\n \";\n\n \/\/ specify the @details part\n\n \/\/ standard body definitions\n cout_docubody();\n\n if (! skip_parameters)\n {\n \/\/ parameters\n if(!param_list_.empty() && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(param_list_, \"@param\", cscan_.param_list_,\n runMode_.auto_add_params);\n }\n\n \/\/ return values\n if(!return_list_.empty() && !is_constructor && !is_getter_ && !is_setter_)\n {\n fout_ << \"*\\n \";\n write_docu_list(return_list_, \"@retval\", cscan_.return_list_,\n runMode_.auto_add_params);\n }\n\n if(runMode_.print_fields)\n {\n \/\/ required fields\n write_docu_listmap(required_list_, \"@par Required fields of \", cscan_.field_docu_);\n\n \/\/ optional fields\n write_docu_listmap(optional_list_, \"@par Optional fields of \", cscan_.field_docu_);\n\n \/\/ return fields\n write_docu_listmap(retval_list_, \"@par Generated fields of \", cscan_.field_docu_);\n }\n }\n #ifdef DEBUG\n std::cerr << \"CLEARING LISTS!\";\n #endif\n clear_lists();\n\n \/\/ extra docu fields\n cout_docuextra();\n if( new_syntax_ )\n {\n fout_ << \"* @synupdate Syntax needs to be updated! \\n \";\n }\n fout_ << \"*\/\\n\";\n }\n else\n {\n clear_lists();\n }\n if(!is_method)\n is_first_function_ = false;\n\n is_setter_ = false; is_getter_ = false;\n cfuncname_.clear();\n}\n\nvoid MFileScanner::debug_output(const std::string & msg, char * p)\n{\n std::cerr << \"Message: \" << msg << \"\\n\";\n std::cerr << \"Next 20 characters to parse: \\n\";\n std::cerr.write(p, 20);\n std::cerr << \"\\n------------------------------------\\n\";\n std::cerr << \"States are: ClassPart: \" << ClassPartNames[class_part_] << \"\\n\"\n << propertyparams_ << methodparams_ << access_;\n std::cerr << \"\\n------------------------------------\\n\";\n}\n\nvoid MFileScanner::postprocess_unused_params(std::string & param, DocuList & doculist)\n{\n if (param == std::string(\"~\"))\n {\n int counter = 1;\n bool found = true;\n while ( found )\n {\n std::ostringstream oss;\n oss << \"unused\" << counter;\n if (doculist.find(oss.str()) == doculist.end())\n {\n param = oss.str();\n found = false;\n }\n ++counter;\n }\n }\n}\n\n\nstd::ostream & operator<<(std::ostream & os, AccessStruct & as)\n{\n os << \"AccessStruct: full = \" << AccessEnumNames[as.full] << \" get = \" <<\n AccessEnumNames[as.get] << \" set = \" << AccessEnumNames[as.set] << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, PropParams & pp)\n{\n os << \"PropParams: constant = \" << pp.constant << \"\\n\";\n return os;\n}\n\nstd::ostream & operator<<(std::ostream & os, MethodParams & mp)\n{\n std::string abstract = mp.abstr ? \"abstract, \" : \"\";\n std::string statics = mp.statical ? \"static, \" : \"\";\n os << \"MethodParams: \" << abstract << statics << \"\\n\";\n return os;\n}\n\n\/* vim: set et sw=2 ft=ragel foldmethod=marker: *\/\n\n","returncode":0,"stderr":"","license":"bsd-2-clause","lang":"Ragel in Ruby Host"} {"commit":"28ba6ef0f9f068f5eaeb82080fb3f04d34a1e48b","subject":"http: add status to http_response","message":"http: add status to http_response\n\nOur HTTP response parser chooses to ignore the status code\nand not keep it anywhere. It's quite useful to be able to\ninspect the received status code, so this value is now kept\nin the http_response structure.\n","repos":"syuu1228\/seastar,avikivity\/seastar,syuu1228\/seastar,avikivity\/seastar,syuu1228\/seastar,scylladb\/seastar,avikivity\/seastar,scylladb\/seastar,scylladb\/seastar","old_file":"src\/http\/response_parser.rl","new_file":"src\/http\/response_parser.rl","new_contents":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \n#include \n\nnamespace seastar {\n\nstruct http_response {\n sstring _version;\n std::unordered_map _headers;\n int _status_code;\n};\n\n%% machine http_response;\n\n%%{\n\naccess _fsm_;\n\naction mark {\n g.mark_start(p);\n}\n\naction store_version {\n _rsp->_version = str();\n}\n\naction store_field_name {\n _field_name = str();\n}\n\naction store_value {\n _value = str();\n}\n\naction assign_field {\n _rsp->_headers[_field_name] = std::move(_value);\n}\n\naction extend_field {\n _rsp->_headers[_field_name] += sstring(\" \") + std::move(_value);\n}\n\naction store_status {\n _rsp->_status_code = std::atoi(str().c_str());\n}\n\naction done {\n done = true;\n fbreak;\n}\n\ncr = '\\r';\nlf = '\\n';\ncrlf = '\\r\\n';\ntchar = alpha | digit | '-' | '!' | '#' | '$' | '%' | '&' | '\\'' | '*'\n | '+' | '.' | '^' | '_' | '`' | '|' | '~';\n\nsp = ' ';\nht = '\\t';\n\nsp_ht = sp | ht;\n\nhttp_version = 'HTTP\/' (digit '.' digit) >mark %store_version;\n\nfield = tchar+ >mark %store_field_name;\nvalue = any* >mark %store_value;\nstatus_code = (digit digit digit) >mark %store_status;\nstart_line = http_version space status_code space (any - cr - lf)* crlf;\nheader_1st = (field sp_ht* ':' value :> crlf) %assign_field;\nheader_cont = (sp_ht+ value sp_ht* crlf) %extend_field;\nheader = header_1st header_cont*;\nmain := start_line header* :> (crlf @done);\n\n}%%\n\nclass http_response_parser : public ragel_parser_base {\n %% write data nofinal noprefix;\npublic:\n enum class state {\n error,\n eof,\n done,\n };\n std::unique_ptr _rsp;\n sstring _field_name;\n sstring _value;\n state _state;\npublic:\n void init() {\n init_base();\n _rsp.reset(new http_response());\n _state = state::eof;\n %% write init;\n }\n char* parse(char* p, char* pe, char* eof) {\n sstring_builder::guard g(_builder, p, pe);\n auto str = [this, &g, &p] { g.mark_end(p); return get_str(); };\n bool done = false;\n if (p != pe) {\n _state = state::error;\n }\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wmisleading-indentation\"\n#endif\n %% write exec;\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n if (!done) {\n p = nullptr;\n } else {\n _state = state::done;\n }\n return p;\n }\n auto get_parsed_response() {\n return std::move(_rsp);\n }\n bool eof() const {\n return _state == state::eof;\n }\n};\n\n}\n","old_contents":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \n#include \n\nnamespace seastar {\n\nstruct http_response {\n sstring _version;\n std::unordered_map _headers;\n};\n\n%% machine http_response;\n\n%%{\n\naccess _fsm_;\n\naction mark {\n g.mark_start(p);\n}\n\naction store_version {\n _rsp->_version = str();\n}\n\naction store_field_name {\n _field_name = str();\n}\n\naction store_value {\n _value = str();\n}\n\naction assign_field {\n _rsp->_headers[_field_name] = std::move(_value);\n}\n\naction extend_field {\n _rsp->_headers[_field_name] += sstring(\" \") + std::move(_value);\n}\n\naction done {\n done = true;\n fbreak;\n}\n\ncr = '\\r';\nlf = '\\n';\ncrlf = '\\r\\n';\ntchar = alpha | digit | '-' | '!' | '#' | '$' | '%' | '&' | '\\'' | '*'\n | '+' | '.' | '^' | '_' | '`' | '|' | '~';\n\nsp = ' ';\nht = '\\t';\n\nsp_ht = sp | ht;\n\nhttp_version = 'HTTP\/' (digit '.' digit) >mark %store_version;\n\nfield = tchar+ >mark %store_field_name;\nvalue = any* >mark %store_value;\nstart_line = http_version space digit digit digit space (any - cr - lf)* crlf;\nheader_1st = (field sp_ht* ':' value :> crlf) %assign_field;\nheader_cont = (sp_ht+ value sp_ht* crlf) %extend_field;\nheader = header_1st header_cont*;\nmain := start_line header* :> (crlf @done);\n\n}%%\n\nclass http_response_parser : public ragel_parser_base {\n %% write data nofinal noprefix;\npublic:\n enum class state {\n error,\n eof,\n done,\n };\n std::unique_ptr _rsp;\n sstring _field_name;\n sstring _value;\n state _state;\npublic:\n void init() {\n init_base();\n _rsp.reset(new http_response());\n _state = state::eof;\n %% write init;\n }\n char* parse(char* p, char* pe, char* eof) {\n sstring_builder::guard g(_builder, p, pe);\n auto str = [this, &g, &p] { g.mark_end(p); return get_str(); };\n bool done = false;\n if (p != pe) {\n _state = state::error;\n }\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wmisleading-indentation\"\n#endif\n %% write exec;\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n if (!done) {\n p = nullptr;\n } else {\n _state = state::done;\n }\n return p;\n }\n auto get_parsed_response() {\n return std::move(_rsp);\n }\n bool eof() const {\n return _state == state::eof;\n }\n};\n\n}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Ragel in Ruby Host"} {"commit":"ded3eb15b8ed4dc42c780ac5e047edcf91fcf61d","subject":"Fixed octal sequence definition","message":"Fixed octal sequence definition\n","repos":"gjtorikian\/regexp_parser,ammar\/regexp_parser,ammar\/regexp_parser,jhart-r7\/regexp_parser","old_file":"lib\/regexp_parser\/scanner.rl","new_file":"lib\/regexp_parser\/scanner.rl","new_contents":"%%{\n machine re_scanner;\n\n wild = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n posix_class_name = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n property_name = 'Alnum' | 'Alpha' | 'Any' | 'Ascii' | 'Blank' |\n 'Cntrl' | 'Digit' | 'Graph' | 'Lower' | 'Print' |\n 'Punct' | 'Space' | 'Upper' | 'Word' | 'Xdigit';\n\n category_letter = 'L' . [ultmo]?;\n category_mark = 'M' . [nce]?;\n category_number = 'N' . [dlo]?;\n category_punctuation = 'P' . [cdseifo]?;\n category_symbol = 'S' . [mcko]?;\n category_separator = 'Z' . [slp]?;\n category_codepoint = 'C' . [cfson]?;\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n posix_class = '[:' . posix_class_name . ':]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n property_char = [pP];\n\n escaped_char = [aefnrtv];\n octal_sequence = [0-7]{3};\n\n hex_sequence = 'x' . xdigit{2};\n wide_hex_sequence = 'x' . '{7' . xdigit{1,7} . '}';\n\n control_sequence = ('c' | 'C-') . xdigit{1,2};\n meta_sequence = 'M-' . xdigit{1,2};\n meta_control_sequence = 'M-\\\\C-' . xdigit{1,2};\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_range = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_range;\n\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | ('?\\'' . group_name . '\\'');\n\n group_type = group_atomic | group_passive | group_named;\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = wild | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n self.emit(:set, :close, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n '^' {\n self.emit(:set, :negate, data[ts..te-1].pack('c*'), ts, te)\n };\n\n alnum . '-' . alnum { # TODO: add properties\n self.emit(:set, :range, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '&&' {\n self.emit(:set, :intersection, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n posix_class {\n case text = data[ts..te-1].pack('c*')\n when '[:alnum:]'; self.emit(:set, :class_alnum, text, ts, te)\n when '[:alpha:]'; self.emit(:set, :class_alpha, text, ts, te)\n when '[:blank:]'; self.emit(:set, :class_blank, text, ts, te)\n when '[:cntrl:]'; self.emit(:set, :class_cntrl, text, ts, te)\n when '[:digit:]'; self.emit(:set, :class_digit, text, ts, te)\n when '[:graph:]'; self.emit(:set, :class_graph, text, ts, te)\n when '[:lower:]'; self.emit(:set, :class_lower, text, ts, te)\n when '[:print:]'; self.emit(:set, :class_print, text, ts, te)\n when '[:punct:]'; self.emit(:set, :class_punct, text, ts, te)\n when '[:space:]'; self.emit(:set, :class_space, text, ts, te)\n when '[:upper:]'; self.emit(:set, :class_upper, text, ts, te)\n when '[:xdigit:]'; self.emit(:set, :class_xdigit, text, ts, te)\n when '[:word:]'; self.emit(:set, :class_word, text, ts, te)\n when '[:ascii:]'; self.emit(:set, :class_ascii, text, ts, te)\n else raise \"Unsupported character posixe class at #{text} (char #{ts})\"\n end\n };\n\n any {\n self.emit(:set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' {\n self.emit(:set, :backspace, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [\\\\\\]\\-\\,] {\n self.emit(:set, :escape, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [dDhHsSwW] {\n case text = data[ts-1..te-1].pack('c*')\n when '\\d'; self.emit(:set, :type_digit, text, ts-1, te)\n when '\\D'; self.emit(:set, :type_nondigit, text, ts-1, te)\n when '\\h'; self.emit(:set, :type_hex, text, ts-1, te)\n when '\\H'; self.emit(:set, :type_nonhex, text, ts-1, te)\n when '\\s'; self.emit(:set, :type_space, text, ts-1, te)\n when '\\S'; self.emit(:set, :type_nonspace, text, ts-1, te)\n when '\\w'; self.emit(:set, :type_word, text, ts-1, te)\n when '\\W'; self.emit(:set, :type_nonword, text, ts-1, te)\n end\n\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n self.emit(:set, :range_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n hex_sequence {\n self.emit(:set, :member_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n hex_sequence {\n self.emit(:escape, :hex, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n wide_hex_sequence {\n self.emit(:escape, :hex_wide, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n control_sequence {\n self.emit(:escape, :control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_sequence {\n self.emit(:escape, :meta, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_control_sequence {\n self.emit(:escape, :meta_control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n # TODO: extract into a separate machine... use in sets\n property_char . '{' . (property_name | general_category) . '}' > (escaped_alpha, 2) {\n text = data[ts..te-1].pack('c*')\n type = text[0,1] == 'p' ? :property: :inverted_property\n\n case name = data[ts+2..te-2].pack('c*')\n\n # Named\n when 'Alnum'; self.emit(type, :alnum, text, ts, te)\n when 'Alpha'; self.emit(type, :alpha, text, ts, te)\n when 'Any'; self.emit(type, :any, text, ts, te)\n when 'Ascii'; self.emit(type, :ascii, text, ts, te)\n when 'Blank'; self.emit(type, :blank, text, ts, te)\n when 'Cntrl'; self.emit(type, :cntrl, text, ts, te)\n when 'Digit'; self.emit(type, :digit, text, ts, te)\n when 'Graph'; self.emit(type, :graph, text, ts, te)\n when 'Lower'; self.emit(type, :lower, text, ts, te)\n when 'Print'; self.emit(type, :print, text, ts, te)\n when 'Punct'; self.emit(type, :punct, text, ts, te)\n when 'Space'; self.emit(type, :space, text, ts, te)\n when 'Upper'; self.emit(type, :upper, text, ts, te)\n when 'Word'; self.emit(type, :word, text, ts, te)\n when 'Xdigit'; self.emit(type, :xdigit, text, ts, te)\n\n # Letters\n when 'L'; self.emit(type, :letter_any, text, ts, te)\n when 'Lu'; self.emit(type, :letter_uppercase, text, ts, te)\n when 'Ll'; self.emit(type, :letter_lowercase, text, ts, te)\n when 'Lt'; self.emit(type, :letter_titlecase, text, ts, te)\n when 'Lm'; self.emit(type, :letter_modifier, text, ts, te)\n when 'Lo'; self.emit(type, :letter_other, text, ts, te)\n\n # Marks\n when 'M'; self.emit(type, :mark_any, text, ts, te)\n when 'Mn'; self.emit(type, :mark_nonspacing, text, ts, te)\n when 'Mc'; self.emit(type, :mark_spacing, text, ts, te)\n when 'Me'; self.emit(type, :mark_enclosing, text, ts, te)\n\n # Numbers\n when 'N'; self.emit(type, :number_any, text, ts, te)\n when 'Nd'; self.emit(type, :number_decimal, text, ts, te)\n when 'Nl'; self.emit(type, :number_letter, text, ts, te)\n when 'No'; self.emit(type, :number_other, text, ts, te)\n\n # Punctuation\n when 'P'; self.emit(type, :punct_any, text, ts, te)\n when 'Pc'; self.emit(type, :punct_connector, text, ts, te)\n when 'Pd'; self.emit(type, :punct_dash, text, ts, te)\n when 'Ps'; self.emit(type, :punct_open, text, ts, te)\n when 'Pe'; self.emit(type, :punct_close, text, ts, te)\n when 'Pi'; self.emit(type, :punct_initial, text, ts, te)\n when 'Pf'; self.emit(type, :punct_final, text, ts, te)\n when 'Po'; self.emit(type, :punct_other, text, ts, te)\n\n # Symbols\n when 'S'; self.emit(type, :symbol_any, text, ts, te)\n when 'Sm'; self.emit(type, :symbol_math, text, ts, te)\n when 'Sc'; self.emit(type, :symbol_currency, text, ts, te)\n when 'Sk'; self.emit(type, :symbol_modifier, text, ts, te)\n when 'So'; self.emit(type, :symbol_other, text, ts, te)\n\n # Separators\n when 'Z'; self.emit(type, :separator_any, text, ts, te)\n when 'Zs'; self.emit(type, :separator_space, text, ts, te)\n when 'Zl'; self.emit(type, :separator_line, text, ts, te)\n when 'Zp'; self.emit(type, :separator_paragraph, text, ts, te)\n\n # Codepoints\n when 'C'; self.emit(type, :code_any, text, ts, te)\n when 'Cc'; self.emit(type, :code_control, text, ts, te)\n when 'Cf'; self.emit(type, :code_format, text, ts, te)\n when 'Cs'; self.emit(type, :code_surrogate, text, ts, te)\n when 'Co'; self.emit(type, :code_private, text, ts, te)\n when 'Cn'; self.emit(type, :code_unassigned, text, ts, te)\n end\n };\n\n any > (escaped_alpha, 1) {\n self.emit(:escape, :literal, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n alternation {\n self.emit(:meta, :alternation, data[ts..te-1].pack('c*'), ts, te)\n };\n\n wild {\n self.emit(:meta, :wild, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S whitespace, non-whitespace\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\d'; self.emit(:type, :digit, text, ts, te)\n when '\\\\D'; self.emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; self.emit(:type, :hex, text, ts, te)\n when '\\\\H'; self.emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; self.emit(:type, :space, text, ts, te)\n when '\\\\S'; self.emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; self.emit(:type, :word, text, ts, te)\n when '\\\\W'; self.emit(:type, :nonword, text, ts, te)\n end\n };\n\n # Anchors\n beginning_of_line {\n self.emit(:anchor, :beginning_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n end_of_line {\n self.emit(:anchor, :end_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\A'; self.emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; self.emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; self.emit(:anchor, :eos_or_before_eol, text, ts, te)\n when '\\\\b'; self.emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; self.emit(:anchor, :nonword_boundary, text, ts, te)\n else raise \"Unsupported anchor at #{text} (char #{ts})\"\n end\n };\n\n # Escaped sequences\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Character sets\n set_open {\n self.emit(:set, :open, data[ts..te-1].pack('c*'), ts, te)\n fcall character_set;\n };\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n group_open . group_comment {\n self.emit(:group, :comment, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # (?mix-mix...) expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n group_open . group_options {\n self.emit(:group, :options, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group (single quotes are no supported, yet)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type {\n case text = data[ts..te-1].pack('c*')\n when '(?:'; self.emit(:group, :passive, text, ts, te)\n when '(?>'; self.emit(:group, :atomic, text, ts, te)\n when \/\\(\\?<\\w+>\/\n self.emit(:group, :named, text, ts, te)\n end\n };\n\n group_open {\n text = data[ts..te-1].pack('c*')\n self.emit(:group, :capture, text, ts, te)\n };\n\n group_close {\n self.emit(:group, :close, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = data[ts..te-1].pack('c*')\n when '?' ; self.emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; self.emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; self.emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n \n zero_or_more {\n case text = data[ts..te-1].pack('c*')\n when '*' ; self.emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; self.emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; self.emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n \n one_or_more {\n case text = data[ts..te-1].pack('c*')\n when '+' ; self.emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; self.emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; self.emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n\n # Intervals: min, max, and exact notations\n # ------------------------------------------------------------------------\n range_open . (digit+)? . ','? . (digit+)? . range_close . quantifier_mode? {\n self.emit(:quantifier, :interval, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Literal: anything, except meta characters. This includes 2, 3, and 4\n # unicode byte sequences.\n # ------------------------------------------------------------------------\n (any - meta_char)+ {\n self.emit(:literal, :literal, data[ts..te-1].pack('c*'), ts, te)\n };\n\n *|;\n}%%\n","old_contents":"%%{\n machine re_scanner;\n\n wild = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n posix_class_name = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n property_name = 'Alnum' | 'Alpha' | 'Any' | 'Ascii' | 'Blank' |\n 'Cntrl' | 'Digit' | 'Graph' | 'Lower' | 'Print' |\n 'Punct' | 'Space' | 'Upper' | 'Word' | 'Xdigit';\n\n category_letter = 'L' . [ultmo]?;\n category_mark = 'M' . [nce]?;\n category_number = 'N' . [dlo]?;\n category_punctuation = 'P' . [cdseifo]?;\n category_symbol = 'S' . [mcko]?;\n category_separator = 'Z' . [slp]?;\n category_codepoint = 'C' . [cfson]?;\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n posix_class = '[:' . posix_class_name . ':]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n property_char = [pP];\n\n escaped_char = [aefnrtv];\n octal_sequence = '0' . [0-7]{2};\n\n hex_sequence = 'x' . xdigit{2};\n wide_hex_sequence = 'x' . '{7' . xdigit{1,7} . '}';\n\n control_sequence = ('c' | 'C-') . xdigit{1,2};\n meta_sequence = 'M-' . xdigit{1,2};\n meta_control_sequence = 'M-\\\\C-' . xdigit{1,2};\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_range = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_range;\n\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | ('?\\'' . group_name . '\\'');\n\n group_type = group_atomic | group_passive | group_named;\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = wild | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n self.emit(:set, :close, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n '^' {\n self.emit(:set, :negate, data[ts..te-1].pack('c*'), ts, te)\n };\n\n alnum . '-' . alnum { # TODO: add properties\n self.emit(:set, :range, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '&&' {\n self.emit(:set, :intersection, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n posix_class {\n case text = data[ts..te-1].pack('c*')\n when '[:alnum:]'; self.emit(:set, :class_alnum, text, ts, te)\n when '[:alpha:]'; self.emit(:set, :class_alpha, text, ts, te)\n when '[:blank:]'; self.emit(:set, :class_blank, text, ts, te)\n when '[:cntrl:]'; self.emit(:set, :class_cntrl, text, ts, te)\n when '[:digit:]'; self.emit(:set, :class_digit, text, ts, te)\n when '[:graph:]'; self.emit(:set, :class_graph, text, ts, te)\n when '[:lower:]'; self.emit(:set, :class_lower, text, ts, te)\n when '[:print:]'; self.emit(:set, :class_print, text, ts, te)\n when '[:punct:]'; self.emit(:set, :class_punct, text, ts, te)\n when '[:space:]'; self.emit(:set, :class_space, text, ts, te)\n when '[:upper:]'; self.emit(:set, :class_upper, text, ts, te)\n when '[:xdigit:]'; self.emit(:set, :class_xdigit, text, ts, te)\n when '[:word:]'; self.emit(:set, :class_word, text, ts, te)\n when '[:ascii:]'; self.emit(:set, :class_ascii, text, ts, te)\n else raise \"Unsupported character posixe class at #{text} (char #{ts})\"\n end\n };\n\n any {\n self.emit(:set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' {\n self.emit(:set, :backspace, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [\\\\\\]\\-\\,] {\n self.emit(:set, :escape, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [dDhHsSwW] {\n case text = data[ts-1..te-1].pack('c*')\n when '\\d'; self.emit(:set, :type_digit, text, ts-1, te)\n when '\\D'; self.emit(:set, :type_nondigit, text, ts-1, te)\n when '\\h'; self.emit(:set, :type_hex, text, ts-1, te)\n when '\\H'; self.emit(:set, :type_nonhex, text, ts-1, te)\n when '\\s'; self.emit(:set, :type_space, text, ts-1, te)\n when '\\S'; self.emit(:set, :type_nonspace, text, ts-1, te)\n when '\\w'; self.emit(:set, :type_word, text, ts-1, te)\n when '\\W'; self.emit(:set, :type_nonword, text, ts-1, te)\n end\n\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n self.emit(:set, :range_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n hex_sequence {\n self.emit(:set, :member_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n hex_sequence {\n self.emit(:escape, :hex, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n wide_hex_sequence {\n self.emit(:escape, :hex_wide, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n control_sequence {\n self.emit(:escape, :control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_sequence {\n self.emit(:escape, :meta, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_control_sequence {\n self.emit(:escape, :meta_control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n # TODO: extract into a separate machine... use in sets\n property_char . '{' . (property_name | general_category) . '}' > (escaped_alpha, 2) {\n text = data[ts..te-1].pack('c*')\n type = text[0,1] == 'p' ? :property: :inverted_property\n\n case name = data[ts+2..te-2].pack('c*')\n\n # Named\n when 'Alnum'; self.emit(type, :alnum, text, ts, te)\n when 'Alpha'; self.emit(type, :alpha, text, ts, te)\n when 'Any'; self.emit(type, :any, text, ts, te)\n when 'Ascii'; self.emit(type, :ascii, text, ts, te)\n when 'Blank'; self.emit(type, :blank, text, ts, te)\n when 'Cntrl'; self.emit(type, :cntrl, text, ts, te)\n when 'Digit'; self.emit(type, :digit, text, ts, te)\n when 'Graph'; self.emit(type, :graph, text, ts, te)\n when 'Lower'; self.emit(type, :lower, text, ts, te)\n when 'Print'; self.emit(type, :print, text, ts, te)\n when 'Punct'; self.emit(type, :punct, text, ts, te)\n when 'Space'; self.emit(type, :space, text, ts, te)\n when 'Upper'; self.emit(type, :upper, text, ts, te)\n when 'Word'; self.emit(type, :word, text, ts, te)\n when 'Xdigit'; self.emit(type, :xdigit, text, ts, te)\n\n # Letters\n when 'L'; self.emit(type, :letter_any, text, ts, te)\n when 'Lu'; self.emit(type, :letter_uppercase, text, ts, te)\n when 'Ll'; self.emit(type, :letter_lowercase, text, ts, te)\n when 'Lt'; self.emit(type, :letter_titlecase, text, ts, te)\n when 'Lm'; self.emit(type, :letter_modifier, text, ts, te)\n when 'Lo'; self.emit(type, :letter_other, text, ts, te)\n\n # Marks\n when 'M'; self.emit(type, :mark_any, text, ts, te)\n when 'Mn'; self.emit(type, :mark_nonspacing, text, ts, te)\n when 'Mc'; self.emit(type, :mark_spacing, text, ts, te)\n when 'Me'; self.emit(type, :mark_enclosing, text, ts, te)\n\n # Numbers\n when 'N'; self.emit(type, :number_any, text, ts, te)\n when 'Nd'; self.emit(type, :number_decimal, text, ts, te)\n when 'Nl'; self.emit(type, :number_letter, text, ts, te)\n when 'No'; self.emit(type, :number_other, text, ts, te)\n\n # Punctuation\n when 'P'; self.emit(type, :punct_any, text, ts, te)\n when 'Pc'; self.emit(type, :punct_connector, text, ts, te)\n when 'Pd'; self.emit(type, :punct_dash, text, ts, te)\n when 'Ps'; self.emit(type, :punct_open, text, ts, te)\n when 'Pe'; self.emit(type, :punct_close, text, ts, te)\n when 'Pi'; self.emit(type, :punct_initial, text, ts, te)\n when 'Pf'; self.emit(type, :punct_final, text, ts, te)\n when 'Po'; self.emit(type, :punct_other, text, ts, te)\n\n # Symbols\n when 'S'; self.emit(type, :symbol_any, text, ts, te)\n when 'Sm'; self.emit(type, :symbol_math, text, ts, te)\n when 'Sc'; self.emit(type, :symbol_currency, text, ts, te)\n when 'Sk'; self.emit(type, :symbol_modifier, text, ts, te)\n when 'So'; self.emit(type, :symbol_other, text, ts, te)\n\n # Separators\n when 'Z'; self.emit(type, :separator_any, text, ts, te)\n when 'Zs'; self.emit(type, :separator_space, text, ts, te)\n when 'Zl'; self.emit(type, :separator_line, text, ts, te)\n when 'Zp'; self.emit(type, :separator_paragraph, text, ts, te)\n\n # Codepoints\n when 'C'; self.emit(type, :code_any, text, ts, te)\n when 'Cc'; self.emit(type, :code_control, text, ts, te)\n when 'Cf'; self.emit(type, :code_format, text, ts, te)\n when 'Cs'; self.emit(type, :code_surrogate, text, ts, te)\n when 'Co'; self.emit(type, :code_private, text, ts, te)\n when 'Cn'; self.emit(type, :code_unassigned, text, ts, te)\n end\n };\n\n any > (escaped_alpha, 1) {\n self.emit(:escape, :literal, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n alternation {\n self.emit(:meta, :alternation, data[ts..te-1].pack('c*'), ts, te)\n };\n\n wild {\n self.emit(:meta, :wild, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S whitespace, non-whitespace\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\d'; self.emit(:type, :digit, text, ts, te)\n when '\\\\D'; self.emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; self.emit(:type, :hex, text, ts, te)\n when '\\\\H'; self.emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; self.emit(:type, :space, text, ts, te)\n when '\\\\S'; self.emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; self.emit(:type, :word, text, ts, te)\n when '\\\\W'; self.emit(:type, :nonword, text, ts, te)\n end\n };\n\n # Anchors\n beginning_of_line {\n self.emit(:anchor, :beginning_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n end_of_line {\n self.emit(:anchor, :end_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\A'; self.emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; self.emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; self.emit(:anchor, :eos_or_before_eol, text, ts, te)\n when '\\\\b'; self.emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; self.emit(:anchor, :nonword_boundary, text, ts, te)\n else raise \"Unsupported anchor at #{text} (char #{ts})\"\n end\n };\n\n # Escaped sequences\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Character sets\n set_open {\n self.emit(:set, :open, data[ts..te-1].pack('c*'), ts, te)\n fcall character_set;\n };\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n group_open . group_comment {\n self.emit(:group, :comment, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # (?mix-mix...) expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n group_open . group_options {\n self.emit(:group, :options, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group (single quotes are no supported, yet)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type {\n case text = data[ts..te-1].pack('c*')\n when '(?:'; self.emit(:group, :passive, text, ts, te)\n when '(?>'; self.emit(:group, :atomic, text, ts, te)\n when \/\\(\\?<\\w+>\/\n self.emit(:group, :named, text, ts, te)\n end\n };\n\n group_open {\n text = data[ts..te-1].pack('c*')\n self.emit(:group, :capture, text, ts, te)\n };\n\n group_close {\n self.emit(:group, :close, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = data[ts..te-1].pack('c*')\n when '?' ; self.emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; self.emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; self.emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n \n zero_or_more {\n case text = data[ts..te-1].pack('c*')\n when '*' ; self.emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; self.emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; self.emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n \n one_or_more {\n case text = data[ts..te-1].pack('c*')\n when '+' ; self.emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; self.emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; self.emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n\n # Intervals: min, max, and exact notations\n # ------------------------------------------------------------------------\n range_open . (digit+)? . ','? . (digit+)? . range_close . quantifier_mode? {\n self.emit(:quantifier, :interval, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Literal: anything, except meta characters. This includes 2, 3, and 4\n # unicode byte sequences.\n # ------------------------------------------------------------------------\n (any - meta_char)+ {\n self.emit(:literal, :literal, data[ts..te-1].pack('c*'), ts, te)\n };\n\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"3fff81c0250210d38a8cb2af22c692b136074eb0","subject":"Add a CONFIG_RL_DEBUG define that prints debugging messages for the crontab parser.","message":"Add a CONFIG_RL_DEBUG define that prints debugging messages for the\ncrontab parser.\n","repos":"niklata\/ncron,niklata\/ncron","old_file":"config.rl","new_file":"config.rl","new_contents":"\/* config.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n#include \"nk\/malloc.h\"\n#include \"nk\/privilege.h\"\n\n#include \"ncron.h\"\n#include \"config.h\"\n#include \"sched.h\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\n\nstruct ParseCfgState\n{\n char v_str[1024];\n\n cronentry_t *stack;\n cronentry_t *deadstack;\n cronentry_t *ce;\n\n char *execfile;\n\n char *jobid_st;\n char *time_st;\n char *intv_st;\n char *intv2_st;\n char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_jobid;\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int noextime;\n int cmdret;\n\n bool intv2_exist;\n};\n\nstatic void nullify_item(cronentry_t *item)\n{\n if (!item)\n return;\n item->id = 0;\n item->command = NULL;\n item->args = NULL;\n item->chroot = NULL;\n item->numruns = 0;\n item->maxruns = 0;\n item->journal = 0;\n item->user = 0;\n item->group = 0;\n item->month = NULL;\n item->day = NULL;\n item->weekday = NULL;\n item->hour = NULL;\n item->minute = NULL;\n item->interval = 0;\n item->exectime = 0;\n item->lasttime = 0;\n item->limits = NULL;\n item->next = NULL;\n}\n\nstatic void nullify_limits(limit_t *l)\n{\n if (!l)\n return;\n l->cpu = NULL;\n l->fsize = NULL;\n l->data = NULL;\n l->stack = NULL;\n l->core = NULL;\n l->rss = NULL;\n l->nproc = NULL;\n l->nofile = NULL;\n l->memlock = NULL;\n l->as = NULL;\n}\n\nstruct hstm {\n char *st;\n int cs;\n int id;\n time_t exectime;\n time_t lasttime;\n unsigned int numruns;\n bool got_exectime:1;\n bool got_lasttime:1;\n bool got_numruns:1;\n};\n\n%%{\n machine history_m;\n access hstm->;\n\n action St { hstm->st = p; }\n action LastTimeEn {\n hstm->lasttime = atoi(p);\n hstm->got_lasttime = 1;\n }\n action NumRunsEn {\n hstm->numruns = atoi(p);\n hstm->got_numruns = 1;\n }\n action ExecTimeEn {\n hstm->exectime = atoi(p);\n hstm->got_exectime = 1;\n }\n action IdEn { hstm->id = atoi(p); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_get_history(struct hstm *hstm, char *buf, size_t blen)\n{\n char *p = buf;\n const char *pe = buf + blen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (hstm->cs >= history_m_first_final)\n return 1;\n if (hstm->cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic void get_history(cronentry_t *item, char *path, int noextime)\n{\n struct hstm hstm = {0};\n\n assert(item);\n\n if (!noextime && !hstm.got_exectime)\n item->exectime = 0;\n\n FILE *f = fopen(path, \"r\");\n if (!f) {\n log_line(\"failed to open history file \\\"%s\\\" for read\", path);\n if (!noextime)\n item->exectime = (time_t)0; \/* gracefully fail *\/\n return;\n }\n\n char buf[MAXLINE];\n while (fgets(buf, sizeof buf, f)) {\n int r = do_get_history(&hstm, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_get_history(%s) failed\", __func__, path);\n if (r == 1) {\n if (hstm.id == item->id) {\n if (hstm.got_lasttime)\n item->lasttime = hstm.lasttime;\n if (hstm.got_numruns)\n item->numruns = hstm.numruns;\n if (hstm.got_exectime && !noextime)\n item->exectime = hstm.exectime;\n break;\n }\n }\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n}\n\nstatic void setlim(struct ParseCfgState *ncs, int type)\n{\n struct rlimit **p = NULL;\n if (!ncs->ce->limits) {\n ncs->ce->limits = xmalloc(sizeof(limit_t));\n nullify_limits(ncs->ce->limits);\n }\n switch (type) {\n case RLIMIT_CPU: *p = ncs->ce->limits->cpu; break;\n case RLIMIT_FSIZE: *p = ncs->ce->limits->fsize; break;\n case RLIMIT_DATA: *p = ncs->ce->limits->data; break;\n case RLIMIT_STACK: *p = ncs->ce->limits->stack; break;\n case RLIMIT_CORE: *p = ncs->ce->limits->core; break;\n case RLIMIT_RSS: *p = ncs->ce->limits->rss; break;\n case RLIMIT_NPROC: *p = ncs->ce->limits->nproc; break;\n case RLIMIT_NOFILE: *p = ncs->ce->limits->nofile; break;\n case RLIMIT_MEMLOCK: *p = ncs->ce->limits->memlock; break;\n#ifndef BSD\n case RLIMIT_AS: *p = ncs->ce->limits->as; break;\n#endif \/* BSD *\/\n default: return;\n }\n if (!p)\n suicide(\"%s: unexpected NULL, corruption?\", __func__);\n if (!*p)\n *p = xmalloc(sizeof(struct rlimit));\n if (ncs->v_int == 0) (*p)->rlim_cur = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int;\n\n if (ncs->v_int2 == 0) (*p)->rlim_max = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int2;\n}\n\nstatic void addipairlist(struct ParseCfgState *ncs,\n ipair_node_t **list, int wildcard, int min, int max)\n{\n ipair_node_t *l;\n int low, high = wildcard;\n\n low = ncs->v_int;\n if (ncs->intv2_exist)\n high = ncs->v_int2;\n\n if (high == wildcard)\n high = low;\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (*list == NULL) {\n *list = xmalloc(sizeof(ipair_node_t));\n l = *list;\n } else {\n l = *list;\n while (l->next)\n l = l->next;\n\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n }\n\n \/* discontinuous range, split into two continuous rules... *\/\n if (low > high) {\n l->node.l = low;\n l->node.h = max;\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n l->node.l = min;\n l->node.h = high;\n l->next = NULL;\n } else {\n \/* handle continuous ranges normally *\/\n l->node.l = low;\n l->node.h = high;\n l->next = NULL;\n }\n}\n\nstatic void setgroupv(struct ParseCfgState *ncs)\n{\n if (nk_gidbyname(ncs->v_str, &ncs->ce->group))\n suicide(\"%s: nonexistent group specified at line %zu\", ncs->linenum);\n}\n\nstatic void setuserv(struct ParseCfgState *ncs)\n{\n if (nk_uidgidbyname(ncs->v_str, &ncs->ce->user, &ncs->ce->group))\n suicide(\"%s: nonexistent user specified at line %zu\", ncs->linenum);\n}\n\nstatic void parse_assign_str(char **dest, char *src, size_t srclen,\n size_t linenum)\n{\n if (srclen > INT_MAX)\n suicide(\"%s: srclen would overflow int at line %zu\",\n __func__, linenum);\n free(*dest);\n *dest = xmalloc(srclen+1);\n ssize_t l = snprintf(*dest, srclen+1, \"%.*s\", (int)srclen, src);\n if (l < 0 || (size_t)l >= srclen+1)\n suicide(\"%s: snprintf failed l=%u srclen+1=%u at line %zu\",\n __func__, l, srclen+1, linenum);\n}\n\nstruct pckm {\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n size_t cmdlen = p - pckm.st;\n parse_assign_str(&ncs->ce->command, pckm.st, cmdlen, ncs->linenum);\n \/\/ Unescape \"\\\\\" and \"\\ \".\n int prevsl = 0;\n size_t i = 0;\n while (ncs->ce->command[i]) {\n if (prevsl && (ncs->ce->command[i] == '\\\\'\n || ncs->ce->command[i] == ' ')) {\n memmove(ncs->ce->command + i - 1,\n ncs->ce->command + i, cmdlen--);\n continue;\n }\n if (ncs->ce->command[i] == '\\\\')\n prevsl = 1;\n ++i;\n }\n }\n action ArgEn {\n parse_assign_str(&ncs->ce->args, pckm.st, p - pckm.st, ncs->linenum);\n }\n\n sptab = [ \\t];\n cmd = sptab+ ([^\\0 \\\\] | '\\\\\\\\' | '\\\\ ')+ > St % CmdEn;\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(struct ParseCfgState *ncs)\n{\n char *p = ncs->v_str;\n const char *pe = ncs->v_str + ncs->v_strlen;\n const char *eof = pe;\n\n struct pckm pckm = {0};\n\n if (ncs->cmdret != 0) {\n ncs->cmdret = -3;\n suicide(\"Duplicate 'command' value at line %zu\", ncs->linenum);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs->cmdret = -1;\n suicide(\"Malformed 'command' value at line %zu\", ncs->linenum);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs->cmdret = 1;\n else {\n ncs->cmdret = -2;\n suicide(\"Incomplete 'command' value at line %zu\", ncs->linenum);\n }\n}\n\nstatic void create_ce(struct ParseCfgState *ncs)\n{\n assert(!ncs->ce);\n ncs->ce = xmalloc(sizeof(cronentry_t));\n nullify_item(ncs->ce);\n ncs->cmdret = 0;\n ncs->noextime = 0;\n}\n\n#ifdef CONFIG_RL_DEBUG\nstatic void debug_print_ce(struct ParseCfgState *ncs)\n{\n printf(\"\\nfinish_ce:\\n\");\n printf(\"id: %u\\n\", ncs->ce->id);\n printf(\"command: %s\\n\", ncs->ce->command);\n printf(\"args: %s\\n\", ncs->ce->args);\n printf(\"chroot: %s\\n\", ncs->ce->chroot);\n printf(\"numruns: %u\\n\", ncs->ce->numruns);\n printf(\"maxruns: %u\\n\", ncs->ce->maxruns);\n printf(\"journal: %d\\n\", ncs->ce->journal);\n printf(\"user: %u\\n\", ncs->ce->user);\n printf(\"group: %u\\n\", ncs->ce->group);\n if (ncs->ce->month)\n printf(\"month: [%d,%d]\\n\", ncs->ce->month->node.l, ncs->ce->month->node.h);\n if (ncs->ce->day)\n printf(\"day: [%d,%d]\\n\", ncs->ce->day->node.l, ncs->ce->day->node.h);\n if (ncs->ce->weekday)\n printf(\"weekday: [%d,%d]\\n\", ncs->ce->weekday->node.l, ncs->ce->weekday->node.h);\n if (ncs->ce->hour)\n printf(\"hour: [%d,%d]\\n\", ncs->ce->hour->node.l, ncs->ce->hour->node.h);\n if (ncs->ce->minute)\n printf(\"minute: [%d,%d]\\n\", ncs->ce->minute->node.l, ncs->ce->minute->node.h);\n printf(\"interval: %u\\n\", ncs->ce->interval);\n printf(\"exectime: %u\\n\", ncs->ce->exectime);\n printf(\"lasttime: %u\\n\", ncs->ce->lasttime);\n}\nstatic void debug_print_ce_ignore(struct ParseCfgState *ncs)\n{\n (void)ncs;\n printf(\"===> IGNORE\\n\");\n}\nstatic void debug_print_ce_add(struct ParseCfgState *ncs)\n{\n (void)ncs;\n printf(\"===> ADD\\n\");\n}\n#else\nstatic void debug_print_ce(struct ParseCfgState *ncs) {(void)ncs;}\nstatic void debug_print_ce_ignore(struct ParseCfgState *ncs) {(void)ncs;}\nstatic void debug_print_ce_add(struct ParseCfgState *ncs) {(void)ncs;}\n#endif\n\nstatic void finish_ce(struct ParseCfgState *ncs)\n{\n if (!ncs->ce)\n return;\n\n debug_print_ce(ncs);\n\n if (ncs->ce->id <= 0\n || (ncs->ce->interval <= 0 && ncs->ce->exectime <= 0)\n || !ncs->ce->command || ncs->cmdret < 1) {\n debug_print_ce_ignore(ncs);\n free_cronentry(&ncs->ce);\n ncs->ce = NULL;\n return;\n }\n debug_print_ce_add(ncs);\n\n \/* we have a job to insert *\/\n if (ncs->ce->exectime != 0) { \/* runat task *\/\n get_history(ncs->ce, ncs->execfile, 1);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n } else { \/* interval task *\/\n get_history(ncs->ce, ncs->execfile, ncs->noextime && !cfg_reload);\n\n \/* compensate for user edits to job constraints *\/\n time_t ttm = get_first_time(ncs->ce);\n if (ttm - ncs->ce->lasttime >= ncs->ce->interval)\n ncs->ce->exectime = ttm;\n else\n force_to_constraint(ncs->ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n && ncs->ce->exectime != 0)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n }\n ncs->ce = NULL;\n}\n\n%%{\n machine ncrontab;\n access ncs->;\n\n spc = [ \\t];\n eqsep = spc+ '=' spc+;\n cmdterm = [\\0\\n];\n\n action TUnitSt { ncs->time_st = p; ncs->v_time = 0; }\n action TSecEn { ncs->v_time += atoi(ncs->time_st); }\n action TMinEn { ncs->v_time += 60 * atoi(ncs->time_st); }\n action THrEn { ncs->v_time += 3600 * atoi(ncs->time_st); }\n action TDayEn { ncs->v_time += 86400 * atoi(ncs->time_st); }\n action TWeekEn { ncs->v_time += 604800 * atoi(ncs->time_st); }\n\n action IntValSt {\n ncs->intv_st = p;\n ncs->v_int = ncs->v_int2 = 0;\n ncs->intv2_exist = false;\n }\n action IntValEn { ncs->v_int = atoi(ncs->intv_st); }\n action IntVal2St { ncs->intv2_st = p; }\n action IntVal2En {\n ncs->v_int2 = atoi(ncs->intv2_st);\n ncs->intv2_exist = true;\n }\n\n action StrValSt { ncs->strv_st = p; ncs->v_strlen = 0; }\n action StrValEn {\n ncs->v_strlen = p - ncs->strv_st;\n if (ncs->v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs->v_str, sizeof ncs->v_str,\n \"%.*s\", (int)ncs->v_strlen, ncs->strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs->v_str)\n suicide(\"error parsing line %u in crontab; too long?\",\n ncs->linenum);\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn) cmdterm;\n timeval = t_any (spc* t_any)* cmdterm;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))? cmdterm;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn) cmdterm;\n\n action JournalEn { ncs->ce->journal = 1; }\n action NoExecTimeEn { ncs->noextime = 1; }\n\n journal = 'journal'i cmdterm % JournalEn;\n noexectime = 'noexectime'i cmdterm % NoExecTimeEn;\n\n action RunAtEn {\n ncs->ce->exectime = ncs->v_int;\n ncs->ce->maxruns = 1;\n ncs->ce->journal = 1;\n }\n action MaxRunsEn {\n if (ncs->ce->exectime == 0)\n ncs->ce->maxruns = ncs->v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n\n action IntervalEn { ncs->ce->interval = ncs->v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addipairlist(ncs, &ncs->ce->month, 0, 1, 12); }\n action DayEn { addipairlist(ncs, &ncs->ce->day, 0, 1, 31); }\n action WeekdayEn { addipairlist(ncs, &ncs->ce->weekday, 0, 1, 7); }\n action HourEn { addipairlist(ncs, &ncs->ce->hour, 24, 0, 23); }\n action MinuteEn { addipairlist(ncs, &ncs->ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn {\n parse_assign_str(&ncs->ce->chroot, ncs->v_str, ncs->v_strlen,\n ncs->linenum);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n maxruns | runat | noexectime | journal;\n\n action JobIdSt { ncs->jobid_st = p; }\n action JobIdEn { ncs->v_jobid = atoi(ncs->jobid_st); }\n action CreateCe { finish_ce(ncs); create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) cmdterm % JobIdEn;\n\n main := jobid | cmds;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(struct ParseCfgState *ncs, char *data, size_t len)\n{\n char *p = data;\n const char *pe = data + len;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs->cs == ncrontab_error)\n return -1;\n if (ncs->cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(char *path, char *execfile, cronentry_t **stk,\n cronentry_t **deadstk)\n{\n char buf[MAXLINE];\n struct ParseCfgState ncs;\n memset(&ncs, 0, sizeof ncs);\n ncs.execfile = execfile;\n ncs.stack = *stk;\n ncs.deadstack = *deadstk;\n\n FILE *f = fopen(path, \"r\");\n if (!f)\n suicide(\"%s: fopen(%s) failed: %s\", __func__, path, strerror(errno));\n\n while (++ncs.linenum, fgets(buf, sizeof buf, f)) {\n int r = do_parse_config(&ncs, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_parse_config(%s) failed\", __func__, path);\n if (r == 1)\n break;\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n *stk = ncs.stack;\n *deadstk = ncs.deadstack;\n if (ncs.ce)\n free_cronentry(&ncs.ce); \/\/ Free partially built unused item.\n cfg_reload = 1;\n}\n\n","old_contents":"\/* config.rl - configure file parser for ncron\n *\n * (c) 2003-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nk\/log.h\"\n#include \"nk\/malloc.h\"\n#include \"nk\/privilege.h\"\n\n#include \"ncron.h\"\n#include \"config.h\"\n#include \"sched.h\"\n\n\/* BSD uses OFILE rather than NOFILE... *\/\n#ifndef RLIMIT_NOFILE\n# define RLIMIT_NOFILE RLIMIT_OFILE\n#endif\n\nstatic int cfg_reload; \/* 0 on first call, 1 on subsequent calls *\/\n\nstruct ParseCfgState\n{\n char v_str[1024];\n\n cronentry_t *stack;\n cronentry_t *deadstack;\n cronentry_t *ce;\n\n char *execfile;\n\n char *jobid_st;\n char *time_st;\n char *intv_st;\n char *intv2_st;\n char *strv_st;\n\n size_t v_strlen;\n size_t linenum;\n\n unsigned int v_jobid;\n unsigned int v_time;\n\n int v_int;\n int v_int2;\n\n int cs;\n int noextime;\n int cmdret;\n\n bool intv2_exist;\n};\n\nstatic void nullify_item(cronentry_t *item)\n{\n if (!item)\n return;\n item->id = 0;\n item->command = NULL;\n item->args = NULL;\n item->chroot = NULL;\n item->numruns = 0;\n item->maxruns = 0;\n item->journal = 0;\n item->user = 0;\n item->group = 0;\n item->month = NULL;\n item->day = NULL;\n item->weekday = NULL;\n item->hour = NULL;\n item->minute = NULL;\n item->interval = 0;\n item->exectime = 0;\n item->lasttime = 0;\n item->limits = NULL;\n item->next = NULL;\n}\n\nstatic void nullify_limits(limit_t *l)\n{\n if (!l)\n return;\n l->cpu = NULL;\n l->fsize = NULL;\n l->data = NULL;\n l->stack = NULL;\n l->core = NULL;\n l->rss = NULL;\n l->nproc = NULL;\n l->nofile = NULL;\n l->memlock = NULL;\n l->as = NULL;\n}\n\nstruct hstm {\n char *st;\n int cs;\n int id;\n time_t exectime;\n time_t lasttime;\n unsigned int numruns;\n bool got_exectime:1;\n bool got_lasttime:1;\n bool got_numruns:1;\n};\n\n%%{\n machine history_m;\n access hstm->;\n\n action St { hstm->st = p; }\n action LastTimeEn {\n hstm->lasttime = atoi(p);\n hstm->got_lasttime = 1;\n }\n action NumRunsEn {\n hstm->numruns = atoi(p);\n hstm->got_numruns = 1;\n }\n action ExecTimeEn {\n hstm->exectime = atoi(p);\n hstm->got_exectime = 1;\n }\n action IdEn { hstm->id = atoi(p); }\n\n lasttime = '|' digit+ > St % LastTimeEn;\n numruns = ':' digit+ > St % NumRunsEn;\n exectime = '=' digit+ > St % ExecTimeEn;\n id = digit+ > St % IdEn;\n main := id (numruns | exectime | lasttime)+;\n}%%\n\n%% write data;\n\nstatic int do_get_history(struct hstm *hstm, char *buf, size_t blen)\n{\n char *p = buf;\n const char *pe = buf + blen;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (hstm->cs >= history_m_first_final)\n return 1;\n if (hstm->cs == history_m_error)\n return -1;\n return -2;\n}\n\nstatic void get_history(cronentry_t *item, char *path, int noextime)\n{\n struct hstm hstm = {0};\n\n assert(item);\n\n if (!noextime && !hstm.got_exectime)\n item->exectime = 0;\n\n FILE *f = fopen(path, \"r\");\n if (!f) {\n log_line(\"failed to open history file \\\"%s\\\" for read\", path);\n if (!noextime)\n item->exectime = (time_t)0; \/* gracefully fail *\/\n return;\n }\n\n char buf[MAXLINE];\n while (fgets(buf, sizeof buf, f)) {\n int r = do_get_history(&hstm, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_get_history(%s) failed\", __func__, path);\n if (r == 1) {\n if (hstm.id == item->id) {\n if (hstm.got_lasttime)\n item->lasttime = hstm.lasttime;\n if (hstm.got_numruns)\n item->numruns = hstm.numruns;\n if (hstm.got_exectime && !noextime)\n item->exectime = hstm.exectime;\n break;\n }\n }\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n}\n\nstatic void setlim(struct ParseCfgState *ncs, int type)\n{\n struct rlimit **p = NULL;\n if (!ncs->ce->limits) {\n ncs->ce->limits = xmalloc(sizeof(limit_t));\n nullify_limits(ncs->ce->limits);\n }\n switch (type) {\n case RLIMIT_CPU: *p = ncs->ce->limits->cpu; break;\n case RLIMIT_FSIZE: *p = ncs->ce->limits->fsize; break;\n case RLIMIT_DATA: *p = ncs->ce->limits->data; break;\n case RLIMIT_STACK: *p = ncs->ce->limits->stack; break;\n case RLIMIT_CORE: *p = ncs->ce->limits->core; break;\n case RLIMIT_RSS: *p = ncs->ce->limits->rss; break;\n case RLIMIT_NPROC: *p = ncs->ce->limits->nproc; break;\n case RLIMIT_NOFILE: *p = ncs->ce->limits->nofile; break;\n case RLIMIT_MEMLOCK: *p = ncs->ce->limits->memlock; break;\n#ifndef BSD\n case RLIMIT_AS: *p = ncs->ce->limits->as; break;\n#endif \/* BSD *\/\n default: return;\n }\n if (!p)\n suicide(\"%s: unexpected NULL, corruption?\", __func__);\n if (!*p)\n *p = xmalloc(sizeof(struct rlimit));\n if (ncs->v_int == 0) (*p)->rlim_cur = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int;\n\n if (ncs->v_int2 == 0) (*p)->rlim_max = RLIM_INFINITY;\n else (*p)->rlim_cur = ncs->v_int2;\n}\n\nstatic void addipairlist(struct ParseCfgState *ncs,\n ipair_node_t **list, int wildcard, int min, int max)\n{\n ipair_node_t *l;\n int low, high = wildcard;\n\n low = ncs->v_int;\n if (ncs->intv2_exist)\n high = ncs->v_int2;\n\n if (high == wildcard)\n high = low;\n if (low > max || low < min)\n low = wildcard;\n if (high > max || high < min)\n high = wildcard;\n\n \/* we don't allow meaningless 'rules' *\/\n if (low == wildcard && high == wildcard)\n return;\n\n if (*list == NULL) {\n *list = xmalloc(sizeof(ipair_node_t));\n l = *list;\n } else {\n l = *list;\n while (l->next)\n l = l->next;\n\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n }\n\n \/* discontinuous range, split into two continuous rules... *\/\n if (low > high) {\n l->node.l = low;\n l->node.h = max;\n l->next = xmalloc(sizeof(ipair_node_t));\n l = l->next;\n l->node.l = min;\n l->node.h = high;\n l->next = NULL;\n } else {\n \/* handle continuous ranges normally *\/\n l->node.l = low;\n l->node.h = high;\n l->next = NULL;\n }\n}\n\nstatic void setgroupv(struct ParseCfgState *ncs)\n{\n if (nk_gidbyname(ncs->v_str, &ncs->ce->group))\n suicide(\"%s: nonexistent group specified at line %zu\", ncs->linenum);\n}\n\nstatic void setuserv(struct ParseCfgState *ncs)\n{\n if (nk_uidgidbyname(ncs->v_str, &ncs->ce->user, &ncs->ce->group))\n suicide(\"%s: nonexistent user specified at line %zu\", ncs->linenum);\n}\n\nstatic void parse_assign_str(char **dest, char *src, size_t srclen,\n size_t linenum)\n{\n if (srclen > INT_MAX)\n suicide(\"%s: srclen would overflow int at line %zu\",\n __func__, linenum);\n free(*dest);\n *dest = xmalloc(srclen+1);\n ssize_t l = snprintf(*dest, srclen+1, \"%.*s\", (int)srclen, src);\n if (l < 0 || (size_t)l >= srclen+1)\n suicide(\"%s: snprintf failed l=%u srclen+1=%u at line %zu\",\n __func__, l, srclen+1, linenum);\n}\n\nstruct pckm {\n char *st;\n int cs;\n};\n\n%%{\n machine parse_cmd_key_m;\n access pckm.;\n\n action St { pckm.st = p; }\n action CmdEn {\n size_t cmdlen = p - pckm.st;\n parse_assign_str(&ncs->ce->command, pckm.st, cmdlen, ncs->linenum);\n \/\/ Unescape \"\\\\\" and \"\\ \".\n int prevsl = 0;\n size_t i = 0;\n while (ncs->ce->command[i]) {\n if (prevsl && (ncs->ce->command[i] == '\\\\'\n || ncs->ce->command[i] == ' ')) {\n memmove(ncs->ce->command + i - 1,\n ncs->ce->command + i, cmdlen--);\n continue;\n }\n if (ncs->ce->command[i] == '\\\\')\n prevsl = 1;\n ++i;\n }\n }\n action ArgEn {\n parse_assign_str(&ncs->ce->args, pckm.st, p - pckm.st, ncs->linenum);\n }\n\n sptab = [ \\t];\n cmd = sptab+ ([^\\0 \\\\] | '\\\\\\\\' | '\\\\ ')+ > St % CmdEn;\n args = sptab+ ([^\\0])* > St % ArgEn;\n main := cmd args;\n}%%\n\n%% write data;\n\n\/\/ cmdret = 0: Not parsed a command key yet.\n\/\/ cmdret = 1: Success. Got a command key.\n\/\/ cmdret = -1: Error: malformed command key.\n\/\/ cmdret = -2: Error: incomplete command key.\n\/\/ cmdret = -3: Error: duplicate command key.\nstatic void parse_command_key(struct ParseCfgState *ncs)\n{\n char *p = ncs->v_str;\n const char *pe = ncs->v_str + ncs->v_strlen;\n const char *eof = pe;\n\n struct pckm pckm = {0};\n\n if (ncs->cmdret != 0) {\n ncs->cmdret = -3;\n suicide(\"Duplicate 'command' value at line %zu\", ncs->linenum);\n }\n\n %% write init;\n %% write exec;\n\n if (pckm.cs == parse_cmd_key_m_error) {\n ncs->cmdret = -1;\n suicide(\"Malformed 'command' value at line %zu\", ncs->linenum);\n } else if (pckm.cs >= parse_cmd_key_m_first_final)\n ncs->cmdret = 1;\n else {\n ncs->cmdret = -2;\n suicide(\"Incomplete 'command' value at line %zu\", ncs->linenum);\n }\n}\n\nstatic void create_ce(struct ParseCfgState *ncs)\n{\n assert(!ncs->ce);\n ncs->ce = xmalloc(sizeof(cronentry_t));\n nullify_item(ncs->ce);\n ncs->cmdret = 0;\n ncs->noextime = 0;\n}\n\nstatic void finish_ce(struct ParseCfgState *ncs)\n{\n assert(ncs->ce);\n if (ncs->ce->id <= 0\n || (ncs->ce->interval <= 0 && ncs->ce->exectime <= 0)\n || !ncs->ce->command || ncs->cmdret < 1) {\n free_cronentry(&ncs->ce);\n return;\n }\n\n \/* we have a job to insert *\/\n if (ncs->ce->exectime != 0) { \/* runat task *\/\n get_history(ncs->ce, ncs->execfile, 1);\n\n \/* insert iif we haven't exceeded maxruns *\/\n if (ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n } else { \/* interval task *\/\n get_history(ncs->ce, ncs->execfile, ncs->noextime && !cfg_reload);\n\n \/* compensate for user edits to job constraints *\/\n time_t ttm = get_first_time(ncs->ce);\n if (ttm - ncs->ce->lasttime >= ncs->ce->interval)\n ncs->ce->exectime = ttm;\n else\n force_to_constraint(ncs->ce);\n\n \/* insert iif numruns < maxruns and no constr error *\/\n if ((ncs->ce->maxruns == 0 || ncs->ce->numruns < ncs->ce->maxruns)\n && ncs->ce->exectime != 0)\n stack_insert(ncs->ce, &ncs->stack);\n else\n stack_insert(ncs->ce, &ncs->deadstack);\n }\n ncs->ce = NULL;\n}\n\n%%{\n machine ncrontab;\n access ncs->;\n\n spc = [ \\t];\n eqsep = spc+ '=' spc+;\n cmdterm = [\\0\\n];\n\n action TUnitSt { ncs->time_st = p; ncs->v_time = 0; }\n action TSecEn { ncs->v_time += atoi(ncs->time_st); }\n action TMinEn { ncs->v_time += 60 * atoi(ncs->time_st); }\n action THrEn { ncs->v_time += 3600 * atoi(ncs->time_st); }\n action TDayEn { ncs->v_time += 86400 * atoi(ncs->time_st); }\n action TWeekEn { ncs->v_time += 604800 * atoi(ncs->time_st); }\n\n action IntValSt {\n ncs->intv_st = p;\n ncs->v_int = ncs->v_int2 = 0;\n ncs->intv2_exist = false;\n }\n action IntValEn { ncs->v_int = atoi(ncs->intv_st); }\n action IntVal2St { ncs->intv2_st = p; }\n action IntVal2En {\n ncs->v_int2 = atoi(ncs->intv2_st);\n ncs->intv2_exist = true;\n }\n\n action StrValSt { ncs->strv_st = p; ncs->v_strlen = 0; }\n action StrValEn {\n ncs->v_strlen = p - ncs->strv_st;\n if (ncs->v_strlen <= INT_MAX) {\n ssize_t snl = snprintf(ncs->v_str, sizeof ncs->v_str,\n \"%.*s\", (int)ncs->v_strlen, ncs->strv_st);\n if (snl < 0 || (size_t)snl >= sizeof ncs->v_str)\n suicide(\"error parsing line %u in crontab; too long?\",\n ncs->linenum);\n }\n }\n\n t_sec = (digit+ > TUnitSt) 's' % TSecEn;\n t_min = (digit+ > TUnitSt) 'm' % TMinEn;\n t_hr = (digit+ > TUnitSt) 'h' % THrEn;\n t_day = (digit+ > TUnitSt) 'd' % TDayEn;\n t_week = (digit+ > TUnitSt) 'w' % TWeekEn;\n t_any = (t_sec | t_min | t_hr | t_day | t_week);\n\n intval = (digit+ > IntValSt % IntValEn) cmdterm;\n timeval = t_any (spc* t_any)* cmdterm;\n intrangeval = (digit+ > IntValSt % IntValEn)\n (',' (digit+ > IntVal2St % IntVal2En))? cmdterm;\n stringval = ([^\\0\\n]+ > StrValSt % StrValEn) cmdterm;\n\n action JournalEn { ncs->ce->journal = 1; }\n action NoExecTimeEn { ncs->noextime = 1; }\n\n journal = 'journal'i cmdterm % JournalEn;\n noexectime = 'noexectime'i cmdterm % NoExecTimeEn;\n\n action RunAtEn {\n ncs->ce->exectime = ncs->v_int;\n ncs->ce->maxruns = 1;\n ncs->ce->journal = 1;\n }\n action MaxRunsEn {\n if (ncs->ce->exectime == 0)\n ncs->ce->maxruns = ncs->v_int;\n }\n\n runat = 'runat'i eqsep intval % RunAtEn;\n maxruns = 'maxruns'i eqsep intval % MaxRunsEn;\n\n action LimAsEn { setlim(ncs, RLIMIT_AS); }\n action LimMemlockEn { setlim(ncs, RLIMIT_MEMLOCK); }\n action LimNofileEn { setlim(ncs, RLIMIT_NOFILE); }\n action LimNprocEn { setlim(ncs, RLIMIT_NPROC); }\n action LimRssEn { setlim(ncs, RLIMIT_RSS); }\n action LimCoreEn { setlim(ncs, RLIMIT_CORE); }\n action LimStackEn { setlim(ncs, RLIMIT_STACK); }\n action LimDataEn { setlim(ncs, RLIMIT_DATA); }\n action LimFsizeEn { setlim(ncs, RLIMIT_FSIZE); }\n action LimCpuEn { setlim(ncs, RLIMIT_CPU); }\n\n lim_as = 'l_as'i eqsep intrangeval % LimAsEn;\n lim_memlock = 'l_memlock'i eqsep intrangeval % LimMemlockEn;\n lim_nofile = 'l_nofile'i eqsep intrangeval % LimNofileEn;\n lim_nproc = 'l_nproc'i eqsep intrangeval % LimNprocEn;\n lim_rss = 'l_rss'i eqsep intrangeval % LimRssEn;\n lim_core = 'l_core'i eqsep intrangeval % LimCoreEn;\n lim_stack = 'l_stack'i eqsep intrangeval % LimStackEn;\n lim_data = 'l_data'i eqsep intrangeval % LimDataEn;\n lim_fsize = 'l_fsize'i eqsep intrangeval % LimFsizeEn;\n lim_cpu = 'l_cpu'i eqsep intrangeval % LimCpuEn;\n\n action IntervalEn { ncs->ce->interval = ncs->v_time; }\n\n interval = 'interval'i eqsep timeval % IntervalEn;\n\n action MonthEn { addipairlist(ncs, &ncs->ce->month, 0, 1, 12); }\n action DayEn { addipairlist(ncs, &ncs->ce->day, 0, 1, 31); }\n action WeekdayEn { addipairlist(ncs, &ncs->ce->weekday, 0, 1, 7); }\n action HourEn { addipairlist(ncs, &ncs->ce->hour, 24, 0, 23); }\n action MinuteEn { addipairlist(ncs, &ncs->ce->minute, 60, 0, 59); }\n\n month = 'month'i eqsep intrangeval % MonthEn;\n day = 'day'i eqsep intrangeval % DayEn;\n weekday = 'weekday'i eqsep intrangeval % WeekdayEn;\n hour = 'hour'i eqsep intrangeval % HourEn;\n minute = 'minute'i eqsep intrangeval % MinuteEn;\n\n action GroupEn { setgroupv(ncs); }\n action UserEn { setuserv(ncs); }\n action ChrootEn {\n parse_assign_str(&ncs->ce->chroot, ncs->v_str, ncs->v_strlen,\n ncs->linenum);\n }\n action CommandEn { parse_command_key(ncs); }\n\n group = 'group'i eqsep stringval % GroupEn;\n user = 'user'i eqsep stringval % UserEn;\n chroot = 'chroot'i eqsep stringval % ChrootEn;\n command = 'command'i eqsep stringval % CommandEn;\n\n cmds = command | chroot | user | group | minute | hour | weekday | day |\n month | interval | lim_cpu | lim_fsize | lim_data | lim_stack |\n lim_core | lim_rss | lim_nproc | lim_nofile | lim_memlock | lim_as |\n maxruns | runat | noexectime | journal;\n\n action JobIdSt { ncs->jobid_st = p; }\n action JobIdEn { ncs->v_jobid = atoi(ncs->jobid_st); }\n action CreateCe { finish_ce(ncs); create_ce(ncs); }\n\n jobid = ('!' > CreateCe) (digit+ > JobIdSt) cmdterm % JobIdEn;\n\n main := jobid | cmds;\n}%%\n\n%% write data;\n\nstatic int do_parse_config(struct ParseCfgState *ncs, char *data, size_t len)\n{\n char *p = data;\n const char *pe = data + len;\n const char *eof = pe;\n\n %% write init;\n %% write exec;\n\n if (ncs->cs == ncrontab_error)\n return -1;\n if (ncs->cs >= ncrontab_first_final)\n return 1;\n return 0;\n}\n\nvoid parse_config(char *path, char *execfile, cronentry_t **stk,\n cronentry_t **deadstk)\n{\n char buf[MAXLINE];\n struct ParseCfgState ncs;\n memset(&ncs, 0, sizeof ncs);\n ncs.execfile = execfile;\n ncs.stack = *stk;\n ncs.deadstack = *deadstk;\n\n FILE *f = fopen(path, \"r\");\n if (!f)\n suicide(\"%s: fopen(%s) failed: %s\", __func__, path, strerror(errno));\n\n while (++ncs.linenum, fgets(buf, sizeof buf, f)) {\n int r = do_parse_config(&ncs, buf, strlen(buf));\n if (r < 0)\n suicide(\"%s: do_parse_config(%s) failed\", __func__, path);\n if (r == 1)\n break;\n }\n if (fclose(f))\n suicide(\"%s: fclose(%s) failed: %s\", __func__, path, strerror(errno));\n\n *stk = ncs.stack;\n *deadstk = ncs.deadstack;\n if (ncs.ce)\n free_cronentry(&ncs.ce); \/\/ Free partially built unused item.\n cfg_reload = 1;\n}\n\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"b7771ed5fe4b82ad72d255444f87f5e51638af7d","subject":"Patch to Oga Upstream to fix \"Oga Parser doesn't handle dots in XML Tags\". Fixes rubyjedi\/soap4r#7","message":"Patch to Oga Upstream to fix \"Oga Parser doesn't handle dots in XML Tags\". Fixes rubyjedi\/soap4r#7\n","repos":"ttasanen\/oga,altmetric\/oga,YorickPeterse\/oga,dfockler\/oga,dfockler\/oga,YorickPeterse\/oga,ttasanen\/oga,YorickPeterse\/oga,ttasanen\/oga,YorickPeterse\/oga,dfockler\/oga,altmetric\/oga,dfockler\/oga,ttasanen\/oga,YorickPeterse\/oga,dfockler\/oga,altmetric\/oga,altmetric\/oga,altmetric\/oga,ttasanen\/oga","old_file":"ext\/ragel\/base_lexer.rl","new_file":"ext\/ragel\/base_lexer.rl","new_contents":"%%machine base_lexer;\n\n%%{\n ##\n # Base grammar for the XML lexer.\n #\n # This grammar is shared between the C and Java extensions. As a result of\n # this you should **not** include language specific code in Ragel\n # actions\/callbacks.\n #\n # To call back in to Ruby you can use one of the following two functions:\n #\n # * callback\n # * callback_simple\n #\n # The first function takes 5 arguments:\n #\n # * The name of the Ruby method to call.\n # * The input data.\n # * The encoding of the input data.\n # * The start of the current buffer.\n # * The end of the current buffer.\n #\n # The function callback_simple only takes one argument: the name of the\n # method to call. This function should be used for callbacks that don't\n # require any values.\n #\n # When you call a method in Ruby make sure that said method is defined as\n # an instance method in the `Oga::XML::Lexer` class.\n #\n # The name of the callback to invoke should be an identifier starting with\n # \"id_\". The identifier should be defined in the associated C and Java code.\n # In case of C code its value should be a Symbol as a ID object, for Java\n # it should be a String. For example:\n #\n # ID id_foo = rb_intern(\"foo\");\n #\n # And for Java:\n #\n # String id_foo = \"foo\";\n #\n # ## Machine Transitions\n #\n # To transition from one machine to another always use `fnext` instead of\n # `fcall` and `fret`. This removes the need for the code to keep track of a\n # stack.\n #\n\n newline = '\\r\\n' | '\\n' | '\\r';\n whitespace = [ \\t];\n ident_char = [a-zA-Z0-9\\-_\\.];\n identifier = ident_char+;\n\n whitespace_or_newline = whitespace | newline;\n\n action count_newlines {\n if ( fc == '\\n' ) lines++;\n }\n\n action advance_newline {\n advance_line(1);\n }\n\n action hold_and_return {\n fhold;\n fret;\n }\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#comments\n #\n # Unlike the W3C specification these rules *do* allow character sequences\n # such as `--` and `->`. Putting extra checks in for these sequences would\n # actually make the rules\/actions more complex.\n #\n\n comment_start = '';\n\n # Everything except \"-\" OR a single \"-\"\n comment_allowed = (^'-'+ | '-') $count_newlines;\n\n action start_comment {\n callback_simple(id_on_comment_start);\n\n fnext comment_body;\n }\n\n comment_body := |*\n comment_allowed => {\n callback(id_on_comment_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n comment_end => {\n callback_simple(id_on_comment_end);\n\n fnext main;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n\n cdata_start = '';\n\n # Everything except \"]\" OR a single \"]\"\n cdata_allowed = (^']'+ | ']') $count_newlines;\n\n action start_cdata {\n callback_simple(id_on_cdata_start);\n\n fnext cdata_body;\n }\n\n cdata_body := |*\n cdata_allowed => {\n callback(id_on_cdata_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n cdata_end => {\n callback_simple(id_on_cdata_end);\n\n fnext main;\n };\n *|;\n\n # Processing Instructions\n #\n # http:\/\/www.w3.org\/TR\/xpath\/#section-Processing-Instruction-Nodes\n # http:\/\/en.wikipedia.org\/wiki\/Processing_Instruction\n #\n # These are tags meant to be used by parsers\/libraries for custom behaviour.\n # One example are the tags used by PHP: . Note that the XML\n # declaration tags () are not considered to be a processing\n # instruction.\n #\n\n proc_ins_start = '';\n\n # Everything except \"?\" OR a single \"?\"\n proc_ins_allowed = (^'?'+ | '?') $count_newlines;\n\n action start_proc_ins {\n callback_simple(id_on_proc_ins_start);\n callback(id_on_proc_ins_name, data, encoding, ts + 2, te);\n\n fnext proc_ins_body;\n }\n\n proc_ins_body := |*\n proc_ins_allowed => {\n callback(id_on_proc_ins_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n proc_ins_end => {\n callback_simple(id_on_proc_ins_end);\n\n fnext main;\n };\n *|;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n action emit_string {\n callback(id_on_string_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n }\n\n action start_string_squote {\n callback_simple(id_on_string_squote);\n\n fcall string_squote;\n }\n\n action start_string_dquote {\n callback_simple(id_on_string_dquote);\n\n fcall string_dquote;\n }\n\n string_squote := |*\n ^squote* $count_newlines => emit_string;\n\n squote => {\n callback_simple(id_on_string_squote);\n\n fret;\n };\n *|;\n\n string_dquote := |*\n ^dquote* $count_newlines => emit_string;\n\n dquote => {\n callback_simple(id_on_string_dquote);\n\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#the-doctype\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext doctype;\n }\n\n # Machine for processing inline rules of a doctype.\n doctype_inline := |*\n ^']'* $count_newlines => {\n callback(id_on_doctype_inline, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n ']' => { fnext doctype; };\n *|;\n\n # Machine for processing doctypes. Doctype values such as the public\n # and system IDs are treated as T_STRING tokens.\n doctype := |*\n 'PUBLIC' | 'SYSTEM' => {\n callback(id_on_doctype_type, data, encoding, ts, te);\n };\n\n # Starts a set of inline doctype rules.\n '[' => { fnext doctype_inline; };\n\n # Lex the public\/system IDs as regular strings.\n squote => start_string_squote;\n dquote => start_string_dquote;\n\n identifier => {\n callback(id_on_doctype_name, data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(id_on_doctype_end);\n fnext main;\n };\n\n newline => advance_newline;\n\n whitespace;\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(id_on_xml_decl_start);\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n callback_simple(id_on_xml_decl_end);\n\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n callback(id_on_attribute, data, encoding, ts, te);\n };\n\n squote => start_string_squote;\n dquote => start_string_dquote;\n\n any $count_newlines;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n\n action start_element {\n fhold;\n fnext element_name;\n }\n\n action start_close_element {\n fnext element_close;\n }\n\n action close_element {\n callback(id_on_element_end, data, encoding, ts, te);\n }\n\n action close_element_fnext_main {\n callback_simple(id_on_element_end);\n\n fnext main;\n }\n\n element_start = '<' ident_char;\n element_end = '<\/';\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(id_on_element_ns, data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(id_on_element_name, data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for lexing the closing tag of an element\n element_close := |*\n # namespace prefixes, currently not used but allows the rule below it\n # to be used for the actual element name.\n identifier ':';\n\n identifier => close_element;\n\n '>' => {\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext main;\n };\n\n any $count_newlines;\n *|;\n\n # Machine used after matching the \"=\" of an attribute and just before moving\n # into the actual attribute value.\n attribute_pre := |*\n whitespace_or_newline $count_newlines;\n\n squote | dquote => {\n fhold;\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext quoted_attribute_value;\n };\n\n any => {\n fhold;\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n if ( html_p )\n {\n fnext unquoted_attribute_value;\n }\n \/* XML doesn't support unquoted attribute values *\/\n else\n {\n fret;\n }\n };\n *|;\n\n # Machine for processing unquoted HTML attribute values.\n #\n # The HTML specification describes a set of characters that can be allowed\n # in an unquoted value at https:\/\/html.spec.whatwg.org\/multipage\/introduction.html#intro-early-example.\n #\n # As is always the case with HTML everybody completely ignores this\n # specification and thus every library and browser out these is expected to\n # support input such as `<\/a>.\n #\n # Oga too has to support this, thus the only characters it disallows in\n # unquoted attribute values are:\n #\n # * > (used for terminating open tags)\n # * whitespace\n #\n unquoted_attribute_value := |*\n ^('>' | whitespace_or_newline)+ => {\n callback_simple(id_on_string_squote);\n\n callback(id_on_string_body, data, encoding, ts, te);\n\n callback_simple(id_on_string_squote);\n };\n\n any => hold_and_return;\n *|;\n\n # Machine used for processing quoted XML\/HTML attribute values.\n quoted_attribute_value := |*\n # The following two actions use \"fnext\" instead of \"fcall\". Combined\n # with \"element_head\" using \"fcall\" to jump to this machine this means\n # we can return back to \"element_head\" after processing a single string.\n squote => {\n callback_simple(id_on_string_squote);\n\n fnext string_squote;\n };\n\n dquote => {\n callback_simple(id_on_string_dquote);\n\n fnext string_dquote;\n };\n\n any => hold_and_return;\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n newline => advance_newline;\n\n # Attribute names and namespaces.\n identifier ':' => {\n callback(id_on_attribute_ns, data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(id_on_attribute, data, encoding, ts, te);\n };\n\n # Attribute values.\n '=' => {\n fcall attribute_pre;\n };\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(id_on_element_open_end);\n\n if ( html_script_p() )\n {\n fnext html_script;\n }\n else if ( html_style_p() )\n {\n fnext html_style;\n }\n else\n {\n fnext main;\n }\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(id_on_element_end);\n fnext main;\n };\n\n any;\n *|;\n\n # Text\n #\n # http:\/\/www.w3.org\/TR\/xml\/#syntax\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#text\n #\n # Text content is everything leading up to certain special tags such as \"<\/\"\n # and \" 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n }\n\n text := |*\n terminate_text | allowed_text => {\n callback(id_on_text, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext main;\n };\n\n # Text followed by a special tag, such as \"foo';\n\n # Everything except \"-\" OR a single \"-\"\n comment_allowed = (^'-'+ | '-') $count_newlines;\n\n action start_comment {\n callback_simple(id_on_comment_start);\n\n fnext comment_body;\n }\n\n comment_body := |*\n comment_allowed => {\n callback(id_on_comment_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n comment_end => {\n callback_simple(id_on_comment_end);\n\n fnext main;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#cdata-sections\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n\n cdata_start = '';\n\n # Everything except \"]\" OR a single \"]\"\n cdata_allowed = (^']'+ | ']') $count_newlines;\n\n action start_cdata {\n callback_simple(id_on_cdata_start);\n\n fnext cdata_body;\n }\n\n cdata_body := |*\n cdata_allowed => {\n callback(id_on_cdata_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n cdata_end => {\n callback_simple(id_on_cdata_end);\n\n fnext main;\n };\n *|;\n\n # Processing Instructions\n #\n # http:\/\/www.w3.org\/TR\/xpath\/#section-Processing-Instruction-Nodes\n # http:\/\/en.wikipedia.org\/wiki\/Processing_Instruction\n #\n # These are tags meant to be used by parsers\/libraries for custom behaviour.\n # One example are the tags used by PHP: . Note that the XML\n # declaration tags () are not considered to be a processing\n # instruction.\n #\n\n proc_ins_start = '';\n\n # Everything except \"?\" OR a single \"?\"\n proc_ins_allowed = (^'?'+ | '?') $count_newlines;\n\n action start_proc_ins {\n callback_simple(id_on_proc_ins_start);\n callback(id_on_proc_ins_name, data, encoding, ts + 2, te);\n\n fnext proc_ins_body;\n }\n\n proc_ins_body := |*\n proc_ins_allowed => {\n callback(id_on_proc_ins_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n proc_ins_end => {\n callback_simple(id_on_proc_ins_end);\n\n fnext main;\n };\n *|;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n #\n dquote = '\"';\n squote = \"'\";\n\n action emit_string {\n callback(id_on_string_body, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n }\n\n action start_string_squote {\n callback_simple(id_on_string_squote);\n\n fcall string_squote;\n }\n\n action start_string_dquote {\n callback_simple(id_on_string_dquote);\n\n fcall string_dquote;\n }\n\n string_squote := |*\n ^squote* $count_newlines => emit_string;\n\n squote => {\n callback_simple(id_on_string_squote);\n\n fret;\n };\n *|;\n\n string_dquote := |*\n ^dquote* $count_newlines => emit_string;\n\n dquote => {\n callback_simple(id_on_string_dquote);\n\n fret;\n };\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#the-doctype\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext doctype;\n }\n\n # Machine for processing inline rules of a doctype.\n doctype_inline := |*\n ^']'* $count_newlines => {\n callback(id_on_doctype_inline, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n };\n\n ']' => { fnext doctype; };\n *|;\n\n # Machine for processing doctypes. Doctype values such as the public\n # and system IDs are treated as T_STRING tokens.\n doctype := |*\n 'PUBLIC' | 'SYSTEM' => {\n callback(id_on_doctype_type, data, encoding, ts, te);\n };\n\n # Starts a set of inline doctype rules.\n '[' => { fnext doctype_inline; };\n\n # Lex the public\/system IDs as regular strings.\n squote => start_string_squote;\n dquote => start_string_dquote;\n\n identifier => {\n callback(id_on_doctype_name, data, encoding, ts, te);\n };\n\n '>' => {\n callback_simple(id_on_doctype_end);\n fnext main;\n };\n\n newline => advance_newline;\n\n whitespace;\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n callback_simple(id_on_xml_decl_start);\n fnext xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n callback_simple(id_on_xml_decl_end);\n\n fnext main;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => {\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n callback(id_on_attribute, data, encoding, ts, te);\n };\n\n squote => start_string_squote;\n dquote => start_string_dquote;\n\n any $count_newlines;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#syntax-elements\n #\n # Lexing of elements is broken up into different machines that handle the\n # name\/namespace, contents of the open tag and the body of an element. The\n # body of an element is lexed using the `main` machine.\n #\n\n action start_element {\n fhold;\n fnext element_name;\n }\n\n action start_close_element {\n fnext element_close;\n }\n\n action close_element {\n callback(id_on_element_end, data, encoding, ts, te);\n }\n\n action close_element_fnext_main {\n callback_simple(id_on_element_end);\n\n fnext main;\n }\n\n element_start = '<' ident_char;\n element_end = '<\/';\n\n # Machine used for lexing the name\/namespace of an element.\n element_name := |*\n identifier ':' => {\n callback(id_on_element_ns, data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(id_on_element_name, data, encoding, ts, te);\n fnext element_head;\n };\n *|;\n\n # Machine used for lexing the closing tag of an element\n element_close := |*\n # namespace prefixes, currently not used but allows the rule below it\n # to be used for the actual element name.\n identifier ':';\n\n identifier => close_element;\n\n '>' => {\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext main;\n };\n\n any $count_newlines;\n *|;\n\n # Machine used after matching the \"=\" of an attribute and just before moving\n # into the actual attribute value.\n attribute_pre := |*\n whitespace_or_newline $count_newlines;\n\n squote | dquote => {\n fhold;\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext quoted_attribute_value;\n };\n\n any => {\n fhold;\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n if ( html_p )\n {\n fnext unquoted_attribute_value;\n }\n \/* XML doesn't support unquoted attribute values *\/\n else\n {\n fret;\n }\n };\n *|;\n\n # Machine for processing unquoted HTML attribute values.\n #\n # The HTML specification describes a set of characters that can be allowed\n # in an unquoted value at https:\/\/html.spec.whatwg.org\/multipage\/introduction.html#intro-early-example.\n #\n # As is always the case with HTML everybody completely ignores this\n # specification and thus every library and browser out these is expected to\n # support input such as `<\/a>.\n #\n # Oga too has to support this, thus the only characters it disallows in\n # unquoted attribute values are:\n #\n # * > (used for terminating open tags)\n # * whitespace\n #\n unquoted_attribute_value := |*\n ^('>' | whitespace_or_newline)+ => {\n callback_simple(id_on_string_squote);\n\n callback(id_on_string_body, data, encoding, ts, te);\n\n callback_simple(id_on_string_squote);\n };\n\n any => hold_and_return;\n *|;\n\n # Machine used for processing quoted XML\/HTML attribute values.\n quoted_attribute_value := |*\n # The following two actions use \"fnext\" instead of \"fcall\". Combined\n # with \"element_head\" using \"fcall\" to jump to this machine this means\n # we can return back to \"element_head\" after processing a single string.\n squote => {\n callback_simple(id_on_string_squote);\n\n fnext string_squote;\n };\n\n dquote => {\n callback_simple(id_on_string_dquote);\n\n fnext string_dquote;\n };\n\n any => hold_and_return;\n *|;\n\n # Machine used for processing the contents of an element's starting tag.\n # This includes the name, namespace and attributes.\n element_head := |*\n newline => advance_newline;\n\n # Attribute names and namespaces.\n identifier ':' => {\n callback(id_on_attribute_ns, data, encoding, ts, te - 1);\n };\n\n identifier => {\n callback(id_on_attribute, data, encoding, ts, te);\n };\n\n # Attribute values.\n '=' => {\n fcall attribute_pre;\n };\n\n # We're done with the open tag of the element.\n '>' => {\n callback_simple(id_on_element_open_end);\n\n if ( html_script_p() )\n {\n fnext html_script;\n }\n else if ( html_style_p() )\n {\n fnext html_style;\n }\n else\n {\n fnext main;\n }\n };\n\n # Self closing tags.\n '\/>' => {\n callback_simple(id_on_element_end);\n fnext main;\n };\n\n any;\n *|;\n\n # Text\n #\n # http:\/\/www.w3.org\/TR\/xml\/#syntax\n # http:\/\/www.w3.org\/TR\/html\/syntax.html#text\n #\n # Text content is everything leading up to certain special tags such as \"<\/\"\n # and \" 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n }\n\n text := |*\n terminate_text | allowed_text => {\n callback(id_on_text, data, encoding, ts, te);\n\n if ( lines > 0 )\n {\n advance_line(lines);\n\n lines = 0;\n }\n\n fnext main;\n };\n\n # Text followed by a special tag, such as \"foo';\n\n action start_comment {\n emit_buffer(ts)\n add_token(:T_COMMENT_START)\n\n start_buffer(te)\n\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n comment_end => {\n emit_buffer(ts)\n add_token(:T_COMMENT_END)\n\n fret;\n };\n\n any;\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n emit_buffer(ts)\n add_token(:T_XML_DECL_START)\n\n start_buffer(te)\n\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n emit_buffer(ts)\n add_token(:T_XML_DECL_END)\n\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => { emit(:T_ATTR, ts, te) };\n\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n emit_buffer(ts)\n add_token(:T_ELEM_START)\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(ts + 1, te)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n end\n\n @elements << name if html?\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => { advance_line };\n\n # Attribute names.\n identifier => { emit(:T_ATTR, ts, te) };\n\n # Attribute values.\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_END, nil)\n @elements.pop\n end\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n emit_buffer(ts)\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n any => {\n # First character, start buffering (unless we already are buffering).\n start_buffer(ts) unless @buffer_start_position\n\n # EOF, emit the text buffer.\n if te == eof\n emit_buffer(te)\n end\n };\n *|;\n }%%\n end # Lexer\n end # XML\nend # Oga\n","old_contents":"%%machine lexer; # %\n\nmodule Oga\n module XML\n ##\n # Low level lexer that supports both XML and HTML (using an extra option).\n # To lex HTML input set the `:html` option to `true` when creating an\n # instance of the lexer:\n #\n # lexer = Oga::XML::Lexer.new(:html => true)\n #\n # @!attribute [r] html\n # @return [TrueClass|FalseClass]\n #\n # @!attribute [r] tokens\n # @return [Array]\n #\n class Lexer\n %% write data;\n\n # % fix highlight\n\n attr_reader :html\n\n ##\n # Names of the HTML void elements that should be handled when HTML lexing\n # is enabled.\n #\n # @return [Set]\n #\n HTML_VOID_ELEMENTS = Set.new([\n 'area',\n 'base',\n 'br',\n 'col',\n 'command',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n ])\n\n ##\n # @param [String] data The data to lex.\n #\n # @param [Hash] options\n #\n # @option options [Symbol] :html When set to `true` the lexer will treat\n # the input as HTML instead of SGML\/XML. This makes it possible to lex\n # HTML void elements such as ``.\n #\n def initialize(data, options = {})\n options.each do |key, value|\n instance_variable_set(\"@#{key}\", value) if respond_to?(key)\n end\n\n @data = data\n\n reset\n end\n\n ##\n # Resets the internal state of the lexer. Typically you don't need to\n # call this method yourself as its called by #lex after lexing a given\n # String.\n #\n def reset\n @line = 1\n @elements = []\n\n @buffer_start_position = nil\n end\n\n ##\n # Gathers all the tokens for the input and returns them as an Array.\n #\n # This method resets the internal state of the lexer after consuming the\n # input.\n #\n # @param [String] data The string to consume.\n # @return [Array]\n # @see #advance\n #\n def lex\n tokens = []\n\n advance do |token|\n tokens << token\n end\n\n reset\n\n return tokens\n end\n\n ##\n # Advances through the input and generates the corresponding tokens. Each\n # token is yielded to the supplied block.\n #\n # Each token is an Array in the following format:\n #\n # [TYPE, VALUE]\n #\n # The type is a symbol, the value is either nil or a String.\n #\n # This method stores the supplied block in `@block` and resets it after\n # the lexer loop has finished.\n #\n # This method does *not* reset the internal state of the lexer.\n #\n #\n # @param [String] data The String to consume.\n # @return [Array]\n #\n def advance(&block)\n @block = block\n\n data = @data\n ts = nil\n te = nil\n stack = []\n top = 0\n cs = self.class.lexer_start\n act = 0\n eof = @data.bytesize\n p = 0\n pe = eof\n\n _lexer_eof_trans = self.class.send(:_lexer_eof_trans)\n _lexer_from_state_actions = self.class.send(:_lexer_from_state_actions)\n _lexer_index_offsets = self.class.send(:_lexer_index_offsets)\n _lexer_indicies = self.class.send(:_lexer_indicies)\n _lexer_key_spans = self.class.send(:_lexer_key_spans)\n _lexer_to_state_actions = self.class.send(:_lexer_to_state_actions)\n _lexer_trans_actions = self.class.send(:_lexer_trans_actions)\n _lexer_trans_keys = self.class.send(:_lexer_trans_keys)\n _lexer_trans_targs = self.class.send(:_lexer_trans_targs)\n\n %% write exec;\n\n # % fix highlight\n ensure\n @block = nil\n end\n\n ##\n # @return [TrueClass|FalseClass]\n #\n def html?\n return !!html\n end\n\n private\n\n ##\n # @param [Fixnum] amount The amount of lines to advance.\n #\n def advance_line(amount = 1)\n @line += amount\n end\n\n ##\n # Emits a token who's value is based on the supplied start\/stop position.\n #\n # @param [Symbol] type The token type.\n # @param [Fixnum] start\n # @param [Fixnum] stop\n #\n # @see #text\n # @see #add_token\n #\n def emit(type, start, stop)\n value = text(start, stop)\n\n add_token(type, value)\n end\n\n ##\n # Returns the text of the current buffer based on the supplied start and\n # stop position.\n #\n # @param [Fixnum] start\n # @param [Fixnum] stop\n # @return [String]\n #\n def text(start, stop)\n return @data.byteslice(start, stop - start)\n end\n\n ##\n # Adds a token with the given type and value to the list.\n #\n # @param [Symbol] type The token type.\n # @param [String] value The token value.\n #\n def add_token(type, value = nil)\n token = [type, value, @line]\n\n @block.call(token)\n end\n\n ##\n # Enables buffering starting at the given position.\n #\n # @param [Fixnum] position The start position of the buffer.\n #\n def start_buffer(position)\n @buffer_start_position = position\n end\n\n ##\n # Returns `true` if we're currently buffering.\n #\n # @return [TrueClass|FalseClass]\n #\n def buffering?\n return !!@buffer_start_position\n end\n\n ##\n # Emits the current buffer if we have any. The current line number is\n # advanced based on the amount of newlines in the buffer.\n #\n # @param [Fixnum] position The end position of the buffer.\n # @param [Symbol] type The type of node to emit.\n #\n def emit_buffer(position, type = :T_TEXT)\n return unless @buffer_start_position\n\n content = text(@buffer_start_position, position)\n\n unless content.empty?\n add_token(type, content)\n\n lines = content.count(\"\\n\")\n\n advance_line(lines) if lines > 0\n end\n\n @buffer_start_position = nil\n end\n\n ##\n # Returns the name of the element we're currently in.\n #\n # @return [String]\n #\n def current_element\n return @elements.last\n end\n\n %%{\n getkey (data.getbyte(p) || 0);\n\n newline = '\\n' | '\\r\\n';\n whitespace = [ \\t];\n identifier = [a-zA-Z0-9\\-_:]+;\n\n # Strings\n #\n # Strings in HTML can either be single or double quoted. If a string\n # starts with one of these quotes it must be closed with the same type\n # of quote.\n dquote = '\"';\n squote = \"'\";\n\n action start_string_dquote {\n start_buffer(te)\n\n fcall string_dquote;\n }\n\n action start_string_squote {\n start_buffer(te)\n\n fcall string_squote;\n }\n\n # Machine for processing double quoted strings.\n string_dquote := |*\n dquote => {\n emit_buffer(ts, :T_STRING)\n fret;\n };\n\n any;\n *|;\n\n # Machine for processing single quoted strings.\n string_squote := |*\n squote => {\n emit_buffer(ts, :T_STRING)\n fret;\n };\n\n any;\n *|;\n\n # DOCTYPES\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#doctype-syntax\n #\n # These rules support the 3 flavours of doctypes:\n #\n # 1. Normal doctypes, as introduced in the HTML5 specification.\n # 2. Deprecated doctypes, the more verbose ones used prior to HTML5.\n # 3. Legacy doctypes\n #\n doctype_start = ' { emit(:T_DOCTYPE_TYPE, ts, te) };\n\n # Lex the public\/system IDs as regular strings.\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n # Whitespace inside doctypes is ignored since there's no point in\n # including it.\n whitespace;\n\n identifier => { emit(:T_DOCTYPE_NAME, ts, te) };\n\n '>' => {\n add_token(:T_DOCTYPE_END)\n fret;\n };\n *|;\n\n # CDATA\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#cdata-sections\n #\n # CDATA tags are broken up into 3 parts: the start, the content and the\n # end tag.\n #\n # In HTML CDATA tags have no meaning\/are not supported. Oga does\n # support them but treats their contents as plain text.\n #\n cdata_start = '';\n\n action start_cdata {\n emit_buffer(ts)\n add_token(:T_CDATA_START)\n\n start_buffer(te)\n\n fcall cdata;\n }\n\n # Machine that for processing the contents of CDATA tags. Everything\n # inside a CDATA tag is treated as plain text.\n cdata := |*\n cdata_end => {\n emit_buffer(ts)\n add_token(:T_CDATA_END)\n\n fret;\n };\n\n any;\n *|;\n\n # Comments\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#comments\n #\n # Comments are lexed into 3 parts: the start tag, the content and the\n # end tag.\n #\n # Unlike the W3 specification these rules *do* allow character\n # sequences such as `--` and `->`. Putting extra checks in for these\n # sequences would actually make the rules\/actions more complex.\n #\n comment_start = '';\n\n action start_comment {\n emit_buffer(ts)\n add_token(:T_COMMENT_START)\n\n start_buffer(te)\n\n fcall comment;\n }\n\n # Machine used for processing the contents of a comment. Everything\n # inside a comment is treated as plain text (similar to CDATA tags).\n comment := |*\n comment_end => {\n emit_buffer(ts)\n add_token(:T_COMMENT_END)\n\n fret;\n };\n\n any;\n *|;\n\n # XML declaration tags\n #\n # http:\/\/www.w3.org\/TR\/REC-xml\/#sec-prolog-dtd\n #\n xml_decl_start = '';\n\n action start_xml_decl {\n emit_buffer(ts)\n add_token(:T_XML_DECL_START)\n\n start_buffer(te)\n\n fcall xml_decl;\n }\n\n # Machine that processes the contents of an XML declaration tag.\n xml_decl := |*\n xml_decl_end => {\n emit_buffer(ts)\n add_token(:T_XML_DECL_END)\n\n fret;\n };\n\n # Attributes and their values (e.g. version=\"1.0\").\n identifier => { emit(:T_ATTR, ts, te) };\n\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n any;\n *|;\n\n # Elements\n #\n # http:\/\/www.w3.org\/TR\/html-markup\/syntax.html#syntax-elements\n #\n\n # Action that creates the tokens for the opening tag, name and\n # namespace (if any). Remaining work is delegated to a dedicated\n # machine.\n action start_element {\n emit_buffer(ts)\n add_token(:T_ELEM_START)\n\n # Add the element name. If the name includes a namespace we'll break\n # the name up into two separate tokens.\n name = text(ts + 1, te)\n\n if name.include?(':')\n ns, name = name.split(':')\n\n add_token(:T_ELEM_NS, ns)\n end\n\n @elements << name if html?\n\n add_token(:T_ELEM_NAME, name)\n\n fcall element_head;\n }\n\n element_start = '<' identifier;\n\n # Machine used for processing the characters inside a element head. An\n # element head is everything between ``.\n #\n # For example, in `

` the element head is ` foo=\"bar\"`.\n #\n element_head := |*\n whitespace | '=';\n\n newline => { advance_line };\n\n # Attribute names.\n identifier => { emit(:T_ATTR, ts, te) };\n\n # Attribute values.\n dquote => start_string_dquote;\n squote => start_string_squote;\n\n # The closing character of the open tag.\n ('>' | '\/') => {\n fhold;\n fret;\n };\n *|;\n\n main := |*\n element_start => start_element;\n doctype_start => start_doctype;\n cdata_start => start_cdata;\n comment_start => start_comment;\n xml_decl_start => start_xml_decl;\n\n # Enter the body of the tag. If HTML mode is enabled and the current\n # element is a void element we'll close it and bail out.\n '>' => {\n if html? and HTML_VOID_ELEMENTS.include?(current_element)\n add_token(:T_ELEM_END, nil)\n @elements.pop\n end\n };\n\n # Regular closing tags.\n '<\/' identifier '>' => {\n emit_buffer(ts)\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Self closing elements that are not handled by the HTML mode.\n '\/>' => {\n add_token(:T_ELEM_END, nil)\n\n @elements.pop if html?\n };\n\n # Note that this rule should be declared at the very bottom as it\n # will otherwise take precedence over the other rules.\n any => {\n # First character, start buffering (unless we already are buffering).\n start_buffer(ts) unless buffering?\n\n # EOF, emit the text buffer.\n if te == eof\n emit_buffer(te)\n end\n };\n *|;\n }%%\n end # Lexer\n end # XML\nend # Oga\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Ragel in Ruby Host"} {"commit":"4f6bbcbf352a50740f7d169eb500bc4ae6e8e827","subject":"[jnc_edit] remove keyword 'alignment', add keyword 'pragma'","message":"[jnc_edit] remove keyword 'alignment', add keyword 'pragma'\n","repos":"vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy,vovkos\/jancy","old_file":"src\/jnc_edit\/jnc_Highlighter.rl","new_file":"src\/jnc_edit\/jnc_Highlighter.rl","new_contents":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n%%{\n\nmachine jancy_lexer;\nwrite data;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n';\nesc = '\\\\' [^\\n];\n\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* [\"\\\\]?;\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* ['\\\\]?;\nraw_lit_dq = '\"' [^\"\\n]* '\"'?;\nraw_lit_sq = \"'\" [^'\\n]* \"'\"?;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n(\n'import' |\n'namespace' |\n'extension' |\n'dynamiclib' |\n'using' |\n'friend' |\n'public' |\n'protected' |\n'pragma' |\n'setas' |\n\n'typedef' |\n'alias' |\n'static' |\n'threadlocal' |\n'stack' |\n'heap' |\n'abstract' |\n'virtual' |\n'override' |\n'mutable' |\n'disposable' |\n\n'signed' |\n'unsigned' |\n'bigendian' |\n'const' |\n'cmut' |\n'readonly' |\n'volatile' |\n'safe' |\n'unsafe' |\n'weak' |\n'thin' |\n'errorcode' |\n'cdecl' |\n'stdcall' |\n'thiscall' |\n'jnccall' |\n'array' |\n'function' |\n'property' |\n'bindable' |\n'autoget' |\n'indexed' |\n'multicast' |\n'event' |\n'reactor' |\n'async' |\n\n'anydata' |\n'void' |\n'variant' |\n'bool' |\n'int' |\n'intptr' |\n'char' |\n'short' |\n'long' |\n'float' |\n'double' |\n'enum' |\n'struct' |\n'union' |\n'class' |\n'opaque' |\n'exposed' |\n'bitflag' |\n\n'get' |\n'set' |\n'construct' |\n'destruct' |\n'operator' |\n'postfix' |\n\n'if' |\n'else' |\n'for' |\n'while' |\n'do' |\n'break' |\n'break' [1-9]? |\n'continue' [1-9]? |\n'return' |\n'switch' |\n'reswitch' |\n'case' |\n'default' |\n'once' |\n'onevent' |\n'try' |\n'throw' |\n'catch' |\n'finally' |\n'nestedscope' |\n'assert' |\n'await' |\n\n'basetype' [1-9]? |\n'this' |\n'true' |\n'false' |\n'null' |\n\n'new' |\n'delete' |\n'sizeof' |\n'countof' |\n'offsetof' |\n'typeof' |\n'bindingof' |\n'dynamic'\n) { highlightLastToken(Color_Keyword); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\nid ;\n\n(\nlit_dq |\nlit_sq |\n[rR] raw_lit_sq |\n[rR] raw_lit_dq |\ndec+ |\n'0' oct+ |\n'0' [xX] hex+ |\n'0' [oO] oct+ |\n'0' [bB] bin+ |\n'0' [nNdD] dec+ |\n'0' [xXoObBnNdD] raw_lit_dq |\ndec+ (('.' dec*) | ([eE] [+\\-]? dec+)) |\n[$fF] lit_dq\n) { highlightLastToken(Color_Constant); };\n\n('0' [xXoObBnNdD])? '\"\"\"'\n { highlightLastToken(Color_Constant); fgoto lit_ml; };\n\n'\/\/' any* { highlightLastToken(Color_Comment); setCurrentBlockState(BlockState_CommentSl); };\n'\/*' { highlightLastToken(Color_Comment); fgoto comment_ml; };\n\nws | nl ;\nany ;\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# comment machine\n#\n\ncomment_ml := |*\n\nany* :>> '*\/'? { highlightLastToken(Color_Comment); if (isTokenSuffix(\"*\/\", 2)) fgoto main; };\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\nany* :>> '\"\"\"'? { highlightLastToken(Color_Constant); if (isTokenSuffix(\"\\\"\\\"\\\"\", 3)) fgoto main; };\n\n*|;\n\n}%%\n\nnamespace jnc {\n\n\/\/..............................................................................\n\nvoid\nJancyHighlighter::init()\n{\n\t%% write init;\n}\n\nvoid\nJancyHighlighter::exec()\n{\n\tint prevBlockState = previousBlockState();\n\tswitch (prevBlockState)\n\t{\n\tcase BlockState_CommentMl:\n\t\tcs = jancy_lexer_en_comment_ml;\n\t\tbreak;\n\n\tcase BlockState_LitMl:\n\t\tcs = jancy_lexer_en_lit_ml;\n\t\tbreak;\n\t}\n\n\tsetCurrentBlockState(BlockState_Normal);\n\n\t%% write exec;\n\n\tswitch (cs)\n\t{\n\tcase jancy_lexer_en_comment_ml:\n\t\tsetCurrentBlockState(BlockState_CommentMl);\n\t\tbreak;\n\n\tcase jancy_lexer_en_lit_ml:\n\t\tsetCurrentBlockState(BlockState_LitMl);\n\t\tbreak;\n\t}\n}\n\n\/\/..............................................................................\n\n} \/\/ namespace jnc\n","old_contents":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n%%{\n\nmachine jancy_lexer;\nwrite data;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# standard definitions\n#\n\ndec = [0-9];\nhex = [0-9a-fA-F];\noct = [0-7];\nbin = [01];\nid = [_a-zA-Z] [_a-zA-Z0-9]*;\nws = [ \\t\\r]+;\nnl = '\\n';\nesc = '\\\\' [^\\n];\n\nlit_dq = '\"' ([^\"\\n\\\\] | esc)* [\"\\\\]?;\nlit_sq = \"'\" ([^'\\n\\\\] | esc)* ['\\\\]?;\nraw_lit_dq = '\"' [^\"\\n]* '\"'?;\nraw_lit_sq = \"'\" [^'\\n]* \"'\"?;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# main machine\n#\n\nmain := |*\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n(\n'import' |\n'namespace' |\n'extension' |\n'dynamiclib' |\n'using' |\n'friend' |\n'public' |\n'protected' |\n'alignment' |\n'setas' |\n\n'typedef' |\n'alias' |\n'static' |\n'threadlocal' |\n'stack' |\n'heap' |\n'abstract' |\n'virtual' |\n'override' |\n'mutable' |\n'disposable' |\n\n'signed' |\n'unsigned' |\n'bigendian' |\n'const' |\n'cmut' |\n'readonly' |\n'volatile' |\n'safe' |\n'unsafe' |\n'weak' |\n'thin' |\n'errorcode' |\n'cdecl' |\n'stdcall' |\n'thiscall' |\n'jnccall' |\n'array' |\n'function' |\n'property' |\n'bindable' |\n'autoget' |\n'indexed' |\n'multicast' |\n'event' |\n'reactor' |\n'async' |\n\n'anydata' |\n'void' |\n'variant' |\n'bool' |\n'int' |\n'intptr' |\n'char' |\n'short' |\n'long' |\n'float' |\n'double' |\n'enum' |\n'struct' |\n'union' |\n'class' |\n'opaque' |\n'exposed' |\n'bitflag' |\n\n'get' |\n'set' |\n'construct' |\n'destruct' |\n'operator' |\n'postfix' |\n\n'if' |\n'else' |\n'for' |\n'while' |\n'do' |\n'break' |\n'break' [1-9]? |\n'continue' [1-9]? |\n'return' |\n'switch' |\n'reswitch' |\n'case' |\n'default' |\n'once' |\n'onevent' |\n'try' |\n'throw' |\n'catch' |\n'finally' |\n'nestedscope' |\n'assert' |\n'await' |\n\n'basetype' [1-9]? |\n'this' |\n'true' |\n'false' |\n'null' |\n\n'new' |\n'delete' |\n'sizeof' |\n'countof' |\n'offsetof' |\n'typeof' |\n'bindingof' |\n'dynamic'\n) { highlightLastToken(Color_Keyword); };\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\nid ;\n\n(\nlit_dq |\nlit_sq |\n[rR] raw_lit_sq |\n[rR] raw_lit_dq |\ndec+ |\n'0' oct+ |\n'0' [xX] hex+ |\n'0' [oO] oct+ |\n'0' [bB] bin+ |\n'0' [nNdD] dec+ |\n'0' [xXoObBnNdD] raw_lit_dq |\ndec+ (('.' dec*) | ([eE] [+\\-]? dec+)) |\n[$fF] lit_dq\n) { highlightLastToken(Color_Constant); };\n\n('0' [xXoObBnNdD])? '\"\"\"'\n { highlightLastToken(Color_Constant); fgoto lit_ml; };\n\n'\/\/' any* { highlightLastToken(Color_Comment); setCurrentBlockState(BlockState_CommentSl); };\n'\/*' { highlightLastToken(Color_Comment); fgoto comment_ml; };\n\nws | nl ;\nany ;\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# comment machine\n#\n\ncomment_ml := |*\n\nany* :>> '*\/'? { highlightLastToken(Color_Comment); if (isTokenSuffix(\"*\/\", 2)) fgoto main; };\n\n*|;\n\n#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n#\n# multi-line literal machine\n#\n\nlit_ml := |*\n\nany* :>> '\"\"\"'? { highlightLastToken(Color_Constant); if (isTokenSuffix(\"\\\"\\\"\\\"\", 3)) fgoto main; };\n\n*|;\n\n}%%\n\nnamespace jnc {\n\n\/\/..............................................................................\n\nvoid\nJancyHighlighter::init()\n{\n\t%% write init;\n}\n\nvoid\nJancyHighlighter::exec()\n{\n\tint prevBlockState = previousBlockState();\n\tswitch (prevBlockState)\n\t{\n\tcase BlockState_CommentMl:\n\t\tcs = jancy_lexer_en_comment_ml;\n\t\tbreak;\n\n\tcase BlockState_LitMl:\n\t\tcs = jancy_lexer_en_lit_ml;\n\t\tbreak;\n\t}\n\n\tsetCurrentBlockState(BlockState_Normal);\n\n\t%% write exec;\n\n\tswitch (cs)\n\t{\n\tcase jancy_lexer_en_comment_ml:\n\t\tsetCurrentBlockState(BlockState_CommentMl);\n\t\tbreak;\n\n\tcase jancy_lexer_en_lit_ml:\n\t\tsetCurrentBlockState(BlockState_LitMl);\n\t\tbreak;\n\t}\n}\n\n\/\/..............................................................................\n\n} \/\/ namespace jnc\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"c3011e263b6685c5e508091d64ef5ff4817e15e9","subject":"Fix the definition of unreserved character.","message":"Fix the definition of unreserved character.\n","repos":"bvanderveen\/httpmachine,joelverhagen\/httpmachine,chinadev\/httpmachine,chinadev\/httpmachine,bvanderveen\/httpmachine,bvanderveen\/httpmachine,joelverhagen\/httpmachine","old_file":"HttpMachine\/uri.rl","new_file":"HttpMachine\/uri.rl","new_contents":"%%{\n\nmachine uri;\n\nscheme = alpha (alpha | digit | \"+\" | \"-\" | \".\")+;\n\nescaped = \"%\" xdigit xdigit;\nmark = \"-\" | \"_\" | \".\" | \"!\" | \"~\" | \"*\" | \"'\" | \"(\" | \")\";\nreserved = \";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\";\nunreserved = alpha | digit | mark;\npchar = unreserved | escaped | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\";\nuric = reserved | unreserved | escaped;\nuric_no_slash = unreserved | escaped | \";\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\";\nrel_segment = (unreserved | escaped | \";\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\")+;\nreg_name = (unreserved | escaped | \"$\" | \",\" | \";\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" )+;\nuserinfo = (unreserved | escaped | \";\" | \":\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\" )*;\n\nparam = pchar*;\nsegment = pchar* (\";\" param)*;\npath_segments = segment (\"\/\" segment)*;\nuri_abs_path = \"\/\" path_segments;\n\nrel_path = rel_segment uri_abs_path?;\n\nuri_query = uric*;\nuri_fragment = uric*;\n\nipv4address = digit{1,3} \".\" digit{1,3} \".\" digit{1,3} \".\" digit{1,3};\ntoplabel = alpha | alpha (alnum | \"-\")* alnum;\ndomainlabel = alnum | (alnum (alnum | \"-\")* alnum);\nhostname = (domainlabel \".\") toplabel \".\"?;\n\n# might be better to condense host to (alnum | \".\" | \"-\")*;\nhost = hostname | ipv4address;\nport = digit*;\n\nhostport = host (\":\" port)?;\nserver = ((userinfo \"@\")? hostport)?;\nuri_authority = server | reg_name;\nnet_path = \"\/\/\" uri_authority uri_abs_path?;\n\nopaque_part = uric_no_slash uric*;\nhier_part = (net_path | uri_abs_path) (\"?\" uri_query)?;\n\n\nuri_absolute_uri = scheme \":\" (hier_part | opaque_part);\nrelative_uri = (uri_abs_path | rel_path) (\"?\" uri_query)?;\n\nuri_reference = (uri_absolute_uri | relative_uri)? (\"#\" uri_fragment)?;\n\n}%%\n","old_contents":"%%{\n\nmachine uri;\n\nscheme = alpha (alpha | digit | \"+\" | \"-\" | \".\")+;\n\nescaped = \"%\" xdigit xdigit;\nmark = \"-\" | \"_\" | \".\" | \"!\" | \"~\" | \"*\" | \"'\" | \"(\" | \")\";\nreserved = \";\" | \"\/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\";\nunreserved = alpha | mark;\npchar = unreserved | escaped | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\";\nuric = reserved | unreserved | escaped;\nuric_no_slash = unreserved | escaped | \";\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\";\nrel_segment = (unreserved | escaped | \";\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\")+;\nreg_name = (unreserved | escaped | \"$\" | \",\" | \";\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" )+;\nuserinfo = (unreserved | escaped | \";\" | \":\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\" )*;\n\nparam = pchar*;\nsegment = pchar* (\";\" param)*;\npath_segments = segment (\"\/\" segment)*;\nuri_abs_path = \"\/\" path_segments;\n\nrel_path = rel_segment uri_abs_path?;\n\nuri_query = uric*;\nuri_fragment = uric*;\n\nipv4address = digit{1,3} \".\" digit{1,3} \".\" digit{1,3} \".\" digit{1,3};\ntoplabel = alpha | alpha (alnum | \"-\")* alnum;\ndomainlabel = alnum | (alnum (alnum | \"-\")* alnum);\nhostname = (domainlabel \".\") toplabel \".\"?;\n\n# might be better to condense host to (alnum | \".\" | \"-\")*;\nhost = hostname | ipv4address;\nport = digit*;\n\nhostport = host (\":\" port)?;\nserver = ((userinfo \"@\")? hostport)?;\nuri_authority = server | reg_name;\nnet_path = \"\/\/\" uri_authority uri_abs_path?;\n\nopaque_part = uric_no_slash uric*;\nhier_part = (net_path | uri_abs_path) (\"?\" uri_query)?;\n\n\nuri_absolute_uri = scheme \":\" (hier_part | opaque_part);\nrelative_uri = (uri_abs_path | rel_path) (\"?\" uri_query)?;\n\nuri_reference = (uri_absolute_uri | relative_uri)? (\"#\" uri_fragment)?;\n\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"06eecf741a54cd1cb052448a09f26df2ad7801e2","subject":"reset %{d} on redirect also","message":"reset %{d} on redirect also\n","repos":"wahern\/dns,wahern\/dns","old_file":"src\/spf.rl","new_file":"src\/spf.rl","new_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009, 2010 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (spf_unlikely(SPF_DEBUG > 0)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#if __GNUC__ >= 3\n#define spf_likely(e)\t__builtin_expect((e), 1)\n#define spf_unlikely(e)\t__builtin_expect((e), 0)\n#else\n#define spf_likely(e)\t(e)\n#define spf_unlikely(e)\t(e)\n#endif\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * V E R S I O N R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst char *spf_vendor(void) {\n\treturn SPF_VENDOR;\n} \/* spf_vendor() *\/\n\n\nint spf_v_rel(void) {\n\treturn SPF_V_REL;\n} \/* spf_v_rel() *\/\n\n\nint spf_v_abi(void) {\n\treturn SPF_V_ABI;\n} \/* spf_v_abi() *\/\n\n\nint spf_v_api(void) {\n\treturn SPF_V_API;\n} \/* spf_v_api() *\/\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > i; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tmacros = 0;\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tmacros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (spf_unlikely(!(cond))) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic inline void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic inline int vm_indexof(struct spf_vm *vm, int p) {\n\tif (spf_likely(p < 0))\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic inline enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic inline intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic inline intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic inline intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic inline intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic inline int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\tSPF_SAY(\"querying %s IN %s\", (char *)qname, dns_strtype(qtype));\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tSPF_SAY(\"querying %s IN %s\", host, dns_strtype(qtype));\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tI8(&sub, 'd');\n\t\tGETENV(&sub);\n\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tDUP(&sub);\n\t\tI8(&sub, 'd');\n\t\tSETENV(&sub);\n\n\t\tsub_emit(&sub, OP_CHECK);\n\n\t\tI8(&sub, 3);\n\t\tNEG(&sub);\n\t\tMOVE(&sub);\n\t\tI8(&sub, 'd');\n\t\tSETENV(&sub);\n\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puta, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\nstatic const char *vm_strcode(int code) {\n\treturn vm_op[code].name;\n} \/* vm_strcode() *\/\n\nstatic int vm_icode(const char *name) {\n\tint code;\n\n\tfor (code = 0; code < (int)spf_lengthof(vm_op); code++) {\n\t\tif (vm_op[code].name && !strcasecmp(name, vm_op[code].name))\n\t\t\treturn code;\n\t}\n\n\treturn -1;\n} \/* vm_icode() *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (spf_unlikely(SPF_DEBUG >= 2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(NULL, &error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nvoid spf_clear(struct spf_resolver *spf) {\n\treturn dns_res_clear(spf->res);\n} \/* spf_clear() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tif (*line) {\n\t\t\t\tif (-1 != (code = vm_icode(line))) {\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t\t} else\n\t\t\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t\t}\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -W print version\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\n\nstatic void version(FILE *fp) {\n\tfprintf(fp, \"spf (spf.c) %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"vendor %s\\n\", spf_vendor());\n\tfprintf(fp, \"release %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"abi %.8X\\n\", spf_v_abi());\n\tfprintf(fp, \"api %.8X\\n\", spf_v_api());\n\tfprintf(fp, \"dns %.8X\\n\", dns_v_rel());\n} \/* version() *\/\n\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vWh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'W':\n\t\t\tversion(stdout);\n\n\t\t\treturn 0;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","old_contents":"\/* ==========================================================================\n * spf.rl - \"spf.c\", a Sender Policy Framework library.\n * --------------------------------------------------------------------------\n * Copyright (c) 2009, 2010 William Ahern\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n * ==========================================================================\n *\/\n#include \t\/* size_t *\/\n#include \t\/* intptr_t *\/\n#include \t\/* malloc(3) free(3) abs(3) *\/\n\n#include \t\/* isgraph(3) isdigit(3) tolower(3) *\/\n\n#include \t\/* memcpy(3) strlen(3) strsep(3) strcmp(3) *\/\n\n#include \t\/* EINVAL EFAULT ENAMETOOLONG E2BIG errno *\/\n\n#include \t\/* assert(3) *\/\n\n#include \t\/* time(3) *\/\n\n#include \t\/* jmp_buf _setjmp(3) _longjmp(3) *\/\n\n#include \t\/* AF_INET AF_INET6 *\/\n\n#include \t\/* gethostname(3) *\/\n\n#include \t\/* struct in_addr struct in6_addr *\/\n\n#include \"dns.h\"\n#include \"spf.h\"\n\n\n#define SPF_DEFEXP \"%{i} is not one of %{d}'s designated mail servers.\"\n\n\n\/*\n * D E B U G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_debug = 0;\n\n#if SPF_DEBUG\n#include \/* stderr fprintf(3) *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG spf_debug\n\n#define SPF_SAY_(fmt, ...) \\\n\tdo { if (spf_unlikely(SPF_DEBUG > 0)) fprintf(stderr, fmt \"%.1s\", __func__, __LINE__, __VA_ARGS__); } while (0)\n#define SPF_SAY(...) SPF_SAY_(\">>>> (%s:%d) \" __VA_ARGS__, \"\\n\")\n#define SPF_HAI SPF_SAY(\"HAI\")\n\n#else \/* !SPF_DEBUG *\/\n\n#undef SPF_DEBUG\n#define SPF_DEBUG 0\n\n#define SPF_SAY(...)\n#define SPF_HAI\n\n#endif \/* SPF_DEBUG *\/\n\n\n\/*\n * M I S C . M A C R O S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#if __GNUC__ >= 3\n#define spf_likely(e)\t__builtin_expect((e), 1)\n#define spf_unlikely(e)\t__builtin_expect((e), 0)\n#else\n#define spf_likely(e)\t(e)\n#define spf_unlikely(e)\t(e)\n#endif\n\n\/** static assert *\/\n#define spf_verify_true(R) (!!sizeof (struct { unsigned int constraint: (R)? 1 : -1; }))\n#define spf_verify(R) extern int (*spf_contraint (void))[spf_verify_true(R)]\n\n#define spf_lengthof(a) (sizeof (a) \/ sizeof (a)[0])\n#define spf_endof(a) (&(a)[spf_lengthof((a))])\n\n#define SPF_PASTE(x, y) a##b\n#define SPF_XPASTE(x, y) SPF_PASTE(a, b)\n#define SPF_STRINGIFY_(x) #x\n#define SPF_STRINGIFY(x) SPF_STRINGIFY_(x)\n\n\n\/*\n * V E R S I O N R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst char *spf_vendor(void) {\n\treturn SPF_VENDOR;\n} \/* spf_vendor() *\/\n\n\nint spf_v_rel(void) {\n\treturn SPF_V_REL;\n} \/* spf_v_rel() *\/\n\n\nint spf_v_abi(void) {\n\treturn SPF_V_ABI;\n} \/* spf_v_abi() *\/\n\n\nint spf_v_api(void) {\n\treturn SPF_V_API;\n} \/* spf_v_api() *\/\n\n\n\/*\n * S T R I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_itoa(char *dst, size_t lim, unsigned i) {\n\tunsigned r, d = 1000000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = '0' + r;\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 10);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itoa() *\/\n\n\nunsigned long spf_atoi(const char *src) {\n\tunsigned long i = 0;\n\n\twhile (isdigit((unsigned char)*src)) {\n\t\ti *= 10;\n\t\ti += *src++ - '0';\n\t}\n\n\treturn i;\n} \/* spf_atoi() *\/\n\n\nunsigned spf_xtoi(const char *src) {\n\tstatic const unsigned char tobase[] =\n\t\t{ [0 ... 255] = 0xf0,\n\t\t ['0'] = 0x0, ['1'] = 0x1, ['2'] = 0x2, ['3'] = 0x3, ['4'] = 0x4,\n\t\t ['5'] = 0x5, ['6'] = 0x6, ['7'] = 0x7, ['8'] = 0x8, ['9'] = 0x9,\n\t\t ['a'] = 0xa, ['b'] = 0xb, ['c'] = 0xc, ['d'] = 0xd, ['e'] = 0xe, ['f'] = 0xf,\n\t\t ['A'] = 0xA, ['B'] = 0xB, ['C'] = 0xC, ['D'] = 0xD, ['E'] = 0xE, ['F'] = 0xF };\n\tunsigned n, i = 0;\n\n\twhile (!(0xf0 & (n = tobase[0xff & (unsigned char)*src++]))) {\n\t\ti <<= 4;\n\t\ti |= n;\n\t}\n\n\treturn i;\n} \/* spf_xtoi() *\/\n\n\nsize_t spf_itox(char *dst, size_t lim, unsigned i) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned r, d = 0x10000000, p = 0;\n\tsize_t dp = 0;\n\n\tif (i) {\n\t\tdo {\n\t\t\tif ((r = i \/ d) || p) {\n\t\t\t\ti -= r * d;\n\n\t\t\t\tp++;\n\n\t\t\t\tif (dp < lim)\n\t\t\t\t\tdst[dp] = tohex[r];\n\t\t\t\tdp++;\n\t\t\t}\n\t\t} while (d \/= 16);\n\t} else {\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '0';\n\n\t\tdp++;\n\t}\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_itox() *\/\n\n\nstatic size_t spf_strlcpy(char *dst, const char *src, size_t lim) {\n\tchar *dp = dst; char *de = &dst[lim]; const char *sp = src;\n\n\tif (dp < de) {\n\t\tdo {\n\t\t\tif ('\\0' == (*dp++ = *sp++))\n\t\t\t\treturn sp - src - 1;\n\t\t} while (dp < de);\n\n\t\tdp[-1]\t= '\\0';\n\t}\n\n\twhile (*sp++ != '\\0')\n\t\t;;\n\n\treturn sp - src - 1;\n} \/* spf_strlcpy() *\/\n\n\nstatic unsigned spf_split(unsigned max, char **argv, char *src, const char *delim, _Bool empty) {\n\tunsigned argc = 0;\n\tchar *arg;\n\n\tdo {\n\t\tif ((arg = strsep(&src, delim)) && (*arg || empty)) {\n\t\t\tif (argc < max)\n\t\t\t\targv[argc] = arg;\n\n\t\t\targc++;\n\t\t}\n\t} while (arg);\n\n\tif (max)\n\t\targv[SPF_MIN(argc, max - 1)] = 0;\n\n\treturn argc;\n} \/* spf_split() *\/\n\n\nchar *spf_tolower(char *src) {\n\tunsigned char *p = (unsigned char *)src;\n\n\twhile (*p) {\n\t\t*p = tolower(*p);\n\t\t++p;\n\t}\n\n\treturn src;\n} \/* spf_tolower() *\/\n\n\nstatic size_t spf_rtrim(char *str, const char *trim) {\n\tint p = strlen(str);\n\n\twhile (--p >= 0 && strchr(trim, str[p]))\n\t\tstr[p] = 0;\n\n\treturn p + 1;\n} \/* spf_rtrim() *\/\n\n\n\/** domain normalization *\/\n\n#define SPF_DN_CHOMP 1\t\/* discard root zone, if any *\/\n#define SPF_DN_ANCHOR 2 \/* add root zone, if none *\/\n#define SPF_DN_TRUNC 4 \/* discard sub-domain(s) if copy overflows *\/\n#define SPF_DN_SUPER 8 \/* discard sub-domain *\/\n\nsize_t spf_fixdn(char *dst, const char *src, size_t lim, int flags) {\n\tsize_t op, dp, sp;\n\tint lc;\n\n\tsp = 0;\nfixdn:\n\top = sp;\n\tdp = 0;\n\tlc = 0;\n\n\t\/* trim any leading dot(s) *\/\n\twhile (src[sp] == '.') {\n\t\tif (!src[++sp]) \/* but keep lone dot *\/\n\t\t\t{ --sp; break; }\n\t}\n\n\twhile (src[sp]) {\n\t\tlc = src[sp];\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = src[sp];\n\n\t\tsp++; dp++;\n\n\t\t\/* trim extra dot(s) *\/\n\t\twhile (lc == '.' && src[sp] == '.')\n\t\t\tsp++;\n\t}\n\n\tif (flags & SPF_DN_CHOMP) {\n\t\tif (lc == '.')\n\t\t\tdp--;\n\t} else if (flags & SPF_DN_ANCHOR) {\n\t\tif (lc != '.') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = '.';\n\n\t\t\tdp++;\n\t\t}\n\t}\n\n\tif (flags & SPF_DN_SUPER) {\n\t\tflags &= ~SPF_DN_SUPER;\n\n\t\twhile (src[op] == '.') {\n\t\t\tif (!src[++op]) {\n\t\t\t\tflags &= ~SPF_DN_ANCHOR;\n\n\t\t\t\tgoto fixdn; \/* output empty string *\/\n\t\t\t}\n\t\t}\n\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\t\/** don't accidentally trim any final root zone. *\/\n\t\t\tif (!src[sp])\n\t\t\t\tsp--;\n\t\t}\n\n\t\tgoto fixdn;\n\t} else if ((flags & SPF_DN_TRUNC) && dp >= lim) {\n\t\top += strcspn(&src[op], \".\");\n\n\t\tif (src[op] == '.') {\n\t\t\tsp = op + 1;\n\n\t\t\tif (src[sp])\n\t\t\t\tgoto fixdn;\n\n\t\t\t\/** return the minimum length possible *\/\n\t\t}\n\t}\n\n\tif (lim > 0)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_fixdn() *\/\n\n\nsize_t spf_4top(char *dst, size_t lim, const struct in_addr *ip) {\n\tchar tmp[16];\n\tsize_t len;\n\tunsigned i;\n\n\tlen = spf_itoa(tmp, sizeof tmp, 0xff & (ntohl(ip->s_addr) >> 24));\n\n\tfor (i = 1; i < 4; i++) {\n\t\ttmp[len++] = '.';\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, 0xff & (ntohl(ip->s_addr) >> (8 * (3 - i))));\n\t}\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_4top() *\/\n\n\n\/** a simple, optimistic IPv4 address string parser *\/\nstruct in_addr *spf_pto4(struct in_addr *ip, const char *src) {\n\tchar *byte[4 + 1];\n\tchar tmp[16];\n\tunsigned bytes, i, iaddr;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tbytes = spf_split(spf_lengthof(byte), byte, tmp, \".\", 1);\n\tiaddr = 0;\n\n\tfor (i = 0; i < SPF_MIN(bytes, 4); i++) {\n\t\tiaddr <<= 8;\n\t\tiaddr |= 0xff & spf_atoi(byte[i]);\n\t}\n\n\tiaddr <<= 8 * (4 - i);\n\n\tip->s_addr = htonl(iaddr);\n\n\treturn ip;\n} \/* spf_pto4() *\/\n\n\n#define SPF_6TOP_NYBBLE 1\n#define SPF_6TOP_COMPAT 2\n#define SPF_6TOP_MAPPED 4\n#define SPF_6TOP_MIXED (SPF_6TOP_COMPAT|SPF_6TOP_MAPPED)\n\nsize_t spf_6top(char *dst, size_t lim, const struct in6_addr *ip, int flags) {\n\tstatic const char tohex[] = \"0123456789abcdef\";\n\tunsigned short group[8];\n\tchar tmp[SPF_MAX(40, 64)]; \/* 40 for canon, 64 for nybbles (includes '\\0') *\/\n\tsize_t len;\n\tunsigned i;\n\t_Bool run, ran;\n\n\tlen = 0;\n\n\tif (flags & SPF_6TOP_NYBBLE) {\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 4)];\n\t\ttmp[len++] = '.';\n\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[0] >> 0)];\n\n\t\tfor (i = 1; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 4)];\n\t\t\ttmp[len++] = '.';\n\t\t\ttmp[len++] = tohex[0x0f & (ip->s6_addr[i] >> 0)];\n\t\t}\n\t} else if (IN6_IS_ADDR_V4COMPAT(ip) && (flags & SPF_6TOP_COMPAT)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else if (IN6_IS_ADDR_V4MAPPED(ip) && (flags & SPF_6TOP_MAPPED)) {\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = ':';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = 'f';\n\t\ttmp[len++] = ':';\n\n\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[12]);\n\n\t\tfor (i = 13; i < 16; i++) {\n\t\t\ttmp[len++] = '.';\n\t\t\tlen += spf_itoa(&tmp[len], sizeof tmp - len, ip->s6_addr[i]);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < 8; i++) {\n\t\t\tgroup[i] = (0xff00 & (ip->s6_addr[i * 2] << 8))\n\t\t\t | (0x00ff & (ip->s6_addr[i * 2 + 1] << 0));\n\t\t}\n\n\t\trun = 0; ran = 0;\n\n\t\tif (group[0]) {\n\t\t\tlen = spf_itox(tmp, sizeof tmp, group[0]);\n\t\t} else\n\t\t\trun++;\n\n\t\tfor (i = 1; i < 8; i++) {\n\t\t\tif (group[i] || ran) {\n\t\t\t\tif (run) {\n\t\t\t\t\ttmp[len++] = ':';\n\t\t\t\t\tran = 1; run = 0;\n\t\t\t\t}\n\n\t\t\t\ttmp[len++] = ':';\n\t\t\t\tlen += spf_itox(&tmp[len], sizeof tmp - len, group[i]);\n\t\t\t} else\n\t\t\t\trun++;\n\t\t}\n\n\t\tif (run) {\n\t\t\ttmp[len++] = ':';\n\t\t\ttmp[len++] = ':';\n\t\t}\n\t}\n\n\ttmp[len] = '\\0';\n\n\treturn spf_strlcpy(dst, tmp, lim);\n} \/* spf_6top() *\/\n\n\n\/** a simple, optimistic IPv6 address string parser *\/\nstruct in6_addr *spf_pto6(struct in6_addr *ip, const char *src) {\n\tchar *part[32 + 1]; \/* 8 words or 32 nybbles *\/\n\tchar tmp[64];\n\tunsigned short group[8] = { 0 };\n\tunsigned count, i, j, k;\n\tstruct in_addr ip4;\n\n\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\tcount = spf_split(spf_lengthof(part), part, tmp, \":\", 1);\n\n\tif (count > 1) {\n\t\tfor (i = 0; i < SPF_MIN(count, 8); i++) {\n\t\t\tif (*part[i]) {\n\t\t\t\tif (strchr(part[i], '.')) {\n\t\t\t\t\tspf_pto4(&ip4, part[i]);\n\n\t\t\t\t\tgroup[i] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\n\t\t\t\t\tif (++i < 8)\n\t\t\t\t\t\tgroup[i] = 0xffff & ntohl(ip4.s_addr);\n\t\t\t\t} else {\n\t\t\t\t\tgroup[i] = spf_xtoi(part[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 7, k = count - 1; j > i && k > i; j--, k--) {\n\t\t\t\t\tif (strchr(part[k], '.')) {\n\t\t\t\t\t\tspf_pto4(&ip4, part[k]);\n\n\t\t\t\t\t\tgroup[j] = 0xffff & ntohl(ip4.s_addr);\n\n\t\t\t\t\t\tif (--j >= 0)\n\t\t\t\t\t\t\tgroup[j] = 0xffff & (ntohl(ip4.s_addr) >> 16);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgroup[j] = spf_xtoi(part[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tspf_strlcpy(tmp, src, sizeof tmp);\n\n\t\tcount = spf_split(spf_lengthof(part), part, tmp, \".\", 1);\n\t\tcount = SPF_MIN(count, 32);\n\n\t\tfor (i = 0, j = 0; i < count; j++) {\n\t\t\tfor (k = 0; k < 4 && i < count; k++, i++) {\n\t\t\t\tgroup[j] <<= 4;\n\t\t\t\tgroup[j] |= 0xf & spf_xtoi(part[i]);\n\t\t\t}\n\n\t\t\tgroup[j] <<= 4 * (4 - k);\n\t\t}\n\t}\n\n\tfor (i = 0, j = 0; i < 8; i++) {\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 8);\n\t\tip->s6_addr[j++] = 0xff & (group[i] >> 0);\n\t}\n\n\twhile (j < 16)\n\t\tip->s6_addr[j++] = 0;\n\n\treturn ip;\n} \/* spf_pto6() *\/\n\n\nvoid *spf_pton(void *dst, int af, const char *src) {\n\treturn (af == AF_INET6)? (void *)spf_pto6(dst, src) : (void *)spf_pto4(dst, src);\n} \/* spf_pton() *\/\n\n\nsize_t spf_ntop(char *dst, size_t lim, int af, const void *ip, int flags) {\n\tif (af == AF_INET6)\n\t\treturn spf_6top(dst, lim, ip, flags);\n\telse\n\t\treturn spf_4top(dst, lim, ip);\n} \/* spf_ntop() *\/\n\n\nint spf_6cmp(const struct in6_addr *a, const struct in6_addr *b, unsigned prefix) {\n\tunsigned i, n;\n\tint cmp;\n\n\tfor (i = 0; i < prefix \/ 8 && i < 16; i++) {\n\t\tif ((cmp = a->s6_addr[i] - b->s6_addr[i]))\n\t\t\treturn cmp;\n\t}\n\n\tif ((prefix % 8) && i < 16) {\n\t\tn = (8 - (prefix % 8));\n\n\t\tif ((cmp = (a->s6_addr[i] >> n) - (b->s6_addr[i] >> n)))\n\t\t\treturn cmp;\n\t}\n\n\treturn 0;\n} \/* spf_6cmp() *\/\n\n\nint spf_4cmp(const struct in_addr *a, const struct in_addr *b, unsigned prefix) {\n\tunsigned long x = ntohl(a->s_addr), y = ntohl(b->s_addr);\n\n\tif (!prefix) {\n\t\treturn 0;\n\t} if (prefix < 32) {\n\t\tx >>= 32 - (prefix % 32);\n\t\ty >>= 32 - (prefix % 32);\n\t}\n\n\treturn (x < y)? -1 : (x > y)? 1 : 0;\n} \/* spf_4cmp() *\/\n\n\nint spf_addrcmp(int af, const void *a, const void *b, unsigned prefix) {\n\tif (af == AF_INET6)\n\t\treturn spf_6cmp(a, b, prefix);\n\telse\n\t\treturn spf_4cmp(a, b, prefix);\n} \/* spf_addrcmp() *\/\n\n\nconst char *spf_strerror(int error) {\n\tswitch (error) {\n\tcase DNS_ENOBUFS:\n\t\treturn \"DNS no buffer space\";\n\tcase DNS_EILLEGAL:\n\t\treturn \"DNS illegal data\";\n\tcase DNS_EUNKNOWN:\n\t\treturn \"DNS unknown\";\n\tdefault:\n\t\treturn strerror(error);\n\t}\n} \/* spf_strerror() *\/\n\n\nconst char *spf_strterm(int term) {\n\tswitch (term) {\n\tcase SPF_ALL:\n\t\treturn \"all\";\n\tcase SPF_INCLUDE:\n\t\treturn \"include\";\n\tcase SPF_A:\n\t\treturn \"a\";\n\tcase SPF_MX:\n\t\treturn \"mx\";\n\tcase SPF_PTR:\n\t\treturn \"ptr\";\n\tcase SPF_IP4:\n\t\treturn \"ip4\";\n\tcase SPF_IP6:\n\t\treturn \"ip6\";\n\tcase SPF_EXISTS:\n\t\treturn \"exists\";\n\tcase SPF_REDIRECT:\n\t\treturn \"redirect\";\n\tcase SPF_EXP:\n\t\treturn \"exp\";\n\tcase SPF_UNKNOWN:\n\t\t\/* FALL THROUGH *\/\n\tdefault:\n\t\treturn \"unknown\";\n\t}\n} \/* spf_strterm() *\/\n\n\nconst char *spf_strresult(int result) {\n\tswitch (result) {\n\tcase SPF_NONE:\n\t\treturn \"None\";\n\tcase SPF_NEUTRAL:\n\t\treturn \"Neutral\";\n\tcase SPF_PASS:\n\t\treturn \"Pass\";\n\tcase SPF_FAIL:\n\t\treturn \"Fail\";\n\tcase SPF_SOFTFAIL:\n\t\treturn \"SoftFail\";\n\tcase SPF_TEMPERROR:\n\t\treturn \"TempError\";\n\tcase SPF_PERMERROR:\n\t\treturn \"PermError\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n} \/* spf_strresult() *\/\n\n\n\/*\n * S T R I N G B U F F E R R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\n#define SBUF_INIT(sbuf) { 0 }\n\nstruct spf_sbuf {\n\tunsigned end;\n\n\t_Bool overflow;\n\n\tchar str[512];\n}; \/* struct spf_sbuf *\/\n\nstatic struct spf_sbuf *sbuf_init(struct spf_sbuf *sbuf) {\n\treturn memset(sbuf, 0, sizeof *sbuf);\n} \/* sbuf_init() *\/\n\nstatic _Bool sbuf_putc(struct spf_sbuf *sbuf, int ch) {\n\tif (sbuf->end < sizeof sbuf->str - 1)\n\t\tsbuf->str[sbuf->end++] = ch;\n\telse\n\t\tsbuf->overflow = 1;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putc() *\/\n\nstatic _Bool sbuf_puts(struct spf_sbuf *sbuf, const char *src) {\n\twhile (*src && sbuf_putc(sbuf, *src))\n\t\tsrc++;\n\n\treturn !sbuf->overflow;\n} \/* sbuf_puts() *\/\n\nstatic _Bool sbuf_putv(struct spf_sbuf *sbuf, const void *src, size_t len) {\n\tsize_t lim = SPF_MIN(len, (sizeof sbuf->str - 1) - sbuf->end);\n\n\tmemcpy(&sbuf->str[sbuf->end], src, lim);\n\tsbuf->end += lim;\n\n\tsbuf->overflow = (lim != len);\n\n\treturn !sbuf->overflow;\n} \/* sbuf_putv() *\/\n\nstatic _Bool sbuf_puti(struct spf_sbuf *sbuf, unsigned long i) {\n\tchar tmp[32];\n\n\tspf_itoa(tmp, sizeof tmp, i);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_puti() *\/\n\nstatic _Bool sbuf_put4(struct spf_sbuf *sbuf, const struct in_addr *ip) {\n\tchar tmp[16];\n\n\tspf_4top(tmp, sizeof tmp, ip);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put4() *\/\n\nstatic _Bool sbuf_put6(struct spf_sbuf *sbuf, const struct in6_addr *ip) {\n\tchar tmp[40];\n\n\tspf_6top(tmp, sizeof tmp, ip, SPF_6TOP_MIXED);\n\n\treturn sbuf_puts(sbuf, tmp);\n} \/* sbuf_put6() *\/\n\n\n\/*\n * P A R S I N G \/ C O M P O S I N G R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic const struct spf_all all_initializer =\n\t{ .type = SPF_ALL, .result = SPF_PASS };\n\nstatic void all_comp(struct spf_sbuf *sbuf, struct spf_all *all) {\n\tsbuf_putc(sbuf, all->result);\n\tsbuf_puts(sbuf, \"all\");\n} \/* all_comp() *\/\n\n\nstatic const struct spf_include include_initializer =\n\t{ .type = SPF_INCLUDE, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void include_comp(struct spf_sbuf *sbuf, struct spf_include *include) {\n\tsbuf_putc(sbuf, include->result);\n\tsbuf_puts(sbuf, \"include\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, include->domain);\n} \/* include_comp() *\/\n\n\nstatic const struct spf_a a_initializer =\n\t{ .type = SPF_A, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void a_comp(struct spf_sbuf *sbuf, struct spf_a *a) {\n\tsbuf_putc(sbuf, a->result);\n\tsbuf_puts(sbuf, \"a\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, a->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, a->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, a->prefix6);\n} \/* a_comp() *\/\n\n\nstatic const struct spf_mx mx_initializer =\n\t{ .type = SPF_MX, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\", .prefix4 = 32, .prefix6 = 128 };\n\nstatic void mx_comp(struct spf_sbuf *sbuf, struct spf_mx *mx) {\n\tsbuf_putc(sbuf, mx->result);\n\tsbuf_puts(sbuf, \"mx\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, mx->domain);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, mx->prefix4);\n\tsbuf_puts(sbuf, \"\/\/\");\n\tsbuf_puti(sbuf, mx->prefix6);\n} \/* mx_comp() *\/\n\n\nstatic const struct spf_ptr ptr_initializer =\n\t{ .type = SPF_PTR, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void ptr_comp(struct spf_sbuf *sbuf, struct spf_ptr *ptr) {\n\tsbuf_putc(sbuf, ptr->result);\n\tsbuf_puts(sbuf, \"ptr\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, ptr->domain);\n} \/* ptr_comp() *\/\n\n\nstatic const struct spf_ip4 ip4_initializer =\n\t{ .type = SPF_IP4, .result = SPF_PASS, .prefix = 32 };\n\nstatic void ip4_comp(struct spf_sbuf *sbuf, struct spf_ip4 *ip4) {\n\tsbuf_putc(sbuf, ip4->result);\n\tsbuf_puts(sbuf, \"ip4\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put4(sbuf, &ip4->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip4->prefix);\n} \/* ip4_comp() *\/\n\n\nstatic const struct spf_ip6 ip6_initializer =\n\t{ .type = SPF_IP6, .result = SPF_PASS, .prefix = 128 };\n\nstatic void ip6_comp(struct spf_sbuf *sbuf, struct spf_ip6 *ip6) {\n\tsbuf_putc(sbuf, ip6->result);\n\tsbuf_puts(sbuf, \"ip6\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_put6(sbuf, &ip6->addr);\n\tsbuf_putc(sbuf, '\/');\n\tsbuf_puti(sbuf, ip6->prefix);\n} \/* ip6_comp() *\/\n\n\nstatic const struct spf_exists exists_initializer =\n\t{ .type = SPF_EXISTS, .result = SPF_PASS, .macros = SPF_M('d'), .domain = \"%{d}\" };\n\nstatic void exists_comp(struct spf_sbuf *sbuf, struct spf_exists *exists) {\n\tsbuf_putc(sbuf, exists->result);\n\tsbuf_puts(sbuf, \"exists\");\n\tsbuf_putc(sbuf, ':');\n\tsbuf_puts(sbuf, exists->domain);\n} \/* exists_comp() *\/\n\n\nstatic const struct spf_redirect redirect_initializer =\n\t{ .type = SPF_REDIRECT };\n\nstatic void redirect_comp(struct spf_sbuf *sbuf, struct spf_redirect *redirect) {\n\tsbuf_puts(sbuf, \"redirect\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, redirect->domain);\n} \/* redirect_comp() *\/\n\n\nstatic const struct spf_exp exp_initializer =\n\t{ .type = SPF_EXP };\n\nstatic void exp_comp(struct spf_sbuf *sbuf, struct spf_exp *exp) {\n\tsbuf_puts(sbuf, \"exp\");\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, exp->domain);\n} \/* exp_comp() *\/\n\n\nstatic const struct spf_unknown unknown_initializer =\n\t{ .type = SPF_UNKNOWN };\n\nstatic void unknown_comp(struct spf_sbuf *sbuf, struct spf_unknown *unknown) {\n\tsbuf_puts(sbuf, unknown->name);\n\tsbuf_putc(sbuf, '=');\n\tsbuf_puts(sbuf, unknown->value);\n} \/* unknown_comp() *\/\n\n\nstatic const struct {\n\tvoid (*comp)();\n} spf_term[] = {\n\t[SPF_ALL] = { &all_comp },\n\t[SPF_INCLUDE] = { &include_comp },\n\t[SPF_A] = { &a_comp },\n\t[SPF_MX] = { &mx_comp },\n\t[SPF_PTR] = { &ptr_comp },\n\t[SPF_IP4] = { &ip4_comp },\n\t[SPF_IP6] = { &ip6_comp },\n\t[SPF_EXISTS] = { &exists_comp },\n\n\t[SPF_REDIRECT] = { &redirect_comp },\n\t[SPF_EXP] = { &exp_comp },\n\t[SPF_UNKNOWN] = { &unknown_comp },\n}; \/* spf_term[] *\/\n\nstatic char *term_comp(struct spf_sbuf *sbuf, void *term) {\n\tspf_term[((union spf_term *)term)->type].comp(sbuf, term);\n\n\treturn sbuf->str;\n} \/* term_comp() *\/\n\n\n%%{\n\tmachine spf_grammar;\n\talphtype unsigned char;\n\n\taccess parser->;\n\tvariable p parser->p;\n\tvariable pe parser->pe;\n\tvariable eof parser->eof;\n\n\taction oops {\n\t\tconst unsigned char *part;\n\n\t\tparser->error.lc = fc;\n\n\t\tif (fpc - parser->rdata >= (sizeof parser->error.near \/ 2))\n\t\t\tpart = fpc - (sizeof parser->error.near \/ 2);\n\t\telse\n\t\t\tpart = parser->rdata;\n\n\t\tparser->error.lp = fpc - part;\n\t\tparser->error.rp = fpc - parser->rdata;\n\n\t\tmemset(parser->error.near, 0, sizeof parser->error.near);\n\t\tmemcpy(parser->error.near, part, SPF_MIN(sizeof parser->error.near - 1, parser->pe - part));\n\n\t\tif (SPF_DEBUG) {\n\t\t\tif (isgraph(parser->error.lc))\n\t\t\t\tSPF_SAY(\"`%c' invalid near offset %d of `%s'\", parser->error.lc, parser->error.lp, parser->error.near);\n\t\t\telse\n\t\t\t\tSPF_SAY(\"error near offset %d of `%s'\", parser->error.lp, parser->error.near);\n\t\t}\n\n\t\terror = EINVAL;\n\n\t\tgoto error;\n\t}\n\n\taction term_begin {\n\t\tresult = SPF_PASS;\n\t\tmemset(term, 0, sizeof *term);\n\t\tsbuf_init(&domain);\n\t\tmacros = 0;\n\t\tprefix4 = 32; prefix6 = 128;\n\t}\n\n\taction term_macro {\n\t\tmacros |= 1U << ((tolower((unsigned char)fc)) - 'a');\n\t}\n\n\taction term_end {\n\t\tif (term->type) {\n\t\t\tfbreak;\n\t\t}\n\t}\n\n\taction all_begin {\n\t\tterm->all = all_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction all_end {\n\t}\n\n\taction include_begin {\n\t\tterm->include = include_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction include_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->include.domain, domain.str, sizeof term->include.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction a_begin {\n\t\tterm->a = a_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction a_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->a.domain, domain.str, sizeof term->a.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->a.prefix4 = prefix4;\n\t\tterm->a.prefix6 = prefix6;\n\t}\n\n\taction mx_begin {\n\t\tterm->mx = mx_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction mx_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->mx.domain, domain.str, sizeof term->mx.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\n\t\tterm->mx.prefix4 = prefix4;\n\t\tterm->mx.prefix6 = prefix6;\n\t}\n\n\taction ptr_begin {\n\t\tterm->ptr = ptr_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ptr_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->ptr.domain, domain.str, sizeof term->ptr.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction ip4_begin {\n\t\tterm->ip4 = ip4_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip4_end {\n\t\tspf_pto4(&term->ip4.addr, domain.str);\n\t\tterm->ip4.prefix = prefix4;\n\t}\n\n\taction ip6_begin {\n\t\tterm->ip6 = ip6_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction ip6_end {\n\t\tspf_pto6(&term->ip6.addr, domain.str);\n\t\tterm->ip6.prefix = prefix6;\n\t}\n\n\taction exists_begin {\n\t\tterm->exists = exists_initializer;\n\t\tterm->result = result;\n\t}\n\n\taction exists_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exists.domain, domain.str, sizeof term->exists.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction redirect_begin {\n\t\tterm->redirect = redirect_initializer;\n\t}\n\n\taction redirect_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->redirect.domain, domain.str, sizeof term->redirect.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction exp_begin {\n\t\tterm->exp = exp_initializer;\n\t}\n\n\taction exp_end {\n\t\tif (*domain.str) {\n\t\t\tspf_fixdn(term->exp.domain, domain.str, sizeof term->exp.domain, SPF_DN_TRUNC);\n\t\t\tterm->macros = macros;\n\t\t}\n\t}\n\n\taction unknown_begin {\n\t\tterm->unknown = unknown_initializer;\n\n\t\tsbuf_init(&name);\n\t\tsbuf_init(&value);\n\t}\n\n\taction unknown_end {\n\t\tif (term->type == SPF_UNKNOWN) {\n\t\t\tspf_strlcpy(term->unknown.name, name.str, sizeof term->unknown.name);\n\t\t\tspf_strlcpy(term->unknown.value, value.str, sizeof term->unknown.value);\n\t\t}\n\t}\n\n\t#\n\t# SPF RR grammar per RFC 4408 Sec. 15 App. A.\n\t#\n\tblank = [ \\t];\n\tname = alpha (alnum | \"-\" | \"_\" | \".\")*;\n\n\tdelimiter = \".\" | \"-\" | \"+\" | \",\" | \"\/\" | \"_\" | \"=\";\n\ttransformers = digit* \"r\"i?;\n\n\tmacro_letter = (\"s\"i | \"l\"i | \"o\"i | \"d\"i | \"i\"i | \"p\"i | \"v\"i | \"h\"i | \"c\"i | \"r\"i | \"t\"i) $term_macro;\n\tmacro_literal = (0x21 .. 0x24) | (0x26 .. 0x7e);\n\tmacro_expand = (\"%{\" macro_letter transformers delimiter* \"}\") | \"%%\" | \"%_\" | \"%-\";\n\tmacro_string = (macro_expand | macro_literal)*;\n\n\ttoplabel = (digit* alpha alnum*) | (alnum+ \"-\" (alnum | \"-\")* alnum);\n\tdomain_end = (\".\" toplabel \".\"?) | macro_expand;\n\tdomain_literal = (0x21 .. 0x24) | (0x26 .. 0x2e) | (0x30 .. 0x7e);\n\tdomain_macro = (macro_expand | domain_literal)*;\n\tdomain_spec = (domain_macro domain_end) ${ sbuf_putc(&domain, fc); };\n\n\tqnum = (\"0\" | ((\"3\" .. \"9\") digit?))\n\t | (\"1\" digit{0,2})\n\t | (\"2\" ( (\"0\" .. \"4\" digit?)?\n\t | (\"5\" (\"0\" .. \"5\")?)?\n\t | (\"6\" .. \"9\")?\n\t )\n\t );\n\tip4_network = (qnum \".\" qnum \".\" qnum \".\" qnum) ${ sbuf_putc(&domain, fc); };\n\tip6_network = (xdigit | \":\" | \".\")+ ${ sbuf_putc(&domain, fc); };\n\n\tip4_cidr_length = \"\/\" digit+ >{ prefix4 = 0; } ${ prefix4 *= 10; prefix4 += fc - '0'; };\n\tip6_cidr_length = \"\/\" digit+ >{ prefix6 = 0; } ${ prefix6 *= 10; prefix6 += fc - '0'; };\n\tdual_cidr_length = ip4_cidr_length? (\"\/\" ip6_cidr_length)?;\n\n\tunknown = name >unknown_begin ${ sbuf_putc(&name, fc); }\n\t \"=\" macro_string ${ sbuf_putc(&value, fc); }\n\t %unknown_end;\n\texp = \"exp\"i %exp_begin \"=\" domain_spec %exp_end;\n\tredirect = \"redirect\"i %redirect_begin \"=\" domain_spec %redirect_end;\n\tmodifier = redirect | exp | unknown;\n\n\texists = \"exists\"i %exists_begin \":\" domain_spec %exists_end;\n\tIP6 = \"ip6\"i %ip6_begin \":\" ip6_network ip6_cidr_length? %ip6_end;\n\tIP4 = \"ip4\"i %ip4_begin \":\" ip4_network ip4_cidr_length? %ip4_end;\n\tPTR = \"ptr\"i %ptr_begin (\":\" domain_spec)? %ptr_end;\n\tMX = \"mx\"i %mx_begin (\":\" domain_spec)? dual_cidr_length? %mx_end;\n\tA = \"a\"i %a_begin (\":\" domain_spec)? dual_cidr_length? %a_end;\n\tinklude = \"include\"i %include_begin \":\" domain_spec %include_end;\n\tall = \"all\"i %all_begin %all_end;\n\n\tmechanism = all | inklude | A | MX | PTR | IP4 | IP6 | exists;\n\tqualifier = (\"+\" | \"-\" | \"?\" | \"~\") @{ result = fc; };\n\tdirective = qualifier? mechanism;\n\n\tterm = blank+ (directive | modifier) >term_begin %term_end;\n\tversion = \"v=spf1\"i;\n\trecord = version term* blank*;\n\n\tmain := record $!oops;\n\n\twrite data;\n}%%\n\n\nint spf_parse(union spf_term *term, struct spf_parser *parser, int *error_) {\n\tenum spf_result result = 0;\n\tstruct spf_sbuf domain, name, value;\n\tunsigned prefix4 = 0, prefix6 = 0;\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tterm->type = 0;\n\n\tif (parser->p < parser->pe) {\n\t\t%% write exec;\n\t}\n\n\t*error_ = 0;\n\n\treturn term->type;\nerror:\n\t*error_ = error;\n\n\treturn 0;\n} \/* spf_parse() *\/\n\n\nvoid spf_parser_init(struct spf_parser *parser, const void *rdata, size_t rdlen) {\n\tparser->rdata = rdata;\n\tparser->p = rdata;\n\tparser->pe = parser->p + rdlen;\n\tparser->eof = parser->pe;\n\n\t%% write init;\n} \/* spf_parser_init() *\/\n\n\n\/*\n * E N V I R O N M E N T R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nint spf_env_init(struct spf_env *env, int af, const void *ip, const char *domain, const char *sender) {\n\tmemset(env->r, 0, sizeof env->r);\n\n\tif (af == AF_INET6) {\n\t\tspf_6top(env->i, sizeof env->i, ip, SPF_6TOP_NYBBLE);\n\t\tspf_6top(env->c, sizeof env->c, ip, SPF_6TOP_MIXED);\n\n\t\tspf_strlcpy(env->v, \"ip6\", sizeof env->v);\n\t} else {\n\t\tspf_4top(env->i, sizeof env->i, ip);\n\t\tspf_4top(env->c, sizeof env->c, ip);\n\n\t\tspf_strlcpy(env->v, \"in-addr\", sizeof env->v);\n\t}\n\n\tspf_strlcpy(env->r, \"unknown\", sizeof env->r);\n\n\tspf_itoa(env->t, sizeof env->t, (unsigned long)time(0));\n\n\treturn 0;\n} \/* spf_env_init() *\/\n\n\nstatic size_t spf_getenv_(char **field, int which, struct spf_env *env) {\n\tswitch (tolower((unsigned char)which)) {\n\tcase 's':\n\t\t*field = env->s;\n\t\treturn sizeof env->s;\n\tcase 'l':\n\t\t*field = env->l;\n\t\treturn sizeof env->l;\n\tcase 'o':\n\t\t*field = env->o;\n\t\treturn sizeof env->o;\n\tcase 'd':\n\t\t*field = env->d;\n\t\treturn sizeof env->d;\n\tcase 'i':\n\t\t*field = env->i;\n\t\treturn sizeof env->i;\n\tcase 'p':\n\t\t*field = env->p;\n\t\treturn sizeof env->p;\n\tcase 'v':\n\t\t*field = env->v;\n\t\treturn sizeof env->v;\n\tcase 'h':\n\t\t*field = env->h;\n\t\treturn sizeof env->h;\n\tcase 'c':\n\t\t*field = env->c;\n\t\treturn sizeof env->c;\n\tcase 'r':\n\t\t*field = env->r;\n\t\treturn sizeof env->r;\n\tcase 't':\n\t\t*field = env->t;\n\t\treturn sizeof env->t;\n\tdefault:\n\t\t*field = 0;\n\t\treturn 0;\n\t}\n} \/* spf_getenv_() *\/\n\n\nsize_t spf_getenv(char *dst, size_t lim, int which, const struct spf_env *env) {\n\tchar *src;\n\n\tif (!spf_getenv_(&src, which, (struct spf_env *)env))\n\t\treturn 0;\n\n\treturn spf_strlcpy(dst, src, lim);\n} \/* spf_getenv() *\/\n\n\nsize_t spf_setenv(struct spf_env *env, int which, const char *src) {\n\tsize_t lim, len;\n\tchar *dst;\n\n\tif (!(lim = spf_getenv_(&dst, which, (struct spf_env *)env)))\n\t\treturn strlen(src);\n\n\tlen = spf_strlcpy(dst, src, lim);\n\n\treturn SPF_MIN(lim - 1, len);\n} \/* spf_setenv() *\/\n\n\n\/*\n * M A C R O R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nstatic size_t spf_expand_(char *dst, size_t lim, const char *src, const struct spf_env *env, int *error) {\n\tchar field[512], *part[128], *tmp;\n\tconst char *delim = \".\";\n\tsize_t len, dp = 0, sp = 0;\n\tint macro = 0;\n\tunsigned keep = 0;\n\tunsigned i, j, count;\n\t_Bool tr = 0, rev = 0;\n\n\tif (!(macro = *src))\n\t\treturn 0;\n\n\twhile (isdigit((unsigned char)src[++sp])) {\n\t\tkeep *= 10;\n\t\tkeep += src[sp] - '0';\n\t\ttr = 1;\n\t}\n\n\tif (src[sp] == 'r')\n\t\t{ tr = 1; rev = 1; ++sp; }\n\n\tif (src[sp]) {\n\t\tdelim = &src[sp];\n\t\ttr = 1;\n\t}\n\n\tif (!(len = spf_getenv(field, sizeof field, macro, env)))\n\t\treturn 0;\n\telse if (len >= sizeof field)\n\t\tgoto toolong;\n\n\tif (!tr)\n\t\treturn spf_strlcpy(dst, field, lim);\n\n\tcount = spf_split(spf_lengthof(part), part, field, delim, 0);\n\n\tif (spf_lengthof(part) <= count)\n\t\tgoto toobig;\n\n\tif (rev) {\n\t\tfor (i = 0, j = count - 1; i < j; i++, j--) {\n\t\t\ttmp = part[i];\n\t\t\tpart[i] = part[j];\n\t\t\tpart[j] = tmp;\n\t\t}\n\t}\n\n\tif (keep && keep < count) {\n\t\tfor (i = 0, j = count - keep; j < count; i++, j++)\n\t\t\tpart[i] = part[j];\n\n\t\tcount = keep;\n\t}\n\n\tfor (i = 0; i < count; i++) {\n\t\tif (dp < lim)\n\t\t\tlen = spf_strlcpy(&dst[dp], part[i], lim - dp);\n\t\telse\n\t\t\tlen = strlen(part[i]);\n\n\t\tdp += len;\n\n\t\tif (dp < lim)\n\t\t\tdst[dp] = '.';\n\n\t\t++dp;\n\t}\n\n\tif (dp > 0)\n\t\t--dp;\n\n\treturn dp;\ntoolong:\n\t*error = ENAMETOOLONG;\n\n\treturn 0;\ntoobig:\n\t*error = E2BIG;\n\n\treturn 0;\n} \/* spf_expand_() *\/\n\n\nsize_t spf_expand(char *dst, size_t lim, spf_macros_t *macros, const char *src, const struct spf_env *env, int *error) {\n\tstruct spf_sbuf macro;\n\tsize_t len, dp = 0, sp = 0;\n\n\t*error = 0;\n\n\tdo {\n\t\twhile (src[sp] && src[sp] != '%') {\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\t\t}\n\n\t\tif (!src[sp])\n\t\t\tbreak;\n\n\t\tswitch (src[++sp]) {\n\t\tcase '{':\n\t\t\tsbuf_init(¯o);\n\n\t\t\twhile (src[++sp] && src[sp] != '}')\n\t\t\t\tsbuf_putc(¯o, src[sp]);\n\n\t\t\tif (src[sp] != '}')\n\t\t\t\tbreak;\n\n\t\t\t++sp;\n\n\t\t\tif (isalpha((unsigned char)*macro.str))\n\t\t\t\t*macros |= 1U << (tolower((unsigned char)*macro.str) - 'a');\n\n\t\t\tlen = (dp < lim)\n\t\t\t ? spf_expand_(&dst[dp], lim - dp, macro.str, env, error)\n\t\t\t : spf_expand_(0, 0, macro.str, env, error);\n\n\t\t\tif (!len && *error)\n\t\t\t\treturn 0;\n\n\t\t\tdp += len;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (dp < lim)\n\t\t\t\tdst[dp] = src[sp];\n\t\t\t++sp; ++dp;\n\n\t\t\tbreak;\n\t\t}\n\t} while (src[sp]);\n\n\tif (lim)\n\t\tdst[SPF_MIN(dp, lim - 1)] = '\\0';\n\n\treturn dp;\n} \/* spf_expand() *\/\n\n\n_Bool spf_isset(spf_macros_t macros, int which) {\n\tif (!isalpha((unsigned char)which))\n\t\treturn 0;\n\n\treturn !!(macros & (1U << (tolower((unsigned char)which) - 'a')));\n} \/* spf_isset() *\/\n\n\nspf_macros_t spf_macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tspf_expand(0, 0, ¯os, src, env, &error);\n\n\treturn macros;\n} \/* spf_macros() *\/\n\n\n\/*\n * V I R T U A L M A C H I N E R O U T I N E S\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nenum vm_type {\n\tT_INT = 0x01,\n\tT_REF = 0x02,\n\tT_MEM = 0x04,\n\n\tT_ANY = T_INT|T_REF|T_MEM,\n}; \/* enum vm_type *\/\n\nenum vm_opcode {\n\tOP_HALT,\t\/* 0\/0 *\/\n\tOP_TRAP,\n\tOP_NOOP,\n\n\tOP_PC,\t\t\/* 0\/1 Push vm.pc *\/\n\tOP_CALL,\t\/* 2\/N Pops #params and address. Inserts return address below parameters and jumps to address. *\/\n\tOP_RET,\t\t\/* Pops #params, shifts return address (#params-1) to top, pops and jumps *\/\n\tOP_EXIT,\t\/* Same as OP_RET, but return address follows vm.end, which is removed and restored. *\/\n\n\tOP_TRUE,\t\/* 0\/1 Push true. *\/\n\tOP_FALSE,\t\/* 0\/1 Push false. *\/\n\tOP_ZERO,\t\/* 0\/1 Push 0. *\/\n\tOP_ONE,\t\t\/* 0\/1 Push 1 *\/\n\tOP_TWO,\t\t\/* 0\/1 Push 2 *\/\n\tOP_THREE,\t\/* 0\/1 Push 3 *\/\n\tOP_I8,\t\t\/* 0\/1 Decode next op and push as T_INT *\/ \n\tOP_I16,\t\t\/* 0\/1 Decode next 2 ops and push as T_INT *\/ \n\tOP_I32,\t\t\/* 0\/1 Decode next 4 ops and push as T_INT *\/\n\tOP_NIL,\t\t\/* 0\/1 Push 0 as T_REF *\/\n\tOP_REF,\t\t\/* 0\/1 Decode next sizeof(intptr_t) opts and push as T_REF *\/\n\tOP_MEM,\t\t\/* 0\/1 Decode next sizeof(intptr_t) ops and push as T_MEM *\/\n\tOP_STR,\t\t\/* 0\/1 Decode until next NUL, allocate and push as T_MEM. *\/\n\tOP_IN4,\t\t\/* 0\/1 Decode (struct in_addr) and push as T_MEM. *\/\n\tOP_IN6,\t\t\/* 0\/1 Decode (struct in6_addr) and push as T_MEM. *\/\n\n\tOP_DEC,\t\t\/* 1\/1 Decrement S(-1) *\/\n\tOP_INC,\t\t\/* 1\/1 Increment S(-1) *\/\n\tOP_NEG,\t\t\/* 1\/1 Arithmetically negate S(-1) (changes type to T_INT) *\/\n\tOP_ADD,\t\t\/* 2\/1 Push S(-2) + S(-1). *\/\n\tOP_NOT,\t\t\/* 1\/1 Logically Negate S(-1) (changes type to T_INT) *\/\n\n\tOP_EQ,\t\t\/* 2\/1 Push S(-2) == S(-1) *\/\n\tOP_LT,\t\t\/* 2\/1 Push S(-2) < S(-1) *\/\n\n\tOP_JMP,\t\t\/* 2\/0 If S(-2) is non-zero, jump S(-1) instruction *\/\n\tOP_GOTO,\t\/* 2\/0 If S(-2) is non-zero, goto I(S(-1)) *\/\n\n\tOP_POP,\t\t\/* 0\/0 Pop item from stack *\/\n\tOP_DUP,\t\t\/* 1\/2 Dup item at top of stack *\/\n\tOP_LOAD,\t\/* 1\/1 Push a copy of S(S(-1)) onto stack (changes T_MEM to T_REF) *\/\n\tOP_STORE,\t\/* 2\/0 Pop index and item and store at index (index computed after popping). *\/\n\tOP_MOVE,\t\/* 1\/1 Move S(S(-1)) to top of stack, shifting everything else down. *\/\n\tOP_SWAP,\t\/* 0\/0 Swap top two items. *\/\n\n\tOP_GETENV,\t\/* 1\/1 Push spf_getenv(S(-1)) *\/\n\tOP_SETENV,\t\/* 2\/0 Do spf_setenv(S(-1), S(-2)) *\/\n\n\tOP_EXPAND,\t\/* 1\/1 Push spf_expand(S(-1)). *\/\n\tOP_ISSET,\t\/* 2\/1 Check for macro S(-1) in S(-2). *\/\n\n\tOP_SUBMIT,\t\/* 2\/0 dns_res_submit(). in: 2(qtype, qname) out: 0 *\/\n\tOP_FETCH,\t\/* 0\/1 dns_res_fetch(). in: 0 out: 1(struct dns_packet) *\/\n\tOP_QNAME,\t\/* 1\/1 Pop packet, Push QNAME. *\/\n\tOP_GREP,\t\/* 3\/1 Push iterator. Takes QNAME, section and type. *\/\n\tOP_NEXT,\t\/* 1\/2 Push next stringized RR data. *\/\n\n\tOP_ADDRINFO,\t\/* 3\/0 dns_ai_open(). *\/\n\tOP_NEXTENT,\t\/* 0\/1 dns_ai_nextent(). *\/\n\n\tOP_CHECK,\t\/* 1\/2 Pop target domain, push exp and result. *\/\n\tOP_COMP,\t\/* 1\/1 Compile S(-1), push code address or 0 if invalid policy. *\/\n\n\tOP_FCRD,\t\/* 0\/0 Forward-confirmed Reverse DNS *\/\n\tOP_FCRDx,\t\/* 1\/0 Pop addrinfo; if A\/AAAA matches ${i}, add .ai_canonname as FCRD *\/\n\n\tOP_SLEEP,\t\/* 1\/0 Sleep *\/\n\n\tOP_CAT,\t\t\/* 2\/1 Concatenate into string *\/\n\tOP_CMP,\t\t\/* 2\/1 strcmp() *\/\n\tOP_LC, \/* 1\/1 strtolower() *\/\n\tOP_GETS,\t\/* 0\/1 Push line from stdin *\/\n\tOP_PUTI,\t\/* 1\/0 Print integer *\/\n\tOP_PUTS,\t\/* 1\/0 Print string *\/\n\tOP_PUTP,\t\/* 1\/0 Print `struct dns_packet' *\/\n\tOP_PUTA,\t\/* 1\/0 Print `struct addrinfo' *\/\n\tOP_RSTR,\t\/* 1\/1 Convert to string with spf_strresult() *\/\n\tOP_ATOI,\t\/* 1\/1 Convert to string with atoi() *\/\n\tOP_4TOP,\t\/* 1\/1 Convert (struct in_addr) to string *\/\n\tOP_PTO4,\t\/* 1\/1 Convert string to (struct in_addr) *\/\n\tOP_6TOP,\t\/* 1\/1 Convert (struct in6_addr) to string *\/\n\tOP_PTO6,\t\/* 1\/1 Convert string to (struct in6_addr) *\/\n\n\tOP_INCLUDE,\n\tOP_A,\n\tOP_MX,\n\tOP_A_MXv,\n\tOP_PTR,\n\tOP_IP4,\n\tOP_IP6,\n\tOP_EXISTS,\n\tOP_EXP,\n\n\tOP__COUNT,\n}; \/* enum vm_opcode *\/\n\n\n#define VM_MAXCODE 1024\n#define VM_MAXSTACK 64\n\nstruct spf_resolver;\n\nstruct spf_vm {\n\tunsigned char code[VM_MAXCODE];\n\tunsigned pc, end;\n\n\tunsigned char type[VM_MAXSTACK];\n\tintptr_t stack[VM_MAXSTACK];\n\tunsigned sp;\n\n\tjmp_buf trap;\n\n\tstruct spf_resolver *spf;\n}; \/* struct spf_vm *\/\n\nstatic void vm_init(struct spf_vm *vm, struct spf_resolver *spf) {\n\tvm->spf = spf;\n} \/* vm_init() *\/\n\n\n\/** forward definition *\/\nstruct spf_resolver {\n\tstruct spf_env env;\n\n\tstruct spf_vm vm;\n\n\tstruct dns_resolver *res;\n\tstruct dns_addrinfo *ai;\n\n\tstruct {\n\t\t_Bool done;\n\n\t\tunion {\n\t\t\tstruct dns_packet ptr;\n\t\t\tchar buf[dns_p_calcsize(512)];\n\t\t};\n\t} fcrd;\n\n\tenum spf_result result;\n\tconst char *exp;\n}; \/* struct spf_resolver *\/\n\n\nstatic void vm_throw() __attribute__((__noreturn__));\nstatic void vm_throw(struct spf_vm *vm, int error) {\n\t_longjmp(vm->trap, (error)? error : EINVAL);\n} \/* vm_throw() *\/\n\n\/*\n * NOTE: Using a macro because it delays evaluation of `error' to allow\n * code like:\n *\n * \tvm_assert(vm, !(error = do_something()), error)\n * \tvm_assert(vm, (rval = do_something(&error)), error)\n * \tvm_assert(vm, (p = malloc()), errno)\n *\/\n#define vm_assert(vm, cond, error) do { \\\n\tif (spf_unlikely(!(cond))) { \\\n\t\tSPF_SAY(\"fail: %s\", SPF_STRINGIFY(cond)); \\\n\t\tvm_throw((vm), (error)); \\\n\t} \\\n} while (0)\n\n\nstatic inline void vm_extend(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, spf_lengthof(vm->stack) - vm->sp >= n, EFAULT);\n} \/* vm_extend() *\/\n\n\nstatic inline int vm_indexof(struct spf_vm *vm, int p) {\n\tif (spf_likely(p < 0))\n\t\tp = vm->sp + p;\n\n\tvm_assert(vm, p >= 0 && p < vm->sp, EFAULT);\n\n\treturn p;\n} \/* vm_indexof() *\/\n\n\nstatic inline enum vm_type vm_typeof(struct spf_vm *vm, int p) {\n\treturn vm->type[vm_indexof(vm, p)];\n} \/* vm_typeof() *\/\n\n\nstatic void t_free(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tswitch (t) {\n\tcase T_INT:\n\t\t\/* FALL THROUGH *\/\n\tcase T_REF:\n\t\tbreak;\n\tcase T_MEM:\n\t\tfree((void *)v);\n\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EFAULT);\n\t} \/* switch() *\/\n} \/* t_free() *\/\n\n\nstatic inline intptr_t vm_pop(struct spf_vm *vm, enum vm_type t) {\n\tintptr_t v;\n\tvm_assert(vm, vm->sp, EFAULT);\n\tvm->sp--;\n\tvm_assert(vm, (vm->type[vm->sp] & t), EINVAL);\n\tt = vm->type[vm->sp];\n\tv = vm->stack[vm->sp];\n\tt_free(vm, t, v);\n\tvm->type[vm->sp] = 0;\n\tvm->stack[vm->sp] = 0;\n\treturn v;\n} \/* vm_pop() *\/\n\n\nstatic void vm_discard(struct spf_vm *vm, unsigned n) {\n\tvm_assert(vm, n <= vm->sp, EFAULT);\n\twhile (n--)\n\t\tvm_pop(vm, T_ANY);\n} \/* vm_discard() *\/\n\n\nstatic inline intptr_t vm_push(struct spf_vm *vm, enum vm_type t, intptr_t v) {\n\tvm_assert(vm, vm->sp < spf_lengthof(vm->stack), ENOMEM);\n\n\tvm->type[vm->sp] = t;\n\tvm->stack[vm->sp] = v;\n\n\tvm->sp++;\n\n\treturn v;\n} \/* vm_push() *\/\n\n\n#define vm_swap(vm) vm_move((vm), -2)\n\nstatic intptr_t vm_move(struct spf_vm *vm, int p) {\n\tenum vm_type t;\n\tintptr_t v;\n\tint i;\n\n\tp = vm_indexof(vm, p);\n\tt = vm->type[p];\n\tv = vm->stack[p];\n\n\ti = p;\n\n\t\/*\n\t * DO NOT move a T_MEM item over an equivalent T_REF, because that\n\t * breaks garbage-collection. Instead, swap types with the first\n\t * equivalent T_REF found. (WARNING: This breaks if T_REF points\n\t * into a T_MEM object. Just don't do that--nest pointers and swap\n\t * stack positions.)\n\t *\/\n\tif (v == T_MEM) {\n\t\tfor (; i < vm->sp - 1; i++) {\n\t\t\tif (vm->type[i + 1] == T_REF && vm->stack[i + 1] == v) {\n\t\t\t\tvm->type[i + 1] = T_MEM;\n\t\t\t\tt = T_REF;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvm->type[i] = vm->type[i + 1];\n\t\t\tvm->stack[i] = vm->stack[i + 1];\n\t\t}\n\t}\n\n\tfor (; i < vm->sp - 1; i++) {\n\t\tvm->type[i] = vm->type[i + 1];\n\t\tvm->stack[i] = vm->stack[i + 1];\n\t}\n\n\tvm->type[i] = t;\n\tvm->stack[i] = v;\n\n\treturn v;\n} \/* vm_move() *\/\n\n\nstatic intptr_t vm_strdup(struct spf_vm *vm, const void *s) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = strdup(s)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)v);\n\n\treturn (intptr_t)v;\n} \/* vm_strdup() *\/\n\n\nstatic intptr_t vm_memdup(struct spf_vm *vm, const void *p, size_t len) {\n\tvoid *v;\n\n\tvm_extend(vm, 1);\n\tvm_assert(vm, (v = malloc(len)), errno);\n\tvm_push(vm, T_MEM, (intptr_t)memcpy(v, p, len));\n\n\treturn (intptr_t)v;\n} \/* vm_memdup() *\/\n\n\nstatic inline intptr_t vm_peek(struct spf_vm *vm, int p, enum vm_type t) {\n\tp = vm_indexof(vm, p);\n\tvm_assert(vm, (t & vm->type[p]), EINVAL);\n\treturn vm->stack[p];\n} \/* vm_peek() *\/\n\n\nstatic inline intptr_t vm_poke(struct spf_vm *vm, int p, enum vm_type t, intptr_t v) {\n\tp = vm_indexof(vm, p);\n\tt_free(vm, vm->type[p], vm->stack[p]);\n\tvm->type[p] = t;\n\tvm->stack[p] = v;\n\treturn v;\n} \/* vm_poke() *\/\n\n\nstatic inline int vm_opcode(struct spf_vm *vm) {\n\tvm_assert(vm, vm->pc < spf_lengthof(vm->code), EFAULT);\n\n\treturn vm->code[vm->pc];\n} \/* vm_opcode() *\/\n\n\n#define vm_emit_(vm, code, v, ...) vm_emit((vm), (code), (v))\n#define vm_emit(vm, ...) vm_emit_((vm), __VA_ARGS__, 0)\n\nstatic unsigned (vm_emit)(struct spf_vm *vm, enum vm_opcode code, intptr_t v_) {\n\tuintptr_t v;\n\tvoid *p;\n\tunsigned i, n;\n\n\tvm_assert(vm, vm->end < spf_lengthof(vm->code), ENOMEM);\n\n\tvm->code[vm->end] = code;\n\n\tswitch (code) {\n\tcase OP_I8:\n\t\tn = 1; goto copy;\n\tcase OP_I16:\n\t\tn = 2; goto copy;\n\tcase OP_I32:\n\t\tn = 4; goto copy;\n\tcase OP_REF:\n\t\t\/* FALL THROUGH *\/\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\ncopy:\n\t\tv = (uintptr_t)v_;\n\t\tvm_assert(vm, vm->end <= spf_lengthof(vm->code) - n, ENOMEM);\n\n\t\tfor (i = 0; i < n; i++)\n\t\t\tvm->code[++vm->end] = 0xffU & (v >> (8U * ((n-i)-1)));\n\n\t\treturn vm->end++;\n\tcase OP_STR:\n\t\tp = (void *)v_;\n\t\tn = strlen(p) + 1;\nembed:\n\t\tvm_assert(vm, spf_lengthof(vm->code) - (vm->end + 1) >= n, ENOMEM);\n\t\tmemcpy(&vm->code[++vm->end], p, n);\n\t\tvm->end += n;\n\n\t\treturn vm->end - 1;\n\tcase OP_IN4:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in_addr);\n\n\t\tgoto embed;\n\tcase OP_IN6:\n\t\tp = (void *)v_;\n\t\tn = sizeof (struct in6_addr);\n\n\t\tgoto embed;\n\tdefault:\n\t\treturn vm->end++;\n\t} \/* switch() *\/\n} \/* vm_emit() *\/\n\n\n#define HALT(sub) sub_emit((sub), OP_HALT)\n#define TRAP(sub) sub_emit((sub), OP_TRAP)\n#define NOOP(sub) sub_emit((sub), OP_NOOP)\n#define PC(sub) sub_emit((sub), OP_PC)\n#define CALL(sub) sub_emit((sub), OP_CALL)\n#define RET(sub) sub_emit((sub), OP_RET)\n#define EXIT(sub) sub_emit((sub), OP_EXIT)\n#define TRUE(sub) sub_emit((sub), OP_TRUE)\n#define FALSE(sub) sub_emit((sub), OP_FALSE)\n#define ZERO(sub) sub_emit((sub), OP_ZERO)\n#define ONE(sub) sub_emit((sub), OP_ONE)\n#define TWO(sub) sub_emit((sub), OP_TWO)\n#define THREE(sub) sub_emit((sub), OP_THREE)\n#define I8(sub,v) sub_emit((sub), OP_I8, (v))\n#define I16(sub,v) sub_emit((sub), OP_I16, (v))\n#define I32(sub,v) sub_emit((sub), OP_I32, (v))\n#define NIL(sub) sub_emit((sub), OP_NIL)\n#define REF(sub,v) sub_emit((sub), OP_REF, (v))\n#define MEM(sub,v) sub_emit((sub), OP_MEM, (v))\n#define STR(sub,v) sub_emit((sub), OP_STR, (v))\n#define IN4(sub,v) sub_emit((sub), OP_IN4, (v))\n#define IN6(sub,v) sub_emit((sub), OP_IN6, (v))\n#define DEC(sub) sub_emit((sub), OP_DEC)\n#define INC(sub) sub_emit((sub), OP_INC)\n#define NEG(sub) sub_emit((sub), OP_NEG)\n#define ADD(sub) sub_emit((sub), OP_ADD)\n#define NOT(sub) sub_emit((sub), OP_NOT)\n#define EQ(sub) sub_emit((sub), OP_EQ)\n#define LT(sub) sub_emit((sub), OP_LT)\n#define POP(sub) sub_emit((sub), OP_POP)\n#define DUP(sub) sub_emit((sub), OP_DUP)\n#define LOAD(sub) sub_emit((sub), OP_LOAD)\n#define STORE(sub) sub_emit((sub), OP_STORE)\n#define MOVE(sub) sub_emit((sub), OP_MOVE)\n#define SWAP(sub) sub_emit((sub), OP_SWAP)\n#define GOTO(sub) sub_emit((sub), OP_GOTO)\n#define GETENV(sub) sub_emit((sub), OP_GETENV)\n#define SETENV(sub) sub_emit((sub), OP_SETENV)\n#define EXPAND(sub) sub_emit((sub), OP_EXPAND)\n#define ISSET(sub) sub_emit((sub), OP_ISSET)\n#define SUBMIT(sub) sub_emit((sub), OP_SUBMIT)\n#define FETCH(sub) sub_emit((sub), OP_FETCH)\n#define QNAME(sub) sub_emit((sub), OP_QNAME)\n#define GREP(sub) sub_emit((sub), OP_GREP)\n#define NEXT(sub) sub_emit((sub), OP_NEXT)\n#define CHECK(sub) sub_emit((sub), OP_CHECK)\n#define COMP(sub) sub_emit((sub), OP_COMP)\n#define FCRD(sub) sub_emit((sub), OP_FCRD)\n#define FCRDx(sub) sub_emit((sub), OP_FCRDx)\n#define CAT(sub) sub_emit((sub), OP_CAT)\n#define CMP(sub) sub_emit((sub), OP_CMP)\n#define LC(sub) sub_emit((sub), OP_LC)\n#define PUTI(sub) sub_emit((sub), OP_PUTI)\n#define PUTS(sub) sub_emit((sub), OP_PUTS)\n#define PUTP(sub) sub_emit((sub), OP_PUTP)\n\n#define SUB_MAXJUMP 64\n#define SUB_MAXLABEL 8\n\n#define L0(sub) sub_label((sub), 0)\n#define L1(sub) sub_label((sub), 1)\n#define L2(sub) sub_label((sub), 2)\n#define L3(sub) sub_label((sub), 3)\n#define L4(sub) sub_label((sub), 4)\n#define L5(sub) sub_label((sub), 5)\n#define L6(sub) sub_label((sub), 6)\n#define L7(sub) sub_label((sub), 7)\n\n#define J0(sub) sub_jump((sub), 0)\n#define J1(sub) sub_jump((sub), 1)\n#define J2(sub) sub_jump((sub), 2)\n#define J3(sub) sub_jump((sub), 3)\n#define J4(sub) sub_jump((sub), 4)\n#define J5(sub) sub_jump((sub), 5)\n#define J6(sub) sub_jump((sub), 6)\n#define J7(sub) sub_jump((sub), 7)\n\nstruct vm_sub {\n\tstruct spf_vm *vm;\n\tstruct { unsigned id, cp; } j[SUB_MAXJUMP];\n\tunsigned jc, l[SUB_MAXLABEL];\n}; \/* struct vm_sub *\/\n\nstatic void sub_init(struct vm_sub *sub, struct spf_vm *vm)\n\t{ memset(sub, 0, sizeof *sub); sub->vm = vm; }\n\n#define sub_emit(sub, ...) vm_emit((sub)->vm, __VA_ARGS__)\n\nstatic void sub_link(struct vm_sub *sub) {\n\tunsigned i, lp, jp;\n\n\tfor (i = 0; i < sub->jc; i++) {\n\t\tlp = sub->l[sub->j[i].id];\n\t\tjp = sub->j[i].cp;\n\n\t\tif (lp < jp) {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = jp - lp;\n\t\t\tsub->vm->code[jp-1] = OP_NEG;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t} else {\n\t\t\tsub->vm->code[jp-3] = OP_I8;\n\t\t\tsub->vm->code[jp-2] = lp - jp;\n\t\t\tsub->vm->code[jp-1] = OP_NOOP;\n\t\t\tsub->vm->code[jp-0] = OP_JMP;\n\t\t}\n\t}\n} \/* sub_link() *\/\n\nstatic void sub_label(struct vm_sub *sub, unsigned id) {\n\tsub->l[id % spf_lengthof(sub->l)] = sub->vm->end;\n} \/* sub_label() *\/\n\nstatic void sub_jump(struct vm_sub *sub, unsigned id) {\n\tvm_assert(sub->vm, sub->jc < spf_lengthof(sub->j), ENOMEM);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tvm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].cp = vm_emit(sub->vm, OP_TRAP);\n\tsub->j[sub->jc].id = id % spf_lengthof(sub->l);\n\tsub->jc++;\n} \/* sub_jump() *\/\n\n\nstatic void op_pop(struct spf_vm *vm) {\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_pop() *\/\n\n\nstatic void op_dup(struct spf_vm *vm) {\n\tintptr_t v;\n\tint t;\n\n\tv = vm_peek(vm, -1, T_ANY);\n\tt = vm_typeof(vm, -1);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, v);\n\n\tvm->pc++;\n} \/* op_dup() *\/\n\n\nstatic void op_load(struct spf_vm *vm) {\n\tint p, t;\n\n\tp = vm_pop(vm, T_INT);\n\tt = vm_typeof(vm, p);\n\n\t\/* convert memory to pointer to prevent double free's *\/\n\tvm_push(vm, (t & (T_MEM))? T_REF : t, vm_peek(vm, p, T_ANY));\n\n\tvm->pc++;\n} \/* op_load() *\/\n\n\nstatic void op_store(struct spf_vm *vm) {\n\tint p, t;\n\tintptr_t v;\n\tp = vm_indexof(vm, vm_pop(vm, T_INT));\n\tv = vm_pop(vm, T_INT); \/* restrict to T_INT so we don't have to worry about GC. *\/\n\tvm_poke(vm, p, T_INT, v);\n\tvm->pc++;\n} \/* op_store() *\/\n\n\nstatic void op_move(struct spf_vm *vm) {\n\tvm_move(vm, vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_move() *\/\n\n\nstatic void op_swap(struct spf_vm *vm) {\n\tvm_swap(vm);\n\tvm->pc++;\n} \/* op_swap() *\/\n\n\nstatic void op_jmp(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm->pc + vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_jmp() *\/\n\n\nstatic void op_goto(struct spf_vm *vm) {\n\tintptr_t cond = vm_peek(vm, -2, T_ANY);\n \tint pc = vm_peek(vm, -1, T_INT);\n\n\tvm_discard(vm, 2);\n\n\tif (cond) {\n\t\tvm_assert(vm, pc >= 0 && pc < vm->end, EFAULT);\n\t\tvm->pc = pc;\n\t} else\n\t\tvm->pc++;\n} \/* op_goto() *\/\n\n\nstatic void op_call(struct spf_vm *vm) {\n\tint f, n, i;\n\n\tf = vm_pop(vm, T_INT);\n\tn = vm_pop(vm, T_INT);\n\n\tvm_push(vm, T_INT, vm->pc + 1);\n\n\t\/* swap return address with parameters *\/\n\tfor (i = 0; i < n; i++)\n\t\tvm_move(vm, -(n + 1));\n\n\tvm->pc = f;\n} \/* op_call() *\/\n\n\nstatic void op_ret(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_ret() *\/\n\n\nstatic void op_exit(struct spf_vm *vm) {\n\tint n;\n\n\tn = vm_pop(vm, T_INT);\n\n\t\/* move code end to top *\/\n\tvm_move(vm, -(n + 2));\n\n\tvm->end = vm_pop(vm, T_INT);\n\n\t\/* move return address to top *\/\n\tvm_move(vm, -(n + 1));\n\n\tvm->pc = vm_pop(vm, T_INT);\n} \/* op_exit() *\/\n\n\nstatic void op_trap(struct spf_vm *vm) {\n\tvm_throw(vm, EFAULT);\n} \/* op_trap() *\/\n\n\nstatic void op_noop(struct spf_vm *vm) {\n\tvm->pc++;\n} \/* op_noop() *\/\n\n\nstatic void op_pc(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm->pc);\n\tvm->pc++;\n} \/* op_pc() *\/\n\n\nstatic void op_lit(struct spf_vm *vm) {\n\tenum vm_opcode code = vm->code[vm->pc];\n\tuintptr_t v;\n\tenum vm_type t;\n\tint i, n;\n\n\tn = 0;\n\tv = 0;\n\n\tswitch (code) {\n\tcase OP_TRUE: case OP_FALSE:\n\t\tv = (code == OP_TRUE);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_ZERO: case OP_ONE: case OP_TWO: case OP_THREE:\n\t\tv = (code - OP_ZERO);\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_NIL:\n\t\tv = 0;\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_I8:\n\t\tn = 1;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I16:\n\t\tn = 2;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_I32:\n\t\tn = 4;\n\t\tt = T_INT;\n\t\tbreak;\n\tcase OP_REF:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_REF;\n\t\tbreak;\n\tcase OP_MEM:\n\t\tn = sizeof (uintptr_t);\n\t\tt = T_MEM;\n\t\tbreak;\n\tdefault:\n\t\tvm_throw(vm, EINVAL);\n\t} \/* switch () *\/\n\n\tvm_assert(vm, vm->pc + n < vm->end, EFAULT);\n\n\tfor (i = 0; i < n; i++) {\n\t\tv <<= 8;\n\t\tv |= 0xff & vm->code[++vm->pc];\n\t}\n\n\tvm_push(vm, t, (intptr_t)v);\n\tvm->pc++;\n} \/* op_lit() *\/\n\n\nstatic void op_str(struct spf_vm *vm) {\n\tunsigned pe, pc = vm->pc + 1;\n\n\tfor (pe = pc; pe < spf_lengthof(vm->code) && vm->code[pe]; pe++)\n\t\t;;\n\tpe++;\n\tvm_assert(vm, pe < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], pe - pc);\n\n\tvm->pc = pe;\n} \/* op_str() *\/\n\n\nstatic void op_in4(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in_addr));\n\n\tvm->pc = pc + sizeof (struct in_addr);\n} \/* op_in4() *\/\n\n\nstatic void op_in6(struct spf_vm *vm) {\n\tunsigned pc = vm->pc + 1;\n\n\tvm_assert(vm, pc + sizeof (struct in6_addr) < spf_lengthof(vm->code), EFAULT);\n\tvm_memdup(vm, &vm->code[pc], sizeof (struct in6_addr));\n\n\tvm->pc = pc + sizeof (struct in6_addr);\n} \/* op_in6() *\/\n\n\nstatic void op_dec(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) - 1);\n\tvm->pc++;\n} \/* op_dec() *\/\n\n\nstatic void op_inc(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, vm_peek(vm, -1, T_INT) + 1);\n\tvm->pc++;\n} \/* op_inc() *\/\n\n\nstatic void op_neg(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, -vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_neg() *\/\n\n\nstatic void op_add(struct spf_vm *vm) {\n\tvm_push(vm, T_INT, vm_pop(vm, T_INT) + vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_add() *\/\n\n\nstatic void op_not(struct spf_vm *vm) {\n\tvm_poke(vm, -1, T_INT, !vm_peek(vm, -1, T_ANY));\n\tvm->pc++;\n} \/* op_not() *\/\n\n\nstatic void op_eq(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tvm_push(vm, T_INT, (vm_pop(vm, t) == vm_pop(vm, t)));\n\n\tvm->pc++;\n} \/* op_eq() *\/\n\n\nstatic void op_lt(struct spf_vm *vm) {\n\tenum vm_type t = vm_typeof(vm, -1);\n\tintptr_t a, b;\n\n\tif ((T_REF|T_MEM) & t)\n\t\tt = T_REF|T_MEM;\n\n\tb = vm_pop(vm, t);\n\ta = vm_pop(vm, t);\n\n\tvm_push(vm, T_INT, a < b);\n\n\tvm->pc++;\n} \/* op_lt() *\/\n\n\nstatic void op_submit(struct spf_vm *vm) {\n\tvoid *qname = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tint qtype = vm_peek(vm, -1, T_INT);\n\tint error;\n\n\tSPF_SAY(\"querying %s IN %s\", (char *)qname, dns_strtype(qtype));\n\n\terror = dns_res_submit(vm->spf->res, qname, qtype, DNS_C_IN);\n\tvm_assert(vm, !error, error);\n\n\tvm_discard(vm, 2);\n\n\tvm->pc++;\n} \/* op_submit() *\/\n\n\nstatic void op_fetch(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tint error;\n\n\terror = dns_res_check(vm->spf->res);\n\tvm_assert(vm, !error, error);\n\n\tvm_extend(vm, 1);\n\tpkt = dns_res_fetch(vm->spf->res, &error);\n\tvm_assert(vm, !!pkt, error);\n\tvm_push(vm, T_MEM, (intptr_t)pkt);\n\n\tvm->pc++;\n} \/* op_fetch() *\/\n\n\nstatic void op_qname(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar qname[DNS_D_MAXNAME + 1];\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\n\tvm_assert(vm, dns_d_expand(qname, sizeof qname, 12, pkt, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, qname);\n\n\tvm->pc++;\n} \/* op_qname() *\/\n\n\nstruct vm_grep {\n\tint type;\n\tstruct dns_rr_i iterator;\n\tchar name[DNS_D_MAXNAME + 1];\n}; \/* struct vm_grep *\/\n\nstatic void op_grep(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tchar *name;\n\tstruct vm_grep *grep;\n\tint sec, type, error;\n\n\tpkt = (void *)vm_peek(vm, -4, T_REF|T_MEM);\n\tname = (void *)vm_peek(vm, -3, T_REF|T_MEM);\n\tsec = vm_peek(vm, -2, T_INT);\n\ttype = vm_peek(vm, -1, T_INT);\n\n\tvm_assert(vm, (grep = malloc(sizeof *grep)), errno);\n\n\tmemset(&grep->iterator, 0, sizeof grep->iterator);\n\n\tgrep->type = type;\n\n\tif (name && *name) {\n\t\tspf_strlcpy(grep->name, name, sizeof grep->name);\n\t\tgrep->iterator.name = grep->name;\n\t}\n\n\tgrep->iterator.section = sec;\n\tgrep->iterator.type = abs(type);\n\n\tdns_rr_i_init(&grep->iterator, pkt);\n\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_MEM, (intptr_t)grep);\n\n\tvm->pc++;\n} \/* op_grep() *\/\n\n\nstatic _Bool txt_isspf(struct dns_txt *txt) {\n\treturn (txt->len >= sizeof \"v=spf1\" && !memcmp(txt->data, \"v=spf1\", sizeof \"v=spf1\" - 1));\n} \/* txt_isspf() *\/\n\nstatic void op_next(struct spf_vm *vm) {\n\tstruct dns_packet *pkt;\n\tstruct vm_grep *grep;\n\tstruct dns_rr rr;\n\tint error;\n\n\tpkt = (void *)vm_peek(vm, -2, T_REF|T_MEM);\n\tgrep = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\ngrep:\n\tif (dns_rr_grep(&rr, 1, &grep->iterator, pkt, &error)) {\n\t\tchar rd[DNS_D_MAXNAME + 1];\n\t\tunion dns_any any;\n\t\tchar *txt;\n\n\t\tdns_any_init(&any, sizeof any);\n\n\t\tvm_assert(vm, !(error = dns_any_parse(&any, &rr, pkt)), error);\n\n\t\tswitch (rr.type) {\n\t\tcase DNS_T_TXT:\n\t\t\tif (grep->type == -DNS_T_TXT && !txt_isspf(&any.txt))\n\t\t\t\tgoto grep;\n\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase DNS_T_SPF:\n\t\t\ttxt = (char *)vm_memdup(vm, any.txt.data, any.txt.len + 1);\n\t\t\ttxt[any.txt.len] = '\\0';\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!dns_any_print(rd, sizeof rd, &any, rr.type))\n\t\t\t\tgoto none;\n\n\t\t\tvm_strdup(vm, rd);\n\n\t\t\tbreak;\n\t\t} \/* switch() *\/\n\t} else {\nnone:\n\t\tvm_push(vm, T_REF, 0);\n\t}\n\n\tvm->pc++;\n} \/* op_next() *\/\n\n\nstatic void op_addrinfo(struct spf_vm *vm) {\n\tstatic const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME };\n\tconst char *host;\n\tchar serv[16];\n\tint qtype, error;\n\n\thost = (char *)vm_peek(vm, -3, T_REF|T_MEM);\n\n\tif (T_INT == vm_typeof(vm, -2))\n\t\tspf_itoa(serv, sizeof serv, vm_peek(vm, -2, T_INT));\n\telse\n\t\tspf_strlcpy(serv, (char *)vm_peek(vm, -2, T_REF|T_MEM), sizeof serv);\n\n\tqtype = vm_peek(vm, -1, T_INT);\n\n\tSPF_SAY(\"querying %s IN %s\", host, dns_strtype(qtype));\n\n\tdns_ai_close(vm->spf->ai);\n\tvm_assert(vm, (vm->spf->ai = dns_ai_open(host, serv, qtype, &hints, vm->spf->res, &error)), error);\n\n\tvm_discard(vm, 3);\n\n\tvm->pc++;\t\n} \/* op_addrinfo() *\/\n\n\nstatic void op_nextent(struct spf_vm *vm) {\n\tstruct addrinfo *ent = 0;\n\tint error;\n\n\tvm_extend(vm, 1);\n\tif ((error = dns_ai_nextent(&ent, vm->spf->ai)))\n\t\tvm_assert(vm, error == ENOENT, error);\n\tvm_push(vm, T_MEM, (intptr_t)ent);\n\n\tvm->pc++;\n} \/* op_nextent() *\/\n\n\nstatic void op_getenv(struct spf_vm *vm) {\n\tchar dst[512];\n\tint error;\n\n\tspf_getenv(dst, sizeof dst, vm_pop(vm, T_INT), &vm->spf->env);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_getenv() *\/\n\n\nstatic void op_setenv(struct spf_vm *vm) {\n\tchar *src;\n\tint error;\n\n\tvm_assert(vm, (src = (char *)vm_peek(vm, -2, T_REF|T_MEM)), EINVAL);\n\tspf_setenv(&vm->spf->env, vm_pop(vm, T_INT), src);\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_setenv() *\/\n\n\nstatic void op_expand(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tchar dst[512];\n\tint error;\n\n\tvm_assert(vm, spf_expand(dst, sizeof dst, ¯os, (void *)vm_peek(vm, -1, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tvm_pop(vm, T_ANY);\n\tvm_strdup(vm, dst);\n\n\tvm->pc++;\n} \/* op_expand() *\/\n\n\nstatic void op_isset(struct spf_vm *vm) {\n\tspf_macros_t macros = 0;\n\tint isset, error;\n\n\tvm_assert(vm, spf_expand(0, 0, ¯os, (void *)vm_peek(vm, -2, T_REF|T_MEM), &vm->spf->env, &error), error);\n\n\tisset = !!spf_isset(macros, vm_peek(vm, -1, T_INT));\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, isset);\n\n\tvm->pc++;\n} \/* op_isset() *\/\n\n\nstatic void op_check(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] packet\n\t *\/\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tNEG(&sub); \/* -DNS_T_TXT asks grep\/next to scan for v=spf1 *\/\n\tGREP(&sub);\n\tL0(&sub);\n\tNEXT(&sub);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ7(&sub);\n\tCOMP(&sub); \/* pushes code address, or 0 if failed. *\/\n\tDUP(&sub);\n\tJ1(&sub); \/* if not 0, jump to transfer code. *\/ \n\tNOT(&sub);\n\tJ0(&sub); \/* otherwise, continue looping *\/\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] code address\n\t *\/\n\tL1(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tTRUE(&sub);\n\tSWAP(&sub);\n\t \/*\n\t * [-4] reset address\n\t * [-3] return address\n\t * [-2] true\n\t * [-1] code address\n\t *\/\n\tGOTO(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tL7(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tPOP(&sub);\n\tNIL(&sub);\n\tI8(&sub, SPF_NONE);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_check() *\/\n\n\nstatic void op_comp(struct spf_vm *vm) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_exp exp = { 0 };\n\tstruct spf_redirect redir = { 0 };\n\tstruct vm_sub sub;\n\tconst char *txt;\n\tint type, error;\n\tunsigned end;\n\n\tend = vm->end;\n\n\tvm_assert(vm, (txt = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EINVAL);\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\t\/*\n\t * L5 is for matches\n\t * L6 is the explanation (i.e. exp= or default).\n\t * L7 is to return\n\t *\/\n\tsub_init(&sub, vm);\n\n\twhile ((type = spf_parse(&term, &parser, &error))) {\n#if 0\n\t\tSTR(&sub, (intptr_t)\"checking\");\n\t\tSTR(&sub, (intptr_t)spf_strterm(type));\n\t\tI8(&sub, ' ');\n\t\tCAT(&sub);\n\t\tPUTS(&sub);\n#endif\n\t\tswitch (type) {\n\t\tcase SPF_ALL:\n\t\t\tTRUE(&sub);\n\t\t\tbreak;\n\t\tcase SPF_INCLUDE:\n\t\t\tI8(&sub, 'd');\n\t\t\tGETENV(&sub);\n\n\t\t\tSTR(&sub, (intptr_t)&term.include.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tDUP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub);\n\n\t\t\tsub_emit(&sub, OP_CHECK);\n\t\t\tSWAP(&sub);\n\t\t\tPOP(&sub); \/* discard exp *\/\n\n\t\t\tSWAP(&sub);\n\t\t\tI8(&sub, 'd');\n\t\t\tSETENV(&sub); \/* replace our ${d} *\/\n\n\t\t\tI8(&sub, SPF_PASS);\n\t\t\tEQ(&sub);\n\n\t\t\tbreak;\n\t\tcase SPF_A:\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase SPF_MX:\n\t\t\tI8(&sub, term.mx.prefix6);\n\t\t\tI8(&sub, term.mx.prefix4);\n\t\t\tif (term.mx.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.mx.domain[0]);\n\t\t\t\tif (term.macros) {\n\t\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\t\tFCRD(&sub);\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, (type == SPF_A)? OP_A : OP_MX);\n\t\t\tbreak;\n\t\tcase SPF_PTR:\n\t\t\tFCRD(&sub);\n\t\t\tif (term.ptr.domain[0]) {\n\t\t\t\tSTR(&sub, (intptr_t)&term.ptr.domain[0]);\n\t\t\t\tif (term.macros)\n\t\t\t\t\tEXPAND(&sub);\n\t\t\t} else {\n\t\t\t\tSTR(&sub, (intptr_t)\"%{d}\");\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_PTR);\n\t\t\tbreak;\n\t\tcase SPF_IP4:\n\t\t\tI32(&sub, (intptr_t)term.ip4.addr.s_addr);\n\t\t\tI8(&sub, term.ip4.prefix);\n\t\t\tsub_emit(&sub, OP_IP4);\n\t\t\tbreak;\n\t\tcase SPF_IP6:\n\t\t\tTRAP(&sub);\n\t\t\tbreak;\n\t\tcase SPF_EXISTS:\n\t\t\tSTR(&sub, (intptr_t)&term.exists.domain[0]);\n\t\t\tif (term.macros) {\n\t\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\t\tFCRD(&sub);\n\t\t\t\tEXPAND(&sub);\n\t\t\t}\n\t\t\tsub_emit(&sub, OP_EXISTS);\n\t\t\tbreak;\n\t\tcase SPF_EXP:\n\t\t\texp = term.exp;\n\t\t\tcontinue;\n\t\tcase SPF_REDIRECT:\n\t\t\tredir = term.redirect;\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\tSPF_SAY(\"unknown term: %d\", type);\n\t\t\tcontinue;\n\t\t} \/* switch (type) *\/\n\n\t\t\/* [-1] matched *\/\n\t\tI8(&sub, term.result);\n\t\tSWAP(&sub);\n\t\tJ5(&sub);\n\t\tPOP(&sub);\n\t}\n\n\tif (error) {\n\t\tvm->end = end;\n\t\tend = 0;\n\t\tgoto done;\n\t}\n\n\tif (redir.type) {\n\t\tSTR(&sub, (intptr_t)&redir.domain[0]);\n\t\tif (redir.macros) {\n\t\t\tif (spf_isset(redir.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_CHECK);\n\t\tTRUE(&sub);\n\t\tJ7(&sub);\n\t}\n\n\t\/*\n\t * No matches.\n\t *\/\n#if 0\n\tSTR(&sub, (intptr_t)\"no match\");\n\tPUTS(&sub);\n#endif\n\tI8(&sub, SPF_NEUTRAL);\n\tTRUE(&sub);\n\tJ6(&sub);\n\n\tL5(&sub);\n#if 0\n\tDUP(&sub);\n\tSTR(&sub, (intptr_t)\"match : result=\");\n\tSWAP(&sub);\n\tI8(&sub, ' ');\n\tCAT(&sub);\n\tPUTS(&sub);\n#endif\n\n\t\/*\n\t * exp\n\t *\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] result\n\t *\/\n\tL6(&sub);\n\tNIL(&sub); \/* queue NIL exp *\/\n\tSWAP(&sub);\n\tDUP(&sub);\n\tI8(&sub, SPF_FAIL);\n\tEQ(&sub);\n\tNOT(&sub);\n\tJ7(&sub); \/* not a fail, so jump to end with our NIL exp *\/\n\tSWAP(&sub);\n\tPOP(&sub); \/* otherwise discard the NIL exp *\/\n\n\tif (exp.type) {\n\t\tSTR(&sub, (intptr_t)&term.exp.domain[0]);\n\t\tif (term.macros) {\n\t\t\tif (spf_isset(term.macros, 'p'))\n\t\t\t\tFCRD(&sub);\n\t\t\tEXPAND(&sub);\n\t\t}\n\t\tsub_emit(&sub, OP_EXP);\n\t\tSWAP(&sub);\n\t} else {\n\t\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\t\tEXPAND(&sub);\n\t\tSWAP(&sub);\n\t}\n\n\tL7(&sub);\n\tTWO(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\ndone:\n\t\/*\n\t * We should always be called in conjunction with OP_CHECK. OP_COMP\n\t * returns the address of the new code, which OP_CHECK will jump\n\t * into (with the reset and return addresses properly set). If\n\t * compiling fails, 0 is returned to OP_CHECK.\n\t *\/\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, end);\n\n\tvm->pc++;\n} \/* op_comp() *\/\n\n\nstatic void op_ip4(struct spf_vm *vm) {\n\tstruct in_addr a, b;\n\tunsigned prefix;\n\tint match;\n\n\tprefix = vm_pop(vm, T_INT);\n\ta.s_addr = vm_pop(vm, T_INT);\n\n\tif (!strcmp(vm->spf->env.v, \"in-addr\")) {\n\t\tspf_pto4(&b, vm->spf->env.i);\n\t\tmatch = (0 == spf_4cmp(&a, &b, prefix));\n\t} else\n\t\tmatch = 0;\n\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ip4() *\/\n\n\nstatic void op_exists(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-3] reset address\n\t * [-2] return address\n\t * [-1] domain\n\t *\/\n\tI8(&sub, DNS_T_A);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tNIL(&sub);\n\tTWO(&sub);\n\tI8(&sub, DNS_T_A);\n\tGREP(&sub);\n\tNEXT(&sub);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] packet\n\t * [-2] iterator\n\t * [-1] rdata\n\t *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exists() *\/\n\n\nstatic void op_a_mxv(struct spf_vm *vm) {\n\tint prefix6 = vm_peek(vm, -3, T_INT);\n\tint prefix4 = vm_peek(vm, -2, T_INT);\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, prefix, error, match = 0;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\tprefix = prefix6;\n\t} else {\n\t\taf = AF_INET;\n\t\tprefix = prefix4;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tmatch = (0 == spf_addrcmp(af, &a, &b, prefix));\ndone:\n\tvm_discard(vm, 3);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_a_mxv() *\/\n\n\nstatic void op_a_mx(struct spf_vm *vm, enum dns_type type) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * [-5] reset address\n\t * [-4] return address\n\t * [-3] prefix6\n\t * [-2] prefix4\n\t * [-1] domain\n\t *\/\n\tI8(&sub, 0);\n\tI8(&sub, type);\n\tsub_emit(&sub, OP_ADDRINFO);\n\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\t\/* push prefix6 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* push prefix4 *\/\n\tTHREE(&sub);\n\tNEG(&sub);\n\tLOAD(&sub);\n\tSWAP(&sub);\n\t\/* call MXv with [-3] prefix6 [-2] prefix4 [-1] ent *\/\n#if 0\n\tDUP(&sub);\n\tsub_emit(&sub, OP_PUTA);\n#endif\n\tsub_emit(&sub, OP_A_MXv);\n\tNOT(&sub);\n\tJ0(&sub);\n\tTRUE(&sub);\n\tTRUE(&sub);\n\tJ1(&sub);\n\n\tL1(&sub);\n\tNOT(&sub); \/* to... *\/\n\tNOT(&sub); \/* ...boolean *\/\n\tSWAP(&sub);\n\tPOP(&sub);\n\tSWAP(&sub);\n\tPOP(&sub);\n\tONE(&sub);\n\tEXIT(&sub);\n\n\tsub_link(&sub);\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\tvm_move(vm, -5);\n\n\tvm->pc = end;\n} \/* op_a_mx() *\/\n\n\nstatic void op_a(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_A);\n} \/* op_a() *\/\n\n\nstatic void op_mx(struct spf_vm *vm) {\n\top_a_mx(vm, DNS_T_MX);\n} \/* op_mx() *\/\n\n\nstatic void op_ptr(struct spf_vm *vm) {\n\tconst char *arg;\n\tstruct dns_rr rr;\n\tchar dn[DNS_D_MAXNAME + 1], cn[DNS_D_MAXNAME + 1];\n\tint error, match = 0;\n\n\tvm_assert(vm, vm->spf->fcrd.done, EFAULT);\n\tvm_assert(vm, (arg = (char *)vm_peek(vm, -1, T_REF|T_MEM)), EFAULT);\n\n\tspf_strlcpy(dn, arg, sizeof dn);\n\tspf_fixdn(dn, dn, sizeof dn, SPF_DN_ANCHOR);\n\n\tdns_rr_foreach(&rr, &vm->spf->fcrd.ptr, .section = DNS_S_ANSWER) {\n\t\tvm_assert(vm, dns_d_expand(cn, sizeof cn, rr.dn.p, &vm->spf->fcrd.ptr, &error), error);\n\n\t\tdo {\n\t\t\tif ((match = !strcasecmp(dn, cn)))\n\t\t\t\tgoto done;\n\t\t} while (spf_fixdn(cn, cn, sizeof cn, SPF_DN_SUPER));\n\t}\n\ndone:\n\tvm_discard(vm, 1);\n\tvm_push(vm, T_INT, match);\n\n\tvm->pc++;\n} \/* op_ptr() *\/\n\n\nstatic void op_fcrdx(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tunion { struct in_addr a4; struct in6_addr a6; } a, b;\n\tint af, rtype, error;\n\n\tif (0 == strcmp(vm->spf->env.v, \"ipv6\")) {\n\t\taf = AF_INET6;\n\t\trtype = DNS_T_AAAA;\n\t} else {\n\t\taf = AF_INET;\n\t\trtype = DNS_T_A;\n\t}\n\n\tif (ent->ai_addr->sa_family != af)\n\t\tgoto done;\n\n\tspf_pton(&a, af, vm->spf->env.c);\n\n\tif (af == AF_INET6)\n\t\tb.a6 = ((struct sockaddr_in6 *)ent->ai_addr)->sin6_addr;\n\telse\n\t\tb.a4 = ((struct sockaddr_in *)ent->ai_addr)->sin_addr;\n\n\tif (0 != spf_addrcmp(af, &a, &b, 128))\n\t\tgoto done;\n\t\n\tvm_assert(vm, !(error = dns_p_push(&vm->spf->fcrd.ptr, DNS_S_AN, ent->ai_canonname, strlen(ent->ai_canonname), rtype, DNS_C_IN, 0, &b)), error);\n\n\t\/*\n\t * FIXME: We need to give preference to a verified domain which is\n\t * the same as %{d}, or a sub-domain of %{d}. HOWEVER, include: and\n\t * require= recursion temporarily replace %{d}, so we need to copy\n\t * the _original_ %{d} somewhere for comparing.\n\t *\/\n\tif (!*vm->spf->env.p || !strcmp(vm->spf->env.p, \"unknown\"))\n\t\tspf_strlcpy(vm->spf->env.p, ent->ai_canonname, sizeof vm->spf->env.p);\ndone:\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_fcrdx() *\/\n\n\nstatic void op_fcrd(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tif (vm->spf->fcrd.done)\n\t\t{ vm->pc++; return; }\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\tREF(&sub, (intptr_t)\"%{ir}.%{v}.arpa.\");\n\tEXPAND(&sub);\n\tI8(&sub, 0);\n\tI8(&sub, DNS_T_PTR);\n\tsub_emit(&sub, OP_ADDRINFO);\n\tL0(&sub);\n\tsub_emit(&sub, OP_NEXTENT);\n\tDUP(&sub);\n\tNOT(&sub);\n\tJ1(&sub);\n\tFCRDx(&sub);\n\tTRUE(&sub);\n\tJ0(&sub);\n\tL1(&sub);\n\tPOP(&sub);\n\tZERO(&sub);\n\tEXIT(&sub); \/* [-1] return address [-2] reset address *\/\n\n\tsub_link(&sub);\n\n\tvm->spf->fcrd.done = 1;\n\n\tvm_push(vm, T_INT, end);\n\tvm_push(vm, T_INT, ret);\n\n\tvm->pc = end;\n} \/* op_fcrd() *\/\n\n\nstatic void op_exp(struct spf_vm *vm) {\n\tstruct vm_sub sub;\n\tunsigned end, ret;\n\n\tend = vm->end;\n\tret = vm->pc + 1;\n\n\tsub_init(&sub, vm);\n\n\t\/*\n\t * Query for TXT record\n\t * \t[-1] target\n\t *\/\n\tL0(&sub);\n\tI8(&sub, DNS_T_TXT);\n\tSUBMIT(&sub);\n\tFETCH(&sub);\n\tREF(&sub, (intptr_t)\"\");\n\tI8(&sub, DNS_S_AN);\n\tI8(&sub, DNS_T_TXT);\n\tGREP(&sub);\n\tNEXT(&sub); \/\/ pops 0, pushes rdata (rdata could be NULL)\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard grep iterator\n\tSWAP(&sub);\n\tPOP(&sub); \/\/ discard DNS packet\n\n\t\/*\n\t * TXT record present?\n\t * \t[-1] exp\n\t *\/\n\tDUP(&sub); \/\/ take a copy\n\tJ1(&sub); \/\/ jump to FCRD check if present\n\tPOP(&sub); \/\/ otherwise, pop and push default string\n\tREF(&sub, (intptr_t)SPF_DEFEXP);\n\n\t\/*\n\t * Do we need to do FCRD match?\n\t * \t[-1] exp\n\t *\/\n\tL1(&sub);\n\tDUP(&sub); \/\/ take a copy\n\tI8(&sub, 'p'); \/\/ %{p} macro triggers FCRD\n\tISSET(&sub); \/\/ check for macro (pops 2, pushs boolean)\n\tNOT(&sub);\n\tJ2(&sub); \/\/ if not set, jump to expansion\n\tFCRD(&sub); \/\/ otherwise do FCRD\n\n\t\/*\n\t * Expand rdata\n\t * \t[-1] exp\n\t *\/\n\tL2(&sub);\n\tEXPAND(&sub); \/\/ pops 1, pushes expansion\n\n\t\/*\n\t * Epilog.\n\t * \t[-1] exp\n\t *\/\n\tONE(&sub); \/\/ returning one result\n\tEXIT(&sub); \/\/ expects [-1] result [-2] return address [-3] reset address\n\n\tsub_link(&sub);\n\n\t\/*\n\t * Call above routine.\n\t * \t[-3] code reset address\n\t * \t[-2] return address\n\t * \t[-1] target\n\t *\/\n\tvm_push(vm, T_INT, end);\n\tvm_swap(vm);\n\tvm_push(vm, T_INT, ret);\n\tvm_swap(vm);\n\n\tvm->pc = end;\n} \/* op_exp() *\/\n\n\nstatic void op_sleep(struct spf_vm *vm) {\n\tsleep(vm_pop(vm, T_INT));\n\tvm->pc++;\n} \/* op_sleep() *\/\n\n\nstatic void op_gets(struct spf_vm *vm) {\n\tchar sbuf[1024];\n\n\tif (fgets(sbuf, sizeof sbuf, stdin)) {\n\t\tspf_rtrim(sbuf, \"\\r\\n\");\n\t\tvm_strdup(vm, sbuf);\n\t} else if (feof(stdin)) {\n\t\tvm_push(vm, T_REF, 0);\n\t} else\n\t\tvm_throw(vm, errno);\n\n\tvm->pc++;\n} \/* op_gets() *\/\n\n\nstatic void op_cat(struct spf_vm *vm) {\n\tstruct spf_sbuf sbuf = SBUF_INIT(&sbuf);\n\n\t\/* Print [-2] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -2))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -2, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -2, T_ANY));\n\n\t\/* Print [-1] as string *\/\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tsbuf_puts(&sbuf, (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\telse\n\t\tsbuf_puti(&sbuf, vm_peek(vm, -1, T_ANY));\n\n\tvm_assert(vm, !sbuf.overflow, ENOMEM);\n\tvm_discard(vm, 2);\n\tvm_strdup(vm, sbuf.str);\n\n\tvm->pc++;\n} \/* op_cat() *\/\n\n\nstatic void op_cmp(struct spf_vm *vm) {\n\tchar *a, *b;\n\tint cmp;\n\ta = (char *)vm_peek(vm, -2, T_REF|T_MEM);\n\tb = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tcmp = strcmp(a, b);\n\tvm_discard(vm, 2);\n\tvm_push(vm, T_INT, cmp);\n\tvm->pc++;\n} \/* op_cmp() *\/\n\n\nstatic void op_lc(struct spf_vm *vm) {\n\tchar *s;\n\ts = (char *)vm_peek(vm, -1, T_REF|T_MEM);\n\tspf_tolower((char *)vm_strdup(vm, s));\n\tvm_swap(vm);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm->pc++;\n} \/* op_lc() *\/\n\n\nstatic void op_puti(struct spf_vm *vm) {\n\tif ((T_REF|T_MEM) & vm_typeof(vm, -1))\n\t\tprintf(\"%p\\n\", (void *)vm_pop(vm, (T_REF|T_MEM)));\n\telse\n\t\tprintf(\"%ld\\n\", (long)vm_pop(vm, T_ANY));\n\tvm->pc++;\n} \/* op_puti() *\/\n\n\nstatic void op_puts(struct spf_vm *vm) {\n\tprintf(\"%s\\n\", (char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_ANY);\n\tvm->pc++;\n} \/* op_puts() *\/\n\n\nstatic void op_putp(struct spf_vm *vm) {\n\tstruct dns_packet *pkt = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tenum dns_section section;\n\tstruct dns_rr rr;\n\tint error;\n\tchar pretty[1024];\n\tsize_t len;\n\n\tsection\t= 0;\n\n\tdns_rr_foreach(&rr, pkt) {\n\t\tif (section != rr.section)\n\t\t\tprintf(\"\\n;; [%s:%d]\\n\", dns_strsection(rr.section), dns_p_count(pkt, rr.section));\n\n\t\tif ((len = dns_rr_print(pretty, sizeof pretty, &rr, pkt, &error)))\n\t\t\tprintf(\"%s\\n\", pretty);\n\n\t\tsection\t= rr.section;\n\t}\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_putp() *\/\n\n\nstatic void op_puta(struct spf_vm *vm) {\n\tstruct addrinfo *ent = (void *)vm_peek(vm, -1, T_REF|T_MEM);\n\tchar pretty[1024];\n\n\tdns_ai_print(pretty, sizeof pretty, ent, vm->spf->ai);\n\tprintf(\"%s\", pretty);\n\n\tvm_discard(vm, 1);\n\n\tvm->pc++;\n} \/* op_puta() *\/\n\n\nstatic void op_rstr(struct spf_vm *vm) {\n\tvm_strdup(vm, spf_strresult(vm_pop(vm, T_INT)));\n\n\tvm->pc++;\n} \/* op_rstr() *\/\n\n\nstatic void op_atoi(struct spf_vm *vm) {\n\tunsigned long i;\n\n\ti = spf_atoi((char *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_push(vm, T_INT, i);\n\n\tvm->pc++;\n} \/* op_atoi() *\/\n\n\nstatic void op_4top(struct spf_vm *vm) {\n\tchar sbuf[INET_ADDRSTRLEN + 1];\n\n\tspf_4top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_4top() *\/\n\n\nstatic void op_pto4(struct spf_vm *vm) {\n\tstruct in_addr in;\n\n\tspf_pto4(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto4() *\/\n\n\nstatic void op_6top(struct spf_vm *vm) {\n\tchar sbuf[INET6_ADDRSTRLEN + 1];\n\n\tspf_6top(sbuf, sizeof sbuf, (void *)vm_peek(vm, -1, T_REF|T_MEM), SPF_6TOP_MIXED);\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_strdup(vm, sbuf);\n\n\tvm->pc++;\n} \/* op_6top() *\/\n\n\nstatic void op_pto6(struct spf_vm *vm) {\n\tstruct in6_addr in;\n\n\tspf_pto6(&in, (void *)vm_peek(vm, -1, T_REF|T_MEM));\n\tvm_pop(vm, T_REF|T_MEM);\n\tvm_memdup(vm, &in, sizeof in);\n\n\tvm->pc++;\n} \/* op_pto6() *\/\n\n\nstatic const struct {\n\tconst char *name;\n\tvoid (*exec)(struct spf_vm *);\n} vm_op[] = {\n\t[OP_HALT] = { \"halt\", 0 },\n\t[OP_TRAP] = { \"trap\", &op_trap },\n\t[OP_NOOP] = { \"noop\", &op_noop },\n\t[OP_PC] = { \"pc\", &op_pc, },\n\t[OP_CALL] = { \"call\", &op_call, },\n\t[OP_RET] = { \"ret\", &op_ret, },\n\t[OP_EXIT] = { \"exit\", &op_exit, },\n\n\t[OP_TRUE] = { \"true\", &op_lit, },\n\t[OP_FALSE] = { \"false\", &op_lit, },\n\t[OP_ZERO] = { \"zero\", &op_lit, },\n\t[OP_ONE] = { \"one\", &op_lit, },\n\t[OP_TWO] = { \"two\", &op_lit, },\n\t[OP_THREE] = { \"three\", &op_lit, },\n\n\t[OP_I8] = { \"i8\", &op_lit, },\n\t[OP_I16] = { \"i16\", &op_lit, },\n\t[OP_I32] = { \"i32\", &op_lit, },\n\t[OP_NIL] = { \"nil\", &op_lit, },\n\t[OP_REF] = { \"ref\", &op_lit, },\n\t[OP_MEM] = { \"mem\", &op_lit, },\n\t[OP_STR] = { \"str\", &op_str, },\n\t[OP_IN4] = { \"in4\", &op_in4, },\n\t[OP_IN6] = { \"in6\", &op_in6, },\n\n\t[OP_DEC] = { \"dec\", &op_dec, },\n\t[OP_INC] = { \"inc\", &op_inc, },\n\t[OP_NEG] = { \"neg\", &op_neg, },\n\t[OP_ADD] = { \"add\", &op_add, },\n\t[OP_NOT] = { \"not\", &op_not, },\n\n\t[OP_EQ] = { \"eq\", &op_eq, },\n\t[OP_LT] = { \"lt\", &op_lt, },\n\n\t[OP_JMP] = { \"jmp\", &op_jmp, },\n\t[OP_GOTO] = { \"goto\", &op_goto, },\n\n\t[OP_POP] = { \"pop\", &op_pop, },\n\t[OP_DUP] = { \"dup\", &op_dup, },\n\t[OP_LOAD] = { \"load\", &op_load, },\n\t[OP_STORE] = { \"store\", &op_store, },\n\t[OP_MOVE] = { \"move\", &op_move, },\n\t[OP_SWAP] = { \"swap\", &op_swap, },\n\n\t[OP_GETENV] = { \"getenv\", &op_getenv, },\n\t[OP_SETENV] = { \"setenv\", &op_setenv, },\n\n\t[OP_EXPAND] = { \"expand\", &op_expand, },\n\t[OP_ISSET] = { \"isset\", &op_isset, },\n\n\t[OP_SUBMIT] = { \"submit\", &op_submit, },\n\t[OP_FETCH] = { \"fetch\", &op_fetch, },\n\t[OP_QNAME] = { \"qname\", &op_qname, },\n\t[OP_GREP] = { \"grep\", &op_grep, },\n\t[OP_NEXT] = { \"next\", &op_next, },\n\n\t[OP_ADDRINFO] = { \"addrinfo\", &op_addrinfo, },\n\t[OP_NEXTENT] = { \"nextent\", &op_nextent, },\n\n\t[OP_IP4] = { \"ip4\", &op_ip4, },\n\t[OP_EXISTS] = { \"exists\", &op_exists, },\n\t[OP_A] = { \"a\", &op_a },\n\t[OP_MX] = { \"mx\", &op_mx },\n\t[OP_A_MXv] = { \"mxv\", &op_a_mxv },\n\t[OP_PTR] = { \"ptr\", &op_ptr },\n\n\t[OP_FCRD] = { \"fcrd\", &op_fcrd, },\n\t[OP_FCRDx] = { \"fcrdx\", &op_fcrdx, },\n\n\t[OP_CHECK] = { \"check\", &op_check, },\n\t[OP_COMP] = { \"comp\", &op_comp, },\n\n\t[OP_SLEEP] = { \"sleep\", &op_sleep },\n\n\t[OP_CAT] = { \"cat\", &op_cat, },\n\t[OP_CMP] = { \"cmp\", &op_cmp, },\n\t[OP_LC] = { \"lc\", &op_lc, },\n\t[OP_GETS] = { \"gets\", &op_gets, },\n\t[OP_PUTI] = { \"puti\", &op_puti, },\n\t[OP_PUTS] = { \"puts\", &op_puts, },\n\t[OP_PUTP] = { \"putp\", &op_putp, },\n\t[OP_PUTA] = { \"puta\", &op_puta, },\n\t[OP_RSTR] = { \"rstr\", &op_rstr, },\n\t[OP_ATOI] = { \"atoi\", &op_atoi, },\n\t[OP_4TOP] = { \"4top\", &op_4top, },\n\t[OP_PTO4] = { \"pto4\", &op_pto4, },\n\t[OP_6TOP] = { \"6top\", &op_6top, },\n\t[OP_PTO6] = { \"pto6\", &op_pto6, },\n\n\t[OP_EXP] = { \"exp\", &op_exp, },\n}; \/* vm_op[] *\/\n\nstatic const char *vm_strcode(int code) {\n\treturn vm_op[code].name;\n} \/* vm_strcode() *\/\n\nstatic int vm_icode(const char *name) {\n\tint code;\n\n\tfor (code = 0; code < (int)spf_lengthof(vm_op); code++) {\n\t\tif (vm_op[code].name && !strcasecmp(name, vm_op[code].name))\n\t\t\treturn code;\n\t}\n\n\treturn -1;\n} \/* vm_icode() *\/\n\n\nstatic int vm_exec(struct spf_vm *vm) {\n\tenum vm_opcode code;\n\tint error;\n\n\tif ((error = _setjmp(vm->trap))) {\n\t\tSPF_SAY(\"trap: %s\", spf_strerror(error));\n\t\treturn error;\n\t}\n\n\twhile ((code = vm_opcode(vm))) {\n\t\tif (spf_unlikely(SPF_DEBUG >= 2)) {\n\t\t\tSPF_SAY(\"code: %s\", vm_op[code].name);\n\t\t}\n\t\tvm_op[code].exec(vm);\n\t}\n\n\treturn 0;\n} \/* vm_exec() *\/\n\n\n\/*\n * R E S O L V E R R O U T I N E S\n *\n * NOTE: `struct spf_resolver' is forward-defined at the beginning of the VM\n * section.\n *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\n\nconst struct spf_limits spf_safelimits = { .querymax = 10, };\n\nstruct spf_resolver *spf_open(const struct spf_env *env, const struct spf_limits *limits, int *error_) {\n\tstruct spf_resolver *spf = 0;\n\tint error;\n\n\tif (!(spf = malloc(sizeof *spf)))\n\t\tgoto syerr;\n\n\tmemset(spf, 0, sizeof *spf);\n\n\tspf->env = *env;\n\n\tvm_init(&spf->vm, spf);\n\n\tif (!(spf->res = dns_res_stub(NULL, &error)))\t\n\t\tgoto error;\n\n\tdns_p_init(&spf->fcrd.ptr, sizeof spf->fcrd.buf);\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tgoto error;\n\n\tvm_emit(&spf->vm, OP_STR, (intptr_t)\"%{d}\");\n\tvm_emit(&spf->vm, OP_EXPAND);\n\tvm_emit(&spf->vm, OP_CHECK);\n\tvm_emit(&spf->vm, OP_HALT);\n\n\treturn spf;\nsyerr:\n\terror = errno;\nerror:\n\t*error_ = error;\n\n\tfree(spf);\n\n\treturn 0;\n} \/* spf_open() *\/\n\n\nvoid spf_close(struct spf_resolver *spf) {\n\tstruct spf_rr *rr;\n\n\tif (!spf)\n\t\treturn;\n\n\tdns_res_close(spf->res);\n\tdns_ai_close(spf->ai);\n\n\tvm_discard(&spf->vm, spf->vm.sp);\n\n\tfree(spf);\n} \/* spf_close() *\/\n\n\nint spf_check(struct spf_resolver *spf) {\n\tint error;\n\n\tif ((error = vm_exec(&spf->vm)))\n\t\treturn error;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\treturn error;\n\n\tspf->result = vm_peek(&spf->vm, -1, T_INT);\n\tspf->exp = (char *)vm_peek(&spf->vm, -2, T_REF|T_MEM);\n\n\treturn 0;\n} \/* spf_check() *\/\n\n\nenum spf_result spf_result(struct spf_resolver *spf) {\n\treturn spf->result;\n} \/* spf_result() *\/\n\n\nconst char *spf_exp(struct spf_resolver *spf) {\n\treturn spf->exp;\n} \/* spf_exp() *\/\n\n\nint spf_elapsed(struct spf_resolver *spf) {\n\treturn dns_res_elapsed(spf->res);\n} \/* spf_elapsed() *\/\n\n\nvoid spf_clear(struct spf_resolver *spf) {\n\treturn dns_res_clear(spf->res);\n} \/* spf_clear() *\/\n\n\nint spf_events(struct spf_resolver *spf) {\n\treturn dns_res_events(spf->res);\n} \/* spf_events() *\/\n\n\nint spf_pollfd(struct spf_resolver *spf) {\n\treturn dns_res_pollfd(spf->res);\n} \/* spf_pollfd() *\/\n\n\nint spf_poll(struct spf_resolver *spf, int timeout) {\n\treturn dns_res_poll(spf->res, timeout);\n} \/* spf_poll() *\/\n\n\n\n#if SPF_MAIN\n\n#include \n#include \n\n#include \n\n#include \t\/* isspace(3) *\/\n\n#include \t\/* getopt(3) *\/\n\n\n#define panic_(fn, ln, fmt, ...) \\\n\tdo { fprintf(stderr, fmt \"%.1s\", (fn), (ln), __VA_ARGS__); _Exit(EXIT_FAILURE); } while (0)\n\n#define panic(...) panic_(__func__, __LINE__, \"spf: (%s:%d) \" __VA_ARGS__, \"\\n\")\n\n\nstatic void frepc(int ch, int count, FILE *fp)\n\t{ while (count--) fputc(ch, fp); }\n\nstatic int vm(const struct spf_env *env, const char *file) {\n#define VM_C(name) { #name, name }\n\tstatic const struct { const char *name; int value; } ctable[] = {\n\t\tVM_C(AF_INET), VM_C(AF_INET6),\n\t\tVM_C(SPF_NONE), VM_C(SPF_NEUTRAL), VM_C(SPF_PASS),\n\t\tVM_C(SPF_FAIL), VM_C(SPF_SOFTFAIL), VM_C(SPF_TEMPERROR),\n\t\tVM_C(SPF_PERMERROR),\n\t\tVM_C(DNS_S_QD), VM_C(DNS_S_AN), VM_C(DNS_S_NS),\n\t\tVM_C(DNS_S_AR), VM_C(DNS_S_ALL),\n\t\tVM_C(DNS_C_IN), VM_C(DNS_C_ANY),\n\t\tVM_C(DNS_T_A), VM_C(DNS_T_NS), VM_C(DNS_T_CNAME),\n\t\tVM_C(DNS_T_SOA), VM_C(DNS_T_PTR), VM_C(DNS_T_MX),\n\t\tVM_C(DNS_T_TXT), VM_C(DNS_T_AAAA), VM_C(DNS_T_SRV),\n\t\tVM_C(DNS_T_SPF), VM_C(DNS_T_ALL),\n\t};\n\tFILE *fp = stdin;\n\tstruct spf_resolver *spf;\n\tstruct spf_vm *vm;\n\tchar line[256], *str, *eos;\n\tlong i;\n\tstruct vm_sub sub;\n\tint code, error;\n\n\tif (file && strcmp(file, \"-\"))\n\t\tassert((fp = fopen(file, \"r\")));\n\n\tassert((spf = spf_open(env, 0, &error)));\n\tvm = &spf->vm;\n\tvm->end = 0;\n\n\tif ((error = _setjmp(spf->vm.trap)))\n\t\tpanic(\"vm_exec: %s\", spf_strerror(error));\n\n\tsub_init(&sub, vm);\n\n\twhile (fgets(line, sizeof line, fp)) {\n\t\tspf_rtrim(line, \"\\r\\n\");\n\n\t\tswitch (line[0]) {\n\t\tcase '#': case ';':\n\t\t\tbreak;\n\t\tcase '$':\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tfor (i = 0; i < spf_lengthof(ctable); i++) {\n\t\t\t\tif (!strcasecmp(&line[1], ctable[i].name))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i >= spf_lengthof(ctable))\n\t\t\t\tpanic(\"%s: unknown constant\", line);\n\n\t\t\ti = ctable[i].value;\n\n\t\t\tgoto number;\n\t\tcase '-': case '+':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\ti = labs(strtol(line, &eos, 0));\n\n\t\t\tif (isalpha((unsigned char)*eos))\n\t\t\t\tgoto search;\nnumber:\n\t\t\tif (i < 4)\n\t\t\t\tsub_emit(&sub, OP_ZERO + i);\n\t\t\telse if (i < (1U<<8))\n\t\t\t\tsub_emit(&sub, OP_I8, i);\n\t\t\telse if (i < (1U<<16))\n\t\t\t\tsub_emit(&sub, OP_I16, i);\n\t\t\telse\n\t\t\t\tsub_emit(&sub, OP_I32, i);\n\n\t\t\tif (line[0] == '-')\n\t\t\t\tsub_emit(&sub, OP_NEG);\n\n\t\t\tbreak;\n\t\tcase '\"':\n\t\t\tsub_emit(&sub, OP_STR, (intptr_t)&line[1]);\n\n\t\t\tbreak;\n\t\tcase '\\'':\n\t\t\tsub_emit(&sub, OP_I8, (intptr_t)line[1]);\n\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_label(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tcase 'J':\n\t\t\tif (!isdigit((unsigned char)line[1]))\n\t\t\t\tbreak;\n\n\t\t\tsub_jump(&sub, line[1] - '0');\n\n\t\t\tbreak;\n\t\tdefault:\nsearch:\n\t\t\tspf_rtrim(line, \" \\t\");\n\n\t\t\tif (*line) {\n\t\t\t\tif (-1 != (code = vm_icode(line))) {\n\t\t\t\t\tsub_emit(&sub, code);\n\t\t\t\t} else\n\t\t\t\t\tSPF_SAY(\"%s: unknown opcode\", line);\n\t\t\t}\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\tsub_emit(&sub, OP_HALT);\n\n\tsub_link(&sub);\n\n\twhile ((error = vm_exec(vm))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = dns_res_poll(spf->res, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"exec: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* vm() *\/\n\n\nstatic int check(int argc, char *argv[], const struct spf_env *env) {\n\tstruct spf_resolver *spf;\n\tint error;\n\n\tassert((spf = spf_open(env, 0, &error)));\n\n\twhile ((error = spf_check(spf))) {\n\t\tswitch (error) {\n\t\tcase EAGAIN:\n\t\t\tif ((error = spf_poll(spf, 5)))\n\t\t\t\tpanic(\"poll: %s\", spf_strerror(error));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"check: %s\", spf_strerror(error));\n\t\t}\n\t}\n\n\tprintf(\"result: %s\\n\", spf_strresult(spf_result(spf)));\n\tprintf(\"exp: %s\\n\", (spf_exp(spf))? spf_exp(spf) : \"[no exp]\");\n\n\tspf_close(spf);\n\n\treturn 0;\n} \/* check() *\/\n\n\nstatic int parse(const char *txt) {\n\tstruct spf_parser parser;\n\tunion spf_term term;\n\tstruct spf_sbuf sbuf;\n\tint error;\n\n\tspf_parser_init(&parser, txt, strlen(txt));\n\n\twhile (spf_parse(&term, &parser, &error)) {\n\t\tterm_comp(sbuf_init(&sbuf), &term);\n\t\tputs(sbuf.str);\n\t}\n\n\tif (error) {\n\t\tfprintf(stderr, \"error near `%s'\\n\", parser.error.near);\n\t\tfrepc('.', 11 + parser.error.lp, stderr);\n\t\tfputc('^', stderr);\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn error;\n} \/* parse() *\/\n\n\nstatic int expand(const char *src, const struct spf_env *env) {\n\tchar dst[512];\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(dst, sizeof dst, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfprintf(stdout, \"[%s]\\n\", dst);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tfputs(\"macros:\", stderr);\n\n\t\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\t\tif (spf_isset(macros, M))\n\t\t\t\t{ fputc(' ', stderr); fputc(M, stderr); }\n\t\t}\n\n\t\tfputc('\\n', stderr);\n\t}\n\n\treturn 0;\n} \/* expand() *\/\n\n\nstatic int macros(const char *src, const struct spf_env *env) {\n\tspf_macros_t macros = 0;\n\tint error;\n\n\tif (!(spf_expand(0, 0, ¯os, src, env, &error)) && error)\n\t\tpanic(\"%s: %s\", src, spf_strerror(error));\t\n\n\tfor (unsigned M = 'A'; M <= 'Z'; M++) {\n\t\tif (spf_isset(macros, M)) {\n\t\t\tfputc(M, stdout);\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\t}\n\n\treturn 0;\n} \/* macros() *\/\n\n\nstatic void ip_flags(int *flags, _Bool *libc, int argc, char *argv[]) {\n\tfor (int i = 0; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"nybble\"))\n\t\t\t*flags |= SPF_6TOP_NYBBLE;\n\t\telse if (!strcmp(argv[i], \"compat\"))\n\t\t\t*flags |= SPF_6TOP_COMPAT;\n\t\telse if (!strcmp(argv[i], \"mapped\"))\n\t\t\t*flags |= SPF_6TOP_MAPPED;\n\t\telse if (!strcmp(argv[i], \"mixed\"))\n\t\t\t*flags |= SPF_6TOP_MIXED;\n\t\telse if (!strcmp(argv[i], \"libc\"))\n\t\t\t*libc = 1;\n\t}\n\n\tif (*libc && *flags)\n\t\tSPF_SAY(\"libc and nybble\/compat\/mapped are mutually exclusive\");\n\telse if ((*flags & SPF_6TOP_NYBBLE) && (*flags & SPF_6TOP_MIXED))\n\t\tSPF_SAY(\"nybble and compat\/mapped are mutually exclusive\");\n} \/* ip_flags() *\/\n\n\n#include \n\nint ip6(int argc, char *argv[]) {\n\tstruct in6_addr ip;\n\tchar str[64];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET6, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v6 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET6, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto6(&ip, argv[0]);\n\t\tspf_6top(str, sizeof str, &ip, flags);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip6() *\/\n\n\nint ip4(int argc, char *argv[]) {\n\tstruct in_addr ip;\n\tchar str[16];\n\tint ret, flags = 0;\n\t_Bool libc = 0;\n\n\tip_flags(&flags, &libc, argc - 1, &argv[1]);\n\n\tif (flags)\n\t\tSPF_SAY(\"nybble\/compat\/mapped invalid flags for v4 address\");\n\n\tmemset(&ip, 0xff, sizeof ip);\n\n\tif (libc) {\n\t\tif (1 != (ret = inet_pton(AF_INET, argv[0], &ip)))\n\t\t\tpanic(\"%s: %s\", argv[0], (ret == 0)? \"not v4 address\" : spf_strerror(errno));\n\n\t\tinet_ntop(AF_INET, &ip, str, sizeof str);\n\t} else {\n\t\tspf_pto4(&ip, argv[0]);\n\t\tspf_4top(str, sizeof str, &ip);\n\t}\n\n\tputs(str);\n\n\treturn 0;\n} \/* ip4() *\/\n\n\nint fixdn(int argc, char *argv[]) {\n\tchar dst[(SPF_MAXDN * 2) + 1];\n\tsize_t lim = (SPF_MAXDN + 1), len;\n\tint flags = 0;\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (!strcmp(argv[i], \"super\")) {\n\t\t\tflags |= SPF_DN_SUPER;\n\t\t} else if (!strcmp(argv[i], \"trunc\")) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t} else if (!strncmp(argv[i], \"trunc=\", 6)) {\n\t\t\tflags |= SPF_DN_TRUNC;\n\t\t\tlim = spf_atoi(&argv[i][6]);\n\t\t} else if (!strcmp(argv[i], \"anchor\")) {\n\t\t\tflags |= SPF_DN_ANCHOR;\n\t\t} else if (!strcmp(argv[i], \"chomp\")) {\n\t\t\tflags |= SPF_DN_CHOMP;\n\t\t} else\n\t\t\tpanic(\"%s: invalid flag (\\\"super\\\", \\\"trunc[=LIMIT]\\\", \\\"anchor\\\", \\\"chomp\\\")\", argv[i]);\n\t}\n\n\tlen = spf_fixdn(dst, argv[0], SPF_MIN(lim, sizeof dst), flags);\n\n\tif (SPF_DEBUG >= 2) {\n\t\tif (len < lim || !len)\n\t\t\tSPF_SAY(\"%zu[%s]\\n\", len, dst);\n\t\telse if (!lim)\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim), dst);\n\t\telse\n\t\t\tSPF_SAY(\"-%zu[%s]\\n\", (len - lim) + 1, dst);\n\t}\n\n\tputs(dst);\n\n\treturn 0;\n} \/* fixdn() *\/\n\n\n#define SIZE(x) { SPF_STRINGIFY(x), sizeof (struct x) }\n#define SIZEu(x) { SPF_STRINGIFY(x), sizeof (union x) }\nint sizes(int argc, char *argv[]) {\n\tstatic const struct { const char *name; size_t size; } type[] = {\n\t\tSIZE(spf_env), SIZE(spf_resolver), SIZE(spf_vm), SIZE(vm_sub),\n\t\tSIZEu(spf_term), SIZE(spf_all), SIZE(spf_include), SIZE(spf_a),\n\t\tSIZE(spf_mx), SIZE(spf_ptr), SIZE(spf_ip4), SIZE(spf_ip6), \n\t\tSIZE(spf_exists), SIZE(spf_redirect), SIZE(spf_exp), SIZE(spf_unknown), \n\t};\n\tint i, max;\n\n\tfor (i = 0, max = 0; i < spf_lengthof(type); i++)\n\t\tmax = SPF_MAX(max, strlen(type[i].name));\n\n\tfor (i = 0; i < spf_lengthof(type); i++)\n\t\tprintf(\"%*s : %zu\\n\", max, type[i].name, type[i].size);\n\n\treturn 0;\n} \/* sizes() *\/\n\n\nint printenv(int argc, char *argv[], const struct spf_env *env) {\n\tprintf(\"%%{s} : %s\\n\", env->s);\n\tprintf(\"%%{l} : %s\\n\", env->l);\n\tprintf(\"%%{o} : %s\\n\", env->o);\n\tprintf(\"%%{d} : %s\\n\", env->d);\n\tprintf(\"%%{i} : %s\\n\", env->i);\n\tprintf(\"%%{p} : %s\\n\", env->p);\n\tprintf(\"%%{v} : %s\\n\", env->v);\n\tprintf(\"%%{h} : %s\\n\", env->h);\n\tprintf(\"%%{c} : %s\\n\", env->c);\n\tprintf(\"%%{r} : %s\\n\", env->r);\n\tprintf(\"%%{t} : %s\\n\", env->t);\n\n\treturn 0;\n} \/* printenv() *\/\n\n\n#define USAGE \\\n\t\"spf [-S:L:O:D:I:P:V:H:C:R:T:f:vh] ACTION\\n\" \\\n\t\" -S EMAIL \\n\" \\\n\t\" -L LOCAL local-part of \\n\" \\\n\t\" -O DOMAIN domain of \\n\" \\\n\t\" -D DOMAIN \\n\" \\\n\t\" -I IP \\n\" \\\n\t\" -P DOMAIN the validated domain name of \\n\" \\\n\t\" -V STR the string \\\"in-addr\\\" if is ipv4, or \\\"ip6\\\" if ipv6\\n\" \\\n\t\" -H DOMAIN HELO\/EHLO domain\\n\" \\\n\t\" -C IP SMTP client IP\\n\" \\\n\t\" -R DOMAIN domain name of host performing the check\\n\" \\\n\t\" -T TIME current timestamp\\n\" \\\n\t\" -f PATH path to file (e.g. to load vm instead of stdin)\\n\" \\\n\t\" -W print version\\n\" \\\n\t\" -v be verbose (use more to increase verboseness)\\n\" \\\n\t\" -h print usage\\n\" \\\n\t\"\\n\" \\\n\t\" check Check SPF policy\\n\" \\\n\t\" parse Parse the SPF policy, pretty-print errors\\n\" \\\n\t\" expand Expand the SPF macro\\n\" \\\n\t\" macros List the embedded macros\\n\" \\\n\t\" ip6 [\\\"nybble\\\" | \\\"compat\\\" | \\\"mapped\\\" | \\\"mixed\\\" | \\\"libc\\\"]\\n\" \\\n\t\" Parse and compose address according to options\\n\" \\\n\t\" ip4 See ip6\\n\" \\\n\t\" fixdn [\\\"super\\\" | \\\"trunc[=LIMIT]\\\" | \\\"anchor\\\" | \\\"chomp\\\"]\\n\" \\\n\t\" Operate on domain string\\n\" \\\n\t\" vm Assemble STDIN into bytecode and execute\\n\" \\\n\t\" sizes Print data structure sizes\\n\" \\\n\t\" printenv Print SPF environment\\n\" \\\n\t\"\\n\" \\\n\t\"Reports bugs to william@25thandClement.com\\n\"\n\n\nstatic void version(FILE *fp) {\n\tfprintf(fp, \"spf (spf.c) %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"vendor %s\\n\", spf_vendor());\n\tfprintf(fp, \"release %.8X\\n\", spf_v_rel());\n\tfprintf(fp, \"abi %.8X\\n\", spf_v_abi());\n\tfprintf(fp, \"api %.8X\\n\", spf_v_api());\n\tfprintf(fp, \"dns %.8X\\n\", dns_v_rel());\n} \/* version() *\/\n\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint opt;\n\tstruct spf_env env;\n\tconst char *file = 0;\n\n\tmemset(&env, 0, sizeof env);\n\n\tspf_strlcpy(env.p, \"unknown\", sizeof env.p);\n\tspf_strlcpy(env.v, \"in-addr\", sizeof env.v);\n\tgethostname(env.r, sizeof env.r);\n\tspf_itoa(env.t, sizeof env.t, (unsigned)time(0));\n\n\twhile (-1 != (opt = getopt(argc, argv, \"S:L:O:D:I:P:V:H:C:R:T:f:vWh\"))) {\n\t\tswitch (opt) {\n\t\tcase 'S':\n\t\t\t{\n\t\t\t\tchar *argv[3];\n\t\t\t\tchar tmp[256];\n\n\t\t\t\tspf_strlcpy(tmp, optarg, sizeof tmp);\n\n\t\t\t\tif (2 == spf_split(spf_lengthof(argv), argv, tmp, \"@\", 0)) {\n\t\t\t\t\tif (!*env.l)\n\t\t\t\t\t\tspf_strlcpy(env.l, argv[0], sizeof env.l);\n\n\t\t\t\t\tif (!*env.o)\n\t\t\t\t\t\tspf_strlcpy(env.o, argv[1], sizeof env.o);\n\n\t\t\t\t\tif (!*env.d)\n\t\t\t\t\t\tspf_strlcpy(env.d, argv[1], sizeof env.d);\n\n\t\t\t\t\tif (!*env.h)\n\t\t\t\t\t\tspf_strlcpy(env.h, argv[1], sizeof env.h);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgoto setenv;\n\t\tcase 'L':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'O':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'D':\n\t\t\tgoto setenv;\n\t\tcase 'I':\n\t\t\tif (!*env.c)\n\t\t\t\tspf_strlcpy(env.c, optarg, sizeof env.c);\n\n\t\t\tgoto setenv;\n\t\tcase 'P':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'V':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'H':\n\t\t\tgoto setenv;\n\t\tcase 'C':\n\t\t\tif (!*env.i)\n\t\t\t\tspf_strlcpy(env.i, optarg, sizeof env.i);\n\n\t\t\tgoto setenv;\n\t\tcase 'R':\n\t\t\t\/* FALL THROUGH *\/\n\t\tcase 'T':\nsetenv:\n\t\t\tspf_setenv(&env, opt, optarg);\n\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tfile = optarg;\n\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tspf_debug++;\n\n\t\t\tbreak;\n\t\tcase 'W':\n\t\t\tversion(stdout);\n\n\t\t\treturn 0;\n\t\tcase 'h':\n\t\t\t\/* FALL THROUGH *\/\n\t\tdefault:\nusage:\n\t\t\tfputs(USAGE, stderr);\n\n\t\t\treturn (opt == 'h')? 0 : EXIT_FAILURE;\n\t\t} \/* switch() *\/\n\t} \/* while() *\/\n\n\targc -= optind;\n\targv += optind;\n\n\tif (!argc) {\n\t\tif (file)\n\t\t\tgoto vm;\n\n\t\tgoto usage;\n\t}\n\n\tif (!strcmp(argv[0], \"check\")) {\n\t\treturn check(argc-1, &argv[1], &env);\n\t} else if (!strcmp(argv[0], \"parse\") && argc > 1) {\n\t\treturn parse(argv[1]);\n\t} else if (!strcmp(argv[0], \"expand\") && argc > 1) {\n\t\treturn expand(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"macros\") && argc > 1) {\n\t\treturn macros(argv[1], &env);\n\t} else if (!strcmp(argv[0], \"ip6\") && argc > 1) {\n\t\treturn ip6(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"ip4\") && argc > 1) {\n\t\treturn ip4(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"fixdn\") && argc > 1) {\n\t\treturn fixdn(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"vm\")) {\nvm:\t\treturn vm(&env, file);\n\t} else if (!strcmp(argv[0], \"sizes\")) {\n\t\treturn sizes(argc - 1, &argv[1]);\n\t} else if (!strcmp(argv[0], \"printenv\")) {\n\t\treturn printenv(argc - 1, &argv[1], &env);\n\t} else\n\t\tgoto usage;\n\n\treturn 0;\n} \/* main() *\/\n\n\n#endif \/* SPF_MAIN *\/\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"b206dc40f039cc3f9896cb70f6270012fb364227","subject":"Ragel: optional debug","message":"Ragel: optional debug\n","repos":"pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf,gusevfe\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,pjotrp\/bioruby-vcf,CuppenResearch\/bioruby-vcf,gusevfe\/bioruby-vcf","old_file":"ragel\/gen_vcfheaderline_parser.rl","new_file":"ragel\/gen_vcfheaderline_parser.rl","new_contents":"# Ragel lexer for VCF-header\n#\n# This is a partial lexer for the VCF header format. Bio-vcf uses this\n# to generate meta information in (for example) JSON format. The\n# advantage of using a full state engine is that it allows for easy\n# parsing of key-value pairs with syntax checking and, for example,\n# escaped quotes in quoted string values. This edition validates ID and\n# Number fields only.\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action endquoted {\n emit.call(:value,data,ts,p)\n }\n\n action kw {\n emit.call(:kw,data,ts,p)\n }\n \n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %endquoted squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %endquoted dquote;\n\n integer = ('+'|'-')?digit+;\n float = ('+'|'-')?digit+'.'digit+;\n assignment = '=';\n identifier = (alpha alnum+); \n str = (ss|dd)* ; \n boolean = '.';\n key_word = ( ('Type'|'Description'|'Source'|'Version'|identifier - ('ID'|'Number')) >mark %{ emit.call(:key_word,data,ts,p) } );\n any_value = ( str|( integer|float|boolean|identifier >mark %{ emit.call(:value,data,ts,p) } ));\n id_value = ( identifier >mark %{ emit.call(:value,data,ts,p) } );\n \n number_value = ( ( integer|boolean|'A'|'R'|'G' ) >mark %{ emit.call(:value,data,ts,p) } );\n\n id_kv = ( ( ('ID') %kw '=' id_value ) @!{ error_code=\"ID\"} );\n number_kv = ( ( ('Number') %kw '=' number_value ) @!{ error_code=\"Number\"} );\n key_value = ( id_kv | number_kv | (key_word '=' any_value) ) >mark @!{ error_code=\"key-value\" };\n \n main := ( '##' ('FILTER'|'FORMAT'|'INFO'|'ALT') '=') (('<'|',') key_value )* ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef self.run_lexer(buf, options = {})\n do_debug = (options[:debug] == true)\n data = buf.unpack(\"c*\") if(buf.is_a?(String))\n eof = data.length\n values = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\" if do_debug\n values << [type,data[ts...p].pack('c*')]\n }\n\n error_code = nil\n \n %% write init;\n %% write exec;\n\n raise \"ERROR: \"+error_code+\" in \"+buf if error_code\n\n begin\n res = {}\n # p values\n values.each_slice(2) do | a,b |\n # p '*',a,b\n res[a[1]] = b[1]\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\n rescue\n print \"ERROR: \"\n p values\n end\n p res if do_debug\n res\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s|\n print s,\"\\n\"\n p VcfHeader::RagelKeyValues.run_lexer(s, debug: false)\n}\n\nend","old_contents":"# Ragel lexer for VCF-header\n#\n# This is a partial lexer for the VCF header format. Bio-vcf uses this\n# to generate meta information in (for example) JSON format. The\n# advantage of using a full state engine is that it allows for easy\n# parsing of key-value pairs with syntax checking and, for example,\n# escaped quotes in quoted string values. This edition validates ID and\n# Number fields only.\n\nmodule VcfHeader\n\n module RagelKeyValues\n \n=begin\n%%{\n\n machine simple_lexer;\n \n action mark { ts=p }\n action endquoted {\n emit.call(:value,data,ts,p)\n }\n\n action kw {\n emit.call(:kw,data,ts,p)\n }\n \n squote = \"'\";\n dquote = '\"';\n not_squote_or_escape = [^'\\\\];\n not_dquote_or_escape = [^\"\\\\];\n escaped_something = \/\\\\.\/;\n ss = space* squote ( not_squote_or_escape | escaped_something )* >mark %endquoted squote;\n dd = space* dquote ( not_dquote_or_escape | escaped_something )* >mark %endquoted dquote;\n\n integer = ('+'|'-')?digit+;\n float = ('+'|'-')?digit+'.'digit+;\n assignment = '=';\n identifier = (alpha alnum+); \n str = (ss|dd)* ; \n boolean = '.';\n key_word = ( ('Type'|'Description'|'Source'|'Version'|identifier - ('ID'|'Number')) >mark %{ emit.call(:key_word,data,ts,p) } );\n any_value = ( str|( integer|float|boolean|identifier >mark %{ emit.call(:value,data,ts,p) } ));\n id_value = ( identifier >mark %{ emit.call(:value,data,ts,p) } );\n \n number_value = ( ( integer|boolean|'A'|'R'|'G' ) >mark %{ emit.call(:value,data,ts,p) } );\n\n id_kv = ( ( ('ID') %kw '=' id_value ) @!{ error_code=\"ID\"} );\n number_kv = ( ( ('Number') %kw '=' number_value ) @!{ error_code=\"Number\"} );\n key_value = ( id_kv | number_kv | (key_word '=' any_value) ) >mark @!{ error_code=\"key-value\" };\n \n main := ( '##' ('FILTER'|'FORMAT'|'INFO'|'ALT') '=') (('<'|',') key_value )* ;\n}%%\n=end\n\n%% write data;\n# %% this just fixes our syntax highlighting...\n\ndef self.run_lexer(buf, options = {})\n data = buf.unpack(\"c*\") if(buf.is_a?(String))\n eof = data.length\n values = []\n stack = []\n\n emit = lambda { |type, data, ts, p|\n # Print the type and text of the last read token\n # p ts,p\n puts \"#{type}: #{data[ts...p].pack('c*')}\" if options[:debug]==true\n values << [type,data[ts...p].pack('c*')]\n }\n\n error_code = nil\n \n %% write init;\n %% write exec;\n\n raise \"ERROR: \"+error_code+\" in \"+buf if error_code\n\n begin\n res = {}\n # p values\n values.each_slice(2) do | a,b |\n # p '*',a,b\n res[a[1]] = b[1]\n # p h[:value] if h[:name]==:identifier or h[:name]==:value or h[:name]==:string\n end\n rescue\n print \"ERROR: \"\n p values\n end\n p res\nend\n\n end\nend\n\nif __FILE__ == $0\n\nlines = <\n##FORMAT=\n##FORMAT=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\n##INFO=\nLINES\n\nlines.strip.split(\"\\n\").each { |s|\n print s,\"\\n\"\n VcfHeader::RagelKeyValues.run_lexer(s, debug: false)\n}\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e0fcaa91df5f81a1b274292fbc7f695f5c77e037","subject":"Added single-quoted named group pattern","message":"Added single-quoted named group pattern\n","repos":"ammar\/regexp_parser,gjtorikian\/regexp_parser,jhart-r7\/regexp_parser,ammar\/regexp_parser","old_file":"lib\/regexp_parser\/scanner.rl","new_file":"lib\/regexp_parser\/scanner.rl","new_contents":"%%{\n machine re_scanner;\n\n wild = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n posix_class_name = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n property_name = 'Alnum' | 'Alpha' | 'Any' | 'Ascii' | 'Blank' |\n 'Cntrl' | 'Digit' | 'Graph' | 'Lower' | 'Print' |\n 'Punct' | 'Space' | 'Upper' | 'Word' | 'Xdigit';\n\n category_letter = 'L' . [ultmo]?;\n category_mark = 'M' . [nce]?;\n category_number = 'N' . [dlo]?;\n category_punctuation = 'P' . [cdseifo]?;\n category_symbol = 'S' . [mcko]?;\n category_separator = 'Z' . [slp]?;\n category_codepoint = 'C' . [cfson]?;\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n posix_class = '[:' . posix_class_name . ':]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n property_char = [pP];\n\n escaped_char = [aefnrtv];\n octal_sequence = '0' . [0-7]{2};\n\n hex_sequence = 'x' . xdigit{2};\n wide_hex_sequence = 'x' . '{7' . xdigit{1,7} . '}';\n\n control_sequence = ('c' | 'C-') . xdigit{1,2};\n meta_sequence = 'M-' . xdigit{1,2};\n meta_control_sequence = 'M-\\\\C-' . xdigit{1,2};\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_range = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_range;\n\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?') | ('?\\'' . group_name . '\\'');\n\n group_type = group_atomic | group_passive | group_named;\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters that 'break' a literal\n meta_char = wild | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n self.emit(:set, :close, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n '^' {\n self.emit(:set, :negate, data[ts..te-1].pack('c*'), ts, te)\n };\n\n alnum . '-' . alnum { # TODO: add properties\n self.emit(:set, :range, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '&&' {\n self.emit(:set, :intersection, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n posix_class {\n case text = data[ts..te-1].pack('c*')\n when '[:alnum:]'; self.emit(:set, :class_alnum, text, ts, te)\n when '[:alpha:]'; self.emit(:set, :class_alpha, text, ts, te)\n when '[:blank:]'; self.emit(:set, :class_blank, text, ts, te)\n when '[:cntrl:]'; self.emit(:set, :class_cntrl, text, ts, te)\n when '[:digit:]'; self.emit(:set, :class_digit, text, ts, te)\n when '[:graph:]'; self.emit(:set, :class_graph, text, ts, te)\n when '[:lower:]'; self.emit(:set, :class_lower, text, ts, te)\n when '[:print:]'; self.emit(:set, :class_print, text, ts, te)\n when '[:punct:]'; self.emit(:set, :class_punct, text, ts, te)\n when '[:space:]'; self.emit(:set, :class_space, text, ts, te)\n when '[:upper:]'; self.emit(:set, :class_upper, text, ts, te)\n when '[:xdigit:]'; self.emit(:set, :class_xdigit, text, ts, te)\n when '[:word:]'; self.emit(:set, :class_word, text, ts, te)\n when '[:ascii:]'; self.emit(:set, :class_ascii, text, ts, te)\n else raise \"Unsupported character posixe class at #{text} (char #{ts})\"\n end\n };\n\n any {\n self.emit(:set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' {\n self.emit(:set, :backspace, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [\\\\\\]\\-\\,] {\n self.emit(:set, :escape, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [dDhHsSwW] {\n case text = data[ts-1..te-1].pack('c*')\n when '\\d'; self.emit(:set, :type_digit, text, ts-1, te)\n when '\\D'; self.emit(:set, :type_nondigit, text, ts-1, te)\n when '\\h'; self.emit(:set, :type_hex, text, ts-1, te)\n when '\\H'; self.emit(:set, :type_nonhex, text, ts-1, te)\n when '\\s'; self.emit(:set, :type_space, text, ts-1, te)\n when '\\S'; self.emit(:set, :type_nonspace, text, ts-1, te)\n when '\\w'; self.emit(:set, :type_word, text, ts-1, te)\n when '\\W'; self.emit(:set, :type_nonword, text, ts-1, te)\n end\n\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n self.emit(:set, :range_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n hex_sequence {\n self.emit(:set, :member_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n hex_sequence {\n self.emit(:escape, :hex, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n wide_hex_sequence {\n self.emit(:escape, :hex_wide, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n control_sequence {\n self.emit(:escape, :control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_sequence {\n self.emit(:escape, :meta, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_control_sequence {\n self.emit(:escape, :meta_control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n # TODO: extract into a separate machine... use in sets\n property_char . '{' . (property_name | general_category) . '}' > (escaped_alpha, 2) {\n text = data[ts..te-1].pack('c*')\n type = text[0,1] == 'p' ? :property: :inverted_property\n\n case name = data[ts+2..te-2].pack('c*')\n\n # Named\n when 'Alnum'; self.emit(type, :alnum, text, ts, te)\n when 'Alpha'; self.emit(type, :alpha, text, ts, te)\n when 'Any'; self.emit(type, :any, text, ts, te)\n when 'Ascii'; self.emit(type, :ascii, text, ts, te)\n when 'Blank'; self.emit(type, :blank, text, ts, te)\n when 'Cntrl'; self.emit(type, :cntrl, text, ts, te)\n when 'Digit'; self.emit(type, :digit, text, ts, te)\n when 'Graph'; self.emit(type, :graph, text, ts, te)\n when 'Lower'; self.emit(type, :lower, text, ts, te)\n when 'Print'; self.emit(type, :print, text, ts, te)\n when 'Punct'; self.emit(type, :punct, text, ts, te)\n when 'Space'; self.emit(type, :space, text, ts, te)\n when 'Upper'; self.emit(type, :upper, text, ts, te)\n when 'Word'; self.emit(type, :word, text, ts, te)\n when 'Xdigit'; self.emit(type, :xdigit, text, ts, te)\n\n # Letters\n when 'L'; self.emit(type, :letter_any, text, ts, te)\n when 'Lu'; self.emit(type, :letter_uppercase, text, ts, te)\n when 'Ll'; self.emit(type, :letter_lowercase, text, ts, te)\n when 'Lt'; self.emit(type, :letter_titlecase, text, ts, te)\n when 'Lm'; self.emit(type, :letter_modifier, text, ts, te)\n when 'Lo'; self.emit(type, :letter_other, text, ts, te)\n\n # Marks\n when 'M'; self.emit(type, :mark_any, text, ts, te)\n when 'Mn'; self.emit(type, :mark_nonspacing, text, ts, te)\n when 'Mc'; self.emit(type, :mark_spacing, text, ts, te)\n when 'Me'; self.emit(type, :mark_enclosing, text, ts, te)\n\n # Numbers\n when 'N'; self.emit(type, :number_any, text, ts, te)\n when 'Nd'; self.emit(type, :number_decimal, text, ts, te)\n when 'Nl'; self.emit(type, :number_letter, text, ts, te)\n when 'No'; self.emit(type, :number_other, text, ts, te)\n\n # Punctuation\n when 'P'; self.emit(type, :punct_any, text, ts, te)\n when 'Pc'; self.emit(type, :punct_connector, text, ts, te)\n when 'Pd'; self.emit(type, :punct_dash, text, ts, te)\n when 'Ps'; self.emit(type, :punct_open, text, ts, te)\n when 'Pe'; self.emit(type, :punct_close, text, ts, te)\n when 'Pi'; self.emit(type, :punct_initial, text, ts, te)\n when 'Pf'; self.emit(type, :punct_final, text, ts, te)\n when 'Po'; self.emit(type, :punct_other, text, ts, te)\n\n # Symbols\n when 'S'; self.emit(type, :symbol_any, text, ts, te)\n when 'Sm'; self.emit(type, :symbol_math, text, ts, te)\n when 'Sc'; self.emit(type, :symbol_currency, text, ts, te)\n when 'Sk'; self.emit(type, :symbol_modifier, text, ts, te)\n when 'So'; self.emit(type, :symbol_other, text, ts, te)\n\n # Separators\n when 'Z'; self.emit(type, :separator_any, text, ts, te)\n when 'Zs'; self.emit(type, :separator_space, text, ts, te)\n when 'Zl'; self.emit(type, :separator_line, text, ts, te)\n when 'Zp'; self.emit(type, :separator_paragraph, text, ts, te)\n\n # Codepoints\n when 'C'; self.emit(type, :code_any, text, ts, te)\n when 'Cc'; self.emit(type, :code_control, text, ts, te)\n when 'Cf'; self.emit(type, :code_format, text, ts, te)\n when 'Cs'; self.emit(type, :code_surrogate, text, ts, te)\n when 'Co'; self.emit(type, :code_private, text, ts, te)\n when 'Cn'; self.emit(type, :code_unassigned, text, ts, te)\n end\n };\n\n any > (escaped_alpha, 1) {\n self.emit(:escape, :literal, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n alternation {\n self.emit(:meta, :alternation, data[ts..te-1].pack('c*'), ts, te)\n };\n\n wild {\n self.emit(:meta, :wild, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S whitespace, non-whitespace\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\d'; self.emit(:type, :digit, text, ts, te)\n when '\\\\D'; self.emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; self.emit(:type, :hex, text, ts, te)\n when '\\\\H'; self.emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; self.emit(:type, :space, text, ts, te)\n when '\\\\S'; self.emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; self.emit(:type, :word, text, ts, te)\n when '\\\\W'; self.emit(:type, :nonword, text, ts, te)\n end\n };\n\n # Anchors\n beginning_of_line {\n self.emit(:anchor, :beginning_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n end_of_line {\n self.emit(:anchor, :end_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\A'; self.emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; self.emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; self.emit(:anchor, :eos_or_before_eol, text, ts, te)\n when '\\\\b'; self.emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; self.emit(:anchor, :nonword_boundary, text, ts, te)\n else raise \"Unsupported anchor at #{text} (char #{ts})\"\n end\n };\n\n # Escaped sequences\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Character sets\n set_open {\n self.emit(:set, :open, data[ts..te-1].pack('c*'), ts, te)\n fcall character_set;\n };\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n group_open . group_comment {\n self.emit(:group, :comment, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # (?mix-mix...) expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n group_open . group_options {\n self.emit(:group, :options, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group (single quotes are no supported, yet)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type {\n case text = data[ts..te-1].pack('c*')\n when '(?:'; self.emit(:group, :passive, text, ts, te)\n when '(?>'; self.emit(:group, :atomic, text, ts, te)\n when \/\\(\\?<\\w+>\/\n self.emit(:group, :named, text, ts, te)\n end\n };\n\n group_open {\n text = data[ts..te-1].pack('c*')\n self.emit(:group, :capture, text, ts, te)\n };\n\n group_close {\n self.emit(:group, :close, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = data[ts..te-1].pack('c*')\n when '?' ; self.emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; self.emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; self.emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n \n zero_or_more {\n case text = data[ts..te-1].pack('c*')\n when '*' ; self.emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; self.emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; self.emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n \n one_or_more {\n case text = data[ts..te-1].pack('c*')\n when '+' ; self.emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; self.emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; self.emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n\n # Intervals: min, max, and exact notations\n # ------------------------------------------------------------------------\n range_open . (digit+)? . ','? . (digit+)? . range_close . quantifier_mode? {\n self.emit(:quantifier, :interval, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Literal: anything, except meta characters. This includes 2, 3, and 4\n # unicode byte sequences.\n # ------------------------------------------------------------------------\n (any - meta_char)+ {\n self.emit(:literal, :literal, data[ts..te-1].pack('c*'), ts, te)\n };\n\n *|;\n}%%\n","old_contents":"%%{\n machine re_scanner;\n\n wild = '.';\n backslash = '\\\\';\n alternation = '|';\n beginning_of_line = '^';\n end_of_line = '$';\n\n range_open = '{';\n range_close = '}';\n curlies = range_open | range_close;\n\n group_open = '(';\n group_close = ')';\n parantheses = group_open | group_close;\n\n set_open = '[';\n set_close = ']';\n brackets = set_open | set_close;\n\n posix_class_name = 'alnum' | 'alpha' | 'blank' |\n 'cntrl' | 'digit' | 'graph' |\n 'lower' | 'print' | 'punct' |\n 'space' | 'upper' | 'xdigit' |\n 'word' | 'ascii';\n\n property_name = 'Alnum' | 'Alpha' | 'Any' | 'Ascii' | 'Blank' |\n 'Cntrl' | 'Digit' | 'Graph' | 'Lower' | 'Print' |\n 'Punct' | 'Space' | 'Upper' | 'Word' | 'Xdigit';\n\n category_letter = 'L' . [ultmo]?;\n category_mark = 'M' . [nce]?;\n category_number = 'N' . [dlo]?;\n category_punctuation = 'P' . [cdseifo]?;\n category_symbol = 'S' . [mcko]?;\n category_separator = 'Z' . [slp]?;\n category_codepoint = 'C' . [cfson]?;\n general_category = category_letter | category_mark |\n category_number | category_punctuation |\n category_symbol | category_separator |\n category_codepoint;\n\n posix_class = '[:' . posix_class_name . ':]';\n\n char_type = [dDhHsSwW];\n\n line_anchor = beginning_of_line | end_of_line;\n anchor_char = [AbBzZG];\n property_char = [pP];\n\n escaped_char = [aefnrtv];\n octal_sequence = '0' . [0-7]{2};\n\n hex_sequence = 'x' . xdigit{2};\n wide_hex_sequence = 'x' . '{7' . xdigit{1,7} . '}';\n control_sequence = ('c' | 'C-') . xdigit{1,2};\n meta_sequence = 'M-' . xdigit{1,2};\n meta_control_sequence = 'M-\\\\C-' . xdigit{1,2};\n\n zero_or_one = '?' | '??' | '?+';\n zero_or_more = '*' | '*?' | '*+';\n one_or_more = '+' | '+?' | '++';\n\n quantifier_greedy = '?' | '*' | '+';\n quantifier_reluctant = '??' | '*?' | '+?';\n quantifier_possessive = '?+' | '*+' | '++';\n quantifier_mode = '?' | '+';\n\n quantifier_range = range_open . (digit+)? . ','? . (digit+)? .\n range_close . quantifier_mode?;\n\n quantifiers = quantifier_greedy | quantifier_reluctant |\n quantifier_possessive | quantifier_range;\n\n\n group_comment = '?#' . [^)]+ . group_close;\n\n group_atomic = '?>';\n group_passive = '?:';\n\n assertion_lookahead = '?=';\n assertion_nlookahead = '?!';\n assertion_lookbehind = '?<=';\n assertion_nlookbehind = '?';\n\n group_type = group_atomic | group_passive | group_named;\n\n assertion_type = assertion_lookahead | assertion_nlookahead |\n assertion_lookbehind | assertion_nlookbehind;\n\n # characters the 'break' a literal\n meta_char = wild | backslash | alternation |\n curlies | parantheses | brackets |\n line_anchor | quantifier_greedy;\n\n\n # Character set scanner, continues consuming characters until it meets the\n # closing bracket of the set.\n # --------------------------------------------------------------------------\n character_set := |*\n ']' {\n self.emit(:set, :close, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n '^' {\n self.emit(:set, :negate, data[ts..te-1].pack('c*'), ts, te)\n };\n\n alnum . '-' . alnum { # TODO: add properties\n self.emit(:set, :range, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '&&' {\n self.emit(:set, :intersection, data[ts..te-1].pack('c*'), ts, te)\n };\n\n '\\\\' {\n fcall set_escape_sequence;\n };\n\n posix_class {\n case text = data[ts..te-1].pack('c*')\n when '[:alnum:]'; self.emit(:set, :class_alnum, text, ts, te)\n when '[:alpha:]'; self.emit(:set, :class_alpha, text, ts, te)\n when '[:blank:]'; self.emit(:set, :class_blank, text, ts, te)\n when '[:cntrl:]'; self.emit(:set, :class_cntrl, text, ts, te)\n when '[:digit:]'; self.emit(:set, :class_digit, text, ts, te)\n when '[:graph:]'; self.emit(:set, :class_graph, text, ts, te)\n when '[:lower:]'; self.emit(:set, :class_lower, text, ts, te)\n when '[:print:]'; self.emit(:set, :class_print, text, ts, te)\n when '[:punct:]'; self.emit(:set, :class_punct, text, ts, te)\n when '[:space:]'; self.emit(:set, :class_space, text, ts, te)\n when '[:upper:]'; self.emit(:set, :class_upper, text, ts, te)\n when '[:xdigit:]'; self.emit(:set, :class_xdigit, text, ts, te)\n when '[:word:]'; self.emit(:set, :class_word, text, ts, te)\n when '[:ascii:]'; self.emit(:set, :class_ascii, text, ts, te)\n else raise \"Unsupported character posixe class at #{text} (char #{ts})\"\n end\n };\n\n any {\n self.emit(:set, :member, data[ts..te-1].pack('c*'), ts, te)\n };\n *|;\n\n # set escapes scanner\n # --------------------------------------------------------------------------\n set_escape_sequence := |*\n 'b' {\n self.emit(:set, :backspace, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [\\\\\\]\\-\\,] {\n self.emit(:set, :escape, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n [dDhHsSwW] {\n case text = data[ts-1..te-1].pack('c*')\n when '\\d'; self.emit(:set, :type_digit, text, ts-1, te)\n when '\\D'; self.emit(:set, :type_nondigit, text, ts-1, te)\n when '\\h'; self.emit(:set, :type_hex, text, ts-1, te)\n when '\\H'; self.emit(:set, :type_nonhex, text, ts-1, te)\n when '\\s'; self.emit(:set, :type_space, text, ts-1, te)\n when '\\S'; self.emit(:set, :type_nonspace, text, ts-1, te)\n when '\\w'; self.emit(:set, :type_word, text, ts-1, te)\n when '\\W'; self.emit(:set, :type_nonword, text, ts-1, te)\n end\n\n fret;\n };\n\n hex_sequence . '-\\\\' . hex_sequence {\n self.emit(:set, :range_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n\n hex_sequence {\n self.emit(:set, :member_hex, data[ts-1..te-1].pack('c*'), ts-1, te)\n fret;\n };\n *|;\n\n\n # escape sequence scanner\n # --------------------------------------------------------------------------\n escape_sequence := |*\n hex_sequence {\n self.emit(:escape, :hex, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n wide_hex_sequence {\n self.emit(:escape, :hex_wide, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n control_sequence {\n self.emit(:escape, :control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_sequence {\n self.emit(:escape, :meta, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n meta_control_sequence {\n self.emit(:escape, :meta_control, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n\n # TODO: extract into a separate machine... use in sets\n property_char . '{' . (property_name | general_category) . '}' > (escaped_alpha, 2) {\n text = data[ts..te-1].pack('c*')\n type = text[0,1] == 'p' ? :property: :inverted_property\n\n case name = data[ts+2..te-2].pack('c*')\n\n # Named\n when 'Alnum'; self.emit(type, :alnum, text, ts, te)\n when 'Alpha'; self.emit(type, :alpha, text, ts, te)\n when 'Any'; self.emit(type, :any, text, ts, te)\n when 'Ascii'; self.emit(type, :ascii, text, ts, te)\n when 'Blank'; self.emit(type, :blank, text, ts, te)\n when 'Cntrl'; self.emit(type, :cntrl, text, ts, te)\n when 'Digit'; self.emit(type, :digit, text, ts, te)\n when 'Graph'; self.emit(type, :graph, text, ts, te)\n when 'Lower'; self.emit(type, :lower, text, ts, te)\n when 'Print'; self.emit(type, :print, text, ts, te)\n when 'Punct'; self.emit(type, :punct, text, ts, te)\n when 'Space'; self.emit(type, :space, text, ts, te)\n when 'Upper'; self.emit(type, :upper, text, ts, te)\n when 'Word'; self.emit(type, :word, text, ts, te)\n when 'Xdigit'; self.emit(type, :xdigit, text, ts, te)\n\n # Letters\n when 'L'; self.emit(type, :letter_any, text, ts, te)\n when 'Lu'; self.emit(type, :letter_uppercase, text, ts, te)\n when 'Ll'; self.emit(type, :letter_lowercase, text, ts, te)\n when 'Lt'; self.emit(type, :letter_titlecase, text, ts, te)\n when 'Lm'; self.emit(type, :letter_modifier, text, ts, te)\n when 'Lo'; self.emit(type, :letter_other, text, ts, te)\n\n # Marks\n when 'M'; self.emit(type, :mark_any, text, ts, te)\n when 'Mn'; self.emit(type, :mark_nonspacing, text, ts, te)\n when 'Mc'; self.emit(type, :mark_spacing, text, ts, te)\n when 'Me'; self.emit(type, :mark_enclosing, text, ts, te)\n\n # Numbers\n when 'N'; self.emit(type, :number_any, text, ts, te)\n when 'Nd'; self.emit(type, :number_decimal, text, ts, te)\n when 'Nl'; self.emit(type, :number_letter, text, ts, te)\n when 'No'; self.emit(type, :number_other, text, ts, te)\n\n # Punctuation\n when 'P'; self.emit(type, :punct_any, text, ts, te)\n when 'Pc'; self.emit(type, :punct_connector, text, ts, te)\n when 'Pd'; self.emit(type, :punct_dash, text, ts, te)\n when 'Ps'; self.emit(type, :punct_open, text, ts, te)\n when 'Pe'; self.emit(type, :punct_close, text, ts, te)\n when 'Pi'; self.emit(type, :punct_initial, text, ts, te)\n when 'Pf'; self.emit(type, :punct_final, text, ts, te)\n when 'Po'; self.emit(type, :punct_other, text, ts, te)\n\n # Symbols\n when 'S'; self.emit(type, :symbol_any, text, ts, te)\n when 'Sm'; self.emit(type, :symbol_math, text, ts, te)\n when 'Sc'; self.emit(type, :symbol_currency, text, ts, te)\n when 'Sk'; self.emit(type, :symbol_modifier, text, ts, te)\n when 'So'; self.emit(type, :symbol_other, text, ts, te)\n\n # Separators\n when 'Z'; self.emit(type, :separator_any, text, ts, te)\n when 'Zs'; self.emit(type, :separator_space, text, ts, te)\n when 'Zl'; self.emit(type, :separator_line, text, ts, te)\n when 'Zp'; self.emit(type, :separator_paragraph, text, ts, te)\n\n # Codepoints\n when 'C'; self.emit(type, :code_any, text, ts, te)\n when 'Cc'; self.emit(type, :code_control, text, ts, te)\n when 'Cf'; self.emit(type, :code_format, text, ts, te)\n when 'Cs'; self.emit(type, :code_surrogate, text, ts, te)\n when 'Co'; self.emit(type, :code_private, text, ts, te)\n when 'Cn'; self.emit(type, :code_unassigned, text, ts, te)\n end\n };\n\n any > (escaped_alpha, 1) {\n self.emit(:escape, :literal, data[ts..te-1].pack('c*'), ts, te)\n fret;\n };\n *|;\n\n\n # Main scanner\n # --------------------------------------------------------------------------\n main := |*\n\n # Meta characters\n alternation {\n self.emit(:meta, :alternation, data[ts..te-1].pack('c*'), ts, te)\n };\n\n wild {\n self.emit(:meta, :wild, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Character types\n # \\d, \\D digit, non-digit\n # \\h, \\H hex, non-hex\n # \\s, \\S whitespace, non-whitespace\n # \\w, \\W word, non-word\n # ------------------------------------------------------------------------\n backslash . char_type > (backslashed, 2) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\d'; self.emit(:type, :digit, text, ts, te)\n when '\\\\D'; self.emit(:type, :nondigit, text, ts, te)\n when '\\\\h'; self.emit(:type, :hex, text, ts, te)\n when '\\\\H'; self.emit(:type, :nonhex, text, ts, te)\n when '\\\\s'; self.emit(:type, :space, text, ts, te)\n when '\\\\S'; self.emit(:type, :nonspace, text, ts, te)\n when '\\\\w'; self.emit(:type, :word, text, ts, te)\n when '\\\\W'; self.emit(:type, :nonword, text, ts, te)\n end\n };\n\n # Anchors\n beginning_of_line {\n self.emit(:anchor, :beginning_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n end_of_line {\n self.emit(:anchor, :end_of_line, data[ts..te-1].pack('c*'), ts, te)\n };\n\n backslash . anchor_char > (backslashed, 3) {\n case text = data[ts..te-1].pack('c*')\n when '\\\\A'; self.emit(:anchor, :bos, text, ts, te)\n when '\\\\z'; self.emit(:anchor, :eos, text, ts, te)\n when '\\\\Z'; self.emit(:anchor, :eos_or_before_eol, text, ts, te)\n when '\\\\b'; self.emit(:anchor, :word_boundary, text, ts, te)\n when '\\\\B'; self.emit(:anchor, :nonword_boundary, text, ts, te)\n else raise \"Unsupported anchor at #{text} (char #{ts})\"\n end\n };\n\n # Escaped sequences\n backslash > (backslashed, 1) {\n fcall escape_sequence;\n };\n\n # Character sets\n set_open {\n self.emit(:set, :open, data[ts..te-1].pack('c*'), ts, te)\n fcall character_set;\n };\n\n # (?#...) comments: parsed as a single expression, without introducing a\n # new nesting level. Comments may not include parentheses, escaped or not.\n group_open . group_comment {\n self.emit(:group, :comment, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # (?mix-mix...) expression options:\n # (?imx-imx) option on\/off\n # i: ignore case\n # m: multi-line (dot(.) match newline)\n # x: extended form\n #\n # (?imx-imx:subexp) option on\/off for subexp\n group_open . group_options {\n self.emit(:group, :options, data[ts..te-1].pack('c*'), ts, te)\n };\n\n # Assertions\n # (?=subexp) look-ahead\n # (?!subexp) negative look-ahead\n # (?<=subexp) look-behind\n # (?subexp) atomic group, don't backtrack in subexp.\n # (?subexp) named group (single quotes are no supported, yet)\n # (subexp) captured group\n # ------------------------------------------------------------------------\n group_open . group_type {\n case text = data[ts..te-1].pack('c*')\n when '(?:'; self.emit(:group, :passive, text, ts, te)\n when '(?>'; self.emit(:group, :atomic, text, ts, te)\n when \/\\(\\?<\\w+>\/\n self.emit(:group, :named, text, ts, te)\n end\n };\n\n group_open {\n text = data[ts..te-1].pack('c*')\n self.emit(:group, :capture, text, ts, te)\n };\n\n group_close {\n self.emit(:group, :close, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Quantifiers\n # ------------------------------------------------------------------------\n zero_or_one {\n case text = data[ts..te-1].pack('c*')\n when '?' ; self.emit(:quantifier, :zero_or_one, text, ts, te)\n when '??'; self.emit(:quantifier, :zero_or_one_reluctant, text, ts, te)\n when '?+'; self.emit(:quantifier, :zero_or_one_possessive, text, ts, te)\n end\n };\n \n zero_or_more {\n case text = data[ts..te-1].pack('c*')\n when '*' ; self.emit(:quantifier, :zero_or_more, text, ts, te)\n when '*?'; self.emit(:quantifier, :zero_or_more_reluctant, text, ts, te)\n when '*+'; self.emit(:quantifier, :zero_or_more_possessive, text, ts, te)\n end\n };\n \n one_or_more {\n case text = data[ts..te-1].pack('c*')\n when '+' ; self.emit(:quantifier, :one_or_more, text, ts, te)\n when '+?'; self.emit(:quantifier, :one_or_more_reluctant, text, ts, te)\n when '++'; self.emit(:quantifier, :one_or_more_possessive, text, ts, te)\n end\n };\n\n\n # Intervals: min, max, and exact notations\n # ------------------------------------------------------------------------\n range_open . (digit+)? . ','? . (digit+)? . range_close . quantifier_mode? {\n self.emit(:quantifier, :interval, data[ts..te-1].pack('c*'), ts, te)\n };\n\n\n # Literal: anything, except meta characters. This includes 2, 3, and 4\n # unicode byte sequences.\n # ------------------------------------------------------------------------\n (any - meta_char)+ {\n self.emit(:literal, :literal, data[ts..te-1].pack('c*'), ts, te)\n };\n\n *|;\n}%%\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"e4515bc325a64f53cca1cef5c7cc194d22f0d9dc","subject":"End list should only occur in list context.","message":"End list should only occur in list context.\n","repos":"ajwans\/libtoml,gdm85\/libtoml","old_file":"toml_parse.rl","new_file":"toml_parse.rl","new_contents":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"toml.h\"\n#include \n\nstruct toml_stack_item {\n\tstruct list_node list;\n\tenum toml_type list_type;\n\tstruct toml_node *node;\n};\n\nstatic const char *\ntoml_type_to_str(enum toml_type type)\n{\n#define CASE_ENUM_TO_STR(x) case(x): return #x\n\tswitch (type) {\n\tCASE_ENUM_TO_STR(TOML_ROOT);\n\tCASE_ENUM_TO_STR(TOML_KEYGROUP);\n\tCASE_ENUM_TO_STR(TOML_LIST);\n\tCASE_ENUM_TO_STR(TOML_INT);\n\tCASE_ENUM_TO_STR(TOML_FLOAT);\n\tCASE_ENUM_TO_STR(TOML_STRING);\n\tCASE_ENUM_TO_STR(TOML_DATE);\n\tCASE_ENUM_TO_STR(TOML_BOOLEAN);\n\t}\n#undef CASE_ENUM_TO_STR\n\treturn \"unknown toml type\";\n}\n\n%%{\n\tmachine toml;\n\n\twhitespace = [\\t ]*;\n\n\tname = (print - (whitespace|']'))+ >{ts = p;};\n\n\taction float_add_place {\n\t\tfloating += (fc - '0') * ((float)1\/dec_pos);\n\t\tdec_pos *= 10;\n\t}\n\n\taction saw_key {\n\t\tname = strndup(ts, namelen);\n\t}\n\n\taction saw_bool {\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_BOOLEAN) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_BOOLEAN), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_BOOLEAN;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_BOOLEAN;\n\t\t\titem->node.value.integer = number;\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_BOOLEAN;\n\t\t\titem->node.value.integer = number;\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t}\n\t}\n\n\taction saw_int {\n\t\tnumber *= sign;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_INT) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_INT), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_INT;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_INT;\n\t\t\titem->node.value.integer = number;\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_INT;\n\t\t\titem->node.value.integer = number;\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t}\n\n\t\tfhold;\n\t}\n\n\taction saw_float {\n\t\tfloating *= sign;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_FLOAT) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_FLOAT), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_FLOAT;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_FLOAT;\n\t\t\titem->node.value.floating = floating;\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_FLOAT;\n\t\t\titem->node.value.floating = floating;\n\t\t}\n\n\t\tfhold;\n\t}\n\n\taction saw_string {\n\t\tint len = strp - string;\n\t\t*strp = 0;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_STRING) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_STRING), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_STRING;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_STRING;\n\t\t\titem->node.value.string = malloc(len);\n\t\t\tif (!item->node.value.string) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tmemcpy(item->node.value.string, string, len);\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_STRING;\n\t\t\titem->node.value.string = malloc(len);\n\t\t\tif (!item->node.value.string) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tmemcpy(item->node.value.string, string, len);\n\t\t}\n\t}\n\n\taction saw_date {\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_DATE) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_DATE), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_DATE;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_DATE;\n\t\t\titem->node.value.epoch = timegm(&tm);\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_DATE;\n\t\t\titem->node.value.epoch = timegm(&tm);\n\t\t}\n\t}\n\n\taction start_list {\n\t\tstruct toml_node *node;\n\n\t\t\/*\n\t\t * if the list stack is empty add this list to the keygroup\n\t\t * otherwise it should be added the to list on top of the stack\n\t\t *\/\n\t\tif (list_empty(&list_stack)) {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\t\/* first add it to the keygroup *\/\n\t\t\titem->node.type = TOML_LIST;\n\t\t\tlist_head_init(&item->node.value.list);\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\tnode = &item->node;\n\t\t} else {\n\t\t\tstruct toml_stack_item *tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_LIST;\n\t\t\titem->node.name = NULL;\n\t\t\tlist_head_init(&item->node.value.list);\n\n\t\t\tlist_add_tail(&tail->node->value.list, &item->list);\n\t\t\tnode = &item->node;\n\t\t}\n\n\t\t\/* push this list onto the stack *\/\n\t\tstruct toml_stack_item *stack_item = malloc(sizeof(*stack_item));\n\t\tif (!stack_item) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\t\tstack_item->node = node;\n\t\tstack_item->list_type = 0;\n\t\tlist_add_tail(&list_stack, &stack_item->list);\n\t}\n\n\taction end_list {\n\t\tstruct toml_stack_item *tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tlist_del(&tail->list);\n\t\tfree(tail);\n\n\t\tif (!list_empty(&list_stack))\n\t\t\tfnext list;\n\t}\n\n\taction saw_keygroup {\n\t\tchar *ancestor, *tofree, *keygroupname;\n\n\t\tstruct toml_node *place = toml_root;\n\n\t\ttofree = keygroupname = strndup(ts, (int)(p-ts));\n\n\t\twhile ((ancestor = strsep(&keygroupname, \".\"))) {\n\t\t\tstruct toml_keygroup_item *item;\n\t\t\tint found = 0;\n\n\t\t\tlist_for_each(&place->value.map, item, map) {\n\t\t\t\tif (strcmp(item->node.name, ancestor) == 0) {\n\t\t\t\t\tplace = &item->node;\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found)\n\t\t\t\tcontinue;\n\n\t\t\t\/* this is the auto-vivification *\/\n\t\t\titem = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\titem->node.name = strdup(ancestor);\n\t\t\titem->node.type = TOML_KEYGROUP;\n\t\t\tlist_head_init(&item->node.value.map);\n\t\t\tlist_add_tail(&place->value.map, &item->map);\n\n\t\t\tplace = &item->node;\n\t\t}\n\n\t\tfree(tofree);\n\n\t\tif (place->type != TOML_KEYGROUP) {\n\t\t\tparse_error = 1;\n\t\t\tfbreak;\n\t\t}\n\n\t\tcur_keygroup = place;\n\t}\n\n\tlines = (\n\t\tstart: (\n\t\t\t# count the indentation to know where the keygroups end\n\t\t\t[\\t ]* >{ indent = 0; } ${ indent++; } ->text\n\t\t),\n\n\t\t# just discard everything until newline\n\t\tcomment: ( [^\\n]*[\\n] @{curline++;} ->start ),\n\n\t\t# a keygroup\n\t\tkeygroup: ( name ']' @saw_keygroup ->start ),\n\n\t\t# the boolean data type\n\t\ttrue: \t( any\t>{fhold;} $saw_bool\t->start ),\n\t\tfalse: \t( any \t>{fhold;} $saw_bool\t->start ),\n\n\t\t# String, we have to escape \\0, \\t, \\n, \\r, everything else can\n\t\t# be prefixed with a slash and the slash just gets dropped\n\t\tstring: (\n\t\t\t'\"' $saw_string\t\t\t\t->start\t\t\t|\n\t\t\t[\\n] ${curline++; *strp++=fc;}\t->string\t\t|\n\t\t\t[\\\\]\t\t\t\t\t\t\t->str_escape\t|\n\t\t\t[^\"\\n\\\\] ${*strp++=fc;}\t\t\t->string\n\t\t),\n\t\tstr_escape: (\n\t\t\t\"0\"\t${*strp++=0;}\t\t-> string |\n\t\t\t\"t\"\t${*strp++='\\t';}\t-> string |\n\t\t\t\"n\"\t${*strp++='\\n';}\t-> string |\n\t\t\t\"r\"\t${*strp++='\\r';}\t-> string |\n\t\t\t[^0tnr]\t${*strp++=fc;}\t-> string\n\t\t),\n\n\t\t# A sign can optiionally prefix a number\n\t\tsign: (\n\t\t\t'-' ${sign = -1;}\t->number |\n\t\t\t'+' ${sign = 1;}\t->number\n\t\t),\n\t\tnumber: (\n\t\t\tdigit ${number *= 10; number += fc - '0';}\t->number\t\t\t|\n\t\t\t'.'\t${floating = number; dec_pos = 10;}\t\t->fractional_part\t|\n\t\t\t[\\n] ${curline++;} $saw_int\t\t\t\t\t->start\t\t\t\t|\n\t\t\t[^0-9.]\t$saw_int\t\t\t\t\t\t\t->start\n\t\t),\n\n\n\t\t# When we don't know yet if this is going to be a date or a number\n\t\t# this is the state\n\t\tnumber_or_date: (\n\t\t\tdigit ${number *= 10; number += fc - '0';}\t->number_or_date\t|\n\t\t\t'-'\t${tm.tm_year = number - 1900;}\t\t\t->date\t\t\t\t|\n\t\t\t'.'\t${floating = number * sign; dec_pos = 10;}\t\t\t->fractional_part\t|\n\t\t\t[\\n] ${curline++;} $saw_int\t\t\t\t\t\t\t\t->start\t|\n\t\t\t[\\t ,\\]] $saw_int\t\t\t\t\t\t\t\t\t\t->start\n\t\t),\n\n\n\t\t# Fractional part of a double\n\t\tfractional_part: (\n\t\t\t[0-9] \t$float_add_place\t->fractional_part |\n\t\t\t[^0-9] $saw_float\t\t\t->start\n\t\t),\n\n\t\t# Zulu date, we've already picked up the first four digits and the '-'\n\t\t# when figuring this was a date and not a number\n\t\tdate: (\n\t\t\tdigit{2} @{tm.tm_mon = atoi(fpc-1) - 1;}\n\t\t\t'-'\n\t\t\tdigit{2} @{tm.tm_mday = atoi(fpc-1);}\n\t\t\t'T'\n\t\t\tdigit{2} @{tm.tm_hour = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_min = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_sec = atoi(fpc-1);}\n\t\t\t'Z' @saw_date ->start\n\t\t),\n\n\t\t# Non-list value\n\t\tsingular: (\n\t\t\t'true'\t@{number = 1;}\t\t\t\t-> true\t\t|\n\t\t\t'false'\t@{number = 0;}\t\t\t\t-> false\t|\n\t\t\t'\"' ${strp = string;}\t\t\t\t-> string\t|\n\t\t\t('-'|'+') ${fhold;number = 0;}\t\t-> sign\t\t|\n\t\t\tdigit ${sign = 1;fhold;number = 0;}\t-> number_or_date\n\t\t),\n\n\t\t# A list of values\n\t\tlist: (\n\t\t\t'#'\t\t\t\t\t\t\t\t->comment\t|\n\t\t\t'\\n' ${ curline++; }\t\t\t->list\t\t|\n\t\t\t[\\t ]\t\t\t\t\t\t\t->list\t\t|\n\t\t\t','\t\t\t\t\t\t\t\t->val\t\t|\n\t\t\t']'\t$end_list\t\t\t\t\t->start\t\t|\n\t\t\t[^#\\t, \\n\\]] ${fhold;}\t\t\t->val\n\t\t),\n\n\t\t# A val can be either a list or a singular value\n\t\tval: (\n\t\t\t'#'\t\t\t\t\t\t\t->comment\t|\n\t\t\t'\\n' ${ curline++; }\t\t->val\t\t|\n\t\t\t[\\t ]\t\t\t\t\t\t->val\t\t|\n\t\t\t'[' $start_list\t\t\t\t->list\t\t|\n\t\t\t']'\t$end_list\t\t\t\t->start\t\t|\n\t\t\t[^#\\t \\n[\\]] ${fhold;}\t\t->singular\n\t\t)\n\n\t\t# A regular key\n\t\tkey: (\n\t\t\tname whitespace >{namelen = (int)(p-ts);} '=' $saw_key ->val\n\t\t),\n\n\t\t# Text stripped of leading whitespace\n\t\ttext: (\n\t\t\t'#'\t\t\t\t\t\t\t->comment\t|\n\t\t\t'['\t\t\t\t\t\t\t->keygroup\t|\n\t\t\t[\\t ]\t\t\t\t\t\t->text\t\t|\n\t\t\t'\\n' ${curline++;}\t\t\t->start |\n\t\t\t[^#[\\t \\n,\\]]\t${fhold;}\t->key\n\t\t)\n\t);\n\n\tmain := lines?;\n}%%\n\n%%write data;\n\nint\ntoml_parse(struct toml_node *toml_root, char *buf, int buflen)\n{\n\tint indent = 0, cs, curline = 1;\n\tchar *p, *pe;\n\tchar *ts;\n\tchar string[1024], *strp;\n\tint sign, number, dec_pos, namelen;\n\tstruct tm tm;\n\tdouble floating;\n\tchar *name;\n\tint parse_error = 0, malloc_error = 0;\n\n\tstruct toml_node *cur_keygroup = toml_root;\n\n\tstruct list_head list_stack;\n\tlist_head_init(&list_stack);\n\n\tassert(toml_root->type == TOML_ROOT);\n\n\t%% write init;\n\n\tp = buf;\n\tpe = buf + buflen;\n\n\t%% write exec;\n\n\tif (malloc_error) {\n\t\tfprintf(stderr, \"malloc failed, line %d\\n\", curline);\n\t\treturn 1;\n\t}\n\n\tif (cs == toml_error || parse_error) {\n\t\tfprintf(stderr, \"PARSE_ERROR, line %d, p = '%.5s'\", curline, p);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n","old_contents":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"toml.h\"\n#include \n\nstruct toml_stack_item {\n\tstruct list_node list;\n\tenum toml_type list_type;\n\tstruct toml_node *node;\n};\n\nstatic const char *\ntoml_type_to_str(enum toml_type type)\n{\n#define CASE_ENUM_TO_STR(x) case(x): return #x\n\tswitch (type) {\n\tCASE_ENUM_TO_STR(TOML_ROOT);\n\tCASE_ENUM_TO_STR(TOML_KEYGROUP);\n\tCASE_ENUM_TO_STR(TOML_LIST);\n\tCASE_ENUM_TO_STR(TOML_INT);\n\tCASE_ENUM_TO_STR(TOML_FLOAT);\n\tCASE_ENUM_TO_STR(TOML_STRING);\n\tCASE_ENUM_TO_STR(TOML_DATE);\n\tCASE_ENUM_TO_STR(TOML_BOOLEAN);\n\t}\n#undef CASE_ENUM_TO_STR\n\treturn \"unknown toml type\";\n}\n\n%%{\n\tmachine toml;\n\n\twhitespace = [\\t ]*;\n\n\tname = (print - (whitespace|']'))+ >{ts = p;};\n\n\taction float_add_place {\n\t\tfloating += (fc - '0') * ((float)1\/dec_pos);\n\t\tdec_pos *= 10;\n\t}\n\n\taction saw_key {\n\t\tname = strndup(ts, namelen);\n\t}\n\n\taction saw_bool {\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_BOOLEAN) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_BOOLEAN), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_BOOLEAN;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_BOOLEAN;\n\t\t\titem->node.value.integer = number;\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_BOOLEAN;\n\t\t\titem->node.value.integer = number;\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t}\n\t}\n\n\taction saw_int {\n\t\tnumber *= sign;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_INT) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_INT), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_INT;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_INT;\n\t\t\titem->node.value.integer = number;\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_INT;\n\t\t\titem->node.value.integer = number;\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t}\n\n\t\tfhold;\n\t}\n\n\taction saw_float {\n\t\tfloating *= sign;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_FLOAT) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_FLOAT), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_FLOAT;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_FLOAT;\n\t\t\titem->node.value.floating = floating;\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_FLOAT;\n\t\t\titem->node.value.floating = floating;\n\t\t}\n\n\t\tfhold;\n\t}\n\n\taction saw_string {\n\t\tint len = strp - string;\n\t\t*strp = 0;\n\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_STRING) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_STRING), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_STRING;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_STRING;\n\t\t\titem->node.value.string = malloc(len);\n\t\t\tif (!item->node.value.string) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tmemcpy(item->node.value.string, string, len);\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_STRING;\n\t\t\titem->node.value.string = malloc(len);\n\t\t\tif (!item->node.value.string) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tmemcpy(item->node.value.string, string, len);\n\t\t}\n\t}\n\n\taction saw_date {\n\t\tstruct toml_stack_item *cur_list =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tif (cur_list) {\n\t\t\tif (cur_list->list_type && cur_list->list_type != TOML_DATE) {\n\t\t\t\tfprintf(stderr, \"incompatible types list %s this %s line %d\\n\",\n\t\t\t\t\t\ttoml_type_to_str(cur_list->list_type),\n\t\t\t\t\t\ttoml_type_to_str(TOML_DATE), curline);\n\t\t\t\tparse_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\tcur_list->list_type = TOML_DATE;\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_DATE;\n\t\t\titem->node.value.epoch = timegm(&tm);\n\t\t\titem->node.name = NULL;\n\n\t\t\tlist_add_tail(&cur_list->node->value.list, &item->list);\n\n\t\t\tfnext list;\n\t\t} else {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\titem->node.type = TOML_DATE;\n\t\t\titem->node.value.epoch = timegm(&tm);\n\t\t}\n\t}\n\n\taction start_list {\n\t\tstruct toml_node *node;\n\n\t\t\/*\n\t\t * if the list stack is empty add this list to the keygroup\n\t\t * otherwise it should be added the to list on top of the stack\n\t\t *\/\n\t\tif (list_empty(&list_stack)) {\n\t\t\tstruct toml_keygroup_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\t\/* first add it to the keygroup *\/\n\t\t\titem->node.type = TOML_LIST;\n\t\t\tlist_head_init(&item->node.value.list);\n\t\t\tlist_add_tail(&cur_keygroup->value.map, &item->map);\n\t\t\titem->node.name = name;\n\t\t\tnode = &item->node;\n\t\t} else {\n\t\t\tstruct toml_stack_item *tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\t\tstruct toml_list_item *item = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\n\t\t\titem->node.type = TOML_LIST;\n\t\t\titem->node.name = NULL;\n\t\t\tlist_head_init(&item->node.value.list);\n\n\t\t\tlist_add_tail(&tail->node->value.list, &item->list);\n\t\t\tnode = &item->node;\n\t\t}\n\n\t\t\/* push this list onto the stack *\/\n\t\tstruct toml_stack_item *stack_item = malloc(sizeof(*stack_item));\n\t\tif (!stack_item) {\n\t\t\tmalloc_error = 1;\n\t\t\tfbreak;\n\t\t}\n\t\tstack_item->node = node;\n\t\tstack_item->list_type = 0;\n\t\tlist_add_tail(&list_stack, &stack_item->list);\n\t}\n\n\taction end_list {\n\t\tstruct toml_stack_item *tail =\n\t\t\t\t\t\tlist_tail(&list_stack, struct toml_stack_item, list);\n\n\t\tlist_del(&tail->list);\n\t\tfree(tail);\n\n\t\tif (!list_empty(&list_stack))\n\t\t\tfnext list;\n\t}\n\n\taction saw_keygroup {\n\t\tchar *ancestor, *tofree, *keygroupname;\n\n\t\tstruct toml_node *place = toml_root;\n\n\t\ttofree = keygroupname = strndup(ts, (int)(p-ts));\n\n\t\twhile ((ancestor = strsep(&keygroupname, \".\"))) {\n\t\t\tstruct toml_keygroup_item *item;\n\t\t\tint found = 0;\n\n\t\t\tlist_for_each(&place->value.map, item, map) {\n\t\t\t\tif (strcmp(item->node.name, ancestor) == 0) {\n\t\t\t\t\tplace = &item->node;\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found)\n\t\t\t\tcontinue;\n\n\t\t\t\/* this is the auto-vivification *\/\n\t\t\titem = malloc(sizeof(*item));\n\t\t\tif (!item) {\n\t\t\t\tmalloc_error = 1;\n\t\t\t\tfbreak;\n\t\t\t}\n\t\t\titem->node.name = strdup(ancestor);\n\t\t\titem->node.type = TOML_KEYGROUP;\n\t\t\tlist_head_init(&item->node.value.map);\n\t\t\tlist_add_tail(&place->value.map, &item->map);\n\n\t\t\tplace = &item->node;\n\t\t}\n\n\t\tfree(tofree);\n\n\t\tif (place->type != TOML_KEYGROUP) {\n\t\t\tparse_error = 1;\n\t\t\tfbreak;\n\t\t}\n\n\t\tcur_keygroup = place;\n\t}\n\n\tlines = (\n\t\tstart: (\n\t\t\t# count the indentation to know where the keygroups end\n\t\t\t[\\t ]* >{ indent = 0; } ${ indent++; } ->text\n\t\t),\n\n\t\t# just discard everything until newline\n\t\tcomment: ( [^\\n]*[\\n] @{curline++;} ->start ),\n\n\t\t# a keygroup\n\t\tkeygroup: ( name ']' @saw_keygroup ->start ),\n\n\t\t# the boolean data type\n\t\ttrue: \t( any\t>{fhold;} $saw_bool\t->start ),\n\t\tfalse: \t( any \t>{fhold;} $saw_bool\t->start ),\n\n\t\t# String, we have to escape \\0, \\t, \\n, \\r, everything else can\n\t\t# be prefixed with a slash and the slash just gets dropped\n\t\tstring: (\n\t\t\t'\"' $saw_string\t\t\t\t->start\t\t\t|\n\t\t\t[\\n] ${curline++; *strp++=fc;}\t->string\t\t|\n\t\t\t[\\\\]\t\t\t\t\t\t\t->str_escape\t|\n\t\t\t[^\"\\n\\\\] ${*strp++=fc;}\t\t\t->string\n\t\t),\n\t\tstr_escape: (\n\t\t\t\"0\"\t${*strp++=0;}\t\t-> string |\n\t\t\t\"t\"\t${*strp++='\\t';}\t-> string |\n\t\t\t\"n\"\t${*strp++='\\n';}\t-> string |\n\t\t\t\"r\"\t${*strp++='\\r';}\t-> string |\n\t\t\t[^0tnr]\t${*strp++=fc;}\t-> string\n\t\t),\n\n\t\t# A sign can optiionally prefix a number\n\t\tsign: (\n\t\t\t'-' ${sign = -1;}\t->number |\n\t\t\t'+' ${sign = 1;}\t->number\n\t\t),\n\t\tnumber: (\n\t\t\tdigit ${number *= 10; number += fc - '0';}\t->number\t\t\t|\n\t\t\t'.'\t${floating = number; dec_pos = 10;}\t\t->fractional_part\t|\n\t\t\t[\\n] ${curline++;} $saw_int\t\t\t\t\t->start\t\t\t\t|\n\t\t\t[^0-9.]\t$saw_int\t\t\t\t\t\t\t->start\n\t\t),\n\n\n\t\t# When we don't know yet if this is going to be a date or a number\n\t\t# this is the state\n\t\tnumber_or_date: (\n\t\t\tdigit ${number *= 10; number += fc - '0';}\t->number_or_date\t|\n\t\t\t'-'\t${tm.tm_year = number - 1900;}\t\t\t->date\t\t\t\t|\n\t\t\t'.'\t${floating = number * sign; dec_pos = 10;}\t\t\t->fractional_part\t|\n\t\t\t[\\n] ${curline++;} $saw_int\t\t\t\t\t\t\t\t->start\t|\n\t\t\t[\\t ,\\]] $saw_int\t\t\t\t\t\t\t\t\t\t->start\n\t\t),\n\n\n\t\t# Fractional part of a double\n\t\tfractional_part: (\n\t\t\t[0-9] \t$float_add_place\t->fractional_part |\n\t\t\t[^0-9] $saw_float\t\t\t->start\n\t\t),\n\n\t\t# Zulu date, we've already picked up the first four digits and the '-'\n\t\t# when figuring this was a date and not a number\n\t\tdate: (\n\t\t\tdigit{2} @{tm.tm_mon = atoi(fpc-1) - 1;}\n\t\t\t'-'\n\t\t\tdigit{2} @{tm.tm_mday = atoi(fpc-1);}\n\t\t\t'T'\n\t\t\tdigit{2} @{tm.tm_hour = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_min = atoi(fpc-1);}\n\t\t\t':'\n\t\t\tdigit{2} @{tm.tm_sec = atoi(fpc-1);}\n\t\t\t'Z' @saw_date ->start\n\t\t),\n\n\t\t# Non-list value\n\t\tsingular: (\n\t\t\t'true'\t@{number = 1;}\t\t\t\t-> true\t\t|\n\t\t\t'false'\t@{number = 0;}\t\t\t\t-> false\t|\n\t\t\t'\"' ${strp = string;}\t\t\t\t-> string\t|\n\t\t\t('-'|'+') ${fhold;number = 0;}\t\t-> sign\t\t|\n\t\t\tdigit ${sign = 1;fhold;number = 0;}\t-> number_or_date\n\t\t),\n\n\t\t# A list of values\n\t\tlist: (\n\t\t\t'#'\t\t\t\t\t\t\t\t->comment\t|\n\t\t\t'\\n' ${ curline++; }\t\t\t->list\t\t|\n\t\t\t[\\t ]\t\t\t\t\t\t\t->list\t\t|\n\t\t\t','\t\t\t\t\t\t\t\t->val\t\t|\n\t\t\t']'\t$end_list\t\t\t\t\t->start\t\t|\n\t\t\t[^#\\t, \\n\\]] ${fhold;}\t\t\t->val\n\t\t),\n\n\t\t# A val can be either a list or a singular value\n\t\tval: (\n\t\t\t'#'\t\t\t\t\t\t\t->comment\t|\n\t\t\t'\\n' ${ curline++; }\t\t->val\t\t|\n\t\t\t[\\t ]\t\t\t\t\t\t->val\t\t|\n\t\t\t'[' $start_list\t\t\t\t->list\t\t|\n\t\t\t']'\t$end_list\t\t\t\t->start\t\t|\n\t\t\t[^#\\t \\n[\\]] ${fhold;}\t\t->singular\n\t\t)\n\n\t\t# A regular key\n\t\tkey: (\n\t\t\tname whitespace >{namelen = (int)(p-ts);} '=' $saw_key ->val\n\t\t),\n\n\t\t# Text stripped of leading whitespace\n\t\ttext: (\n\t\t\t'#'\t\t\t\t\t\t\t->comment\t|\n\t\t\t'['\t\t\t\t\t\t\t->keygroup\t|\n\t\t\t[\\t ]\t\t\t\t\t\t->text\t\t|\n\t\t\t'\\n' ${curline++;}\t\t\t->start |\n\t\t\t']' $end_list\t\t\t\t->start\t\t|\n\t\t\t[^#[\\t \\n,\\]]\t${fhold;}\t->key\n\t\t)\n\t);\n\n\tmain := lines?;\n}%%\n\n%%write data;\n\nint\ntoml_parse(struct toml_node *toml_root, char *buf, int buflen)\n{\n\tint indent = 0, cs, curline = 1;\n\tchar *p, *pe;\n\tchar *ts;\n\tchar string[1024], *strp;\n\tint sign, number, dec_pos, namelen;\n\tstruct tm tm;\n\tdouble floating;\n\tchar *name;\n\tint parse_error = 0, malloc_error = 0;\n\n\tstruct toml_node *cur_keygroup = toml_root;\n\n\tstruct list_head list_stack;\n\tlist_head_init(&list_stack);\n\n\tassert(toml_root->type == TOML_ROOT);\n\n\t%% write init;\n\n\tp = buf;\n\tpe = buf + buflen;\n\n\t%% write exec;\n\n\tif (malloc_error) {\n\t\tfprintf(stderr, \"malloc failed, line %d\\n\", curline);\n\t\treturn 1;\n\t}\n\n\tif (cs == toml_error || parse_error) {\n\t\tfprintf(stderr, \"PARSE_ERROR, line %d, p = '%.5s'\", curline, p);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"539c695d5a4e3c8f748c0bbc1fa621e5376ed91d","subject":"Fixed reseting byte accumulator in pack Bb.","message":"Fixed reseting byte accumulator in pack Bb.\n","repos":"rubinius\/rapa","old_file":"actions\/rubinius\/pack_code.rl","new_file":"actions\/rubinius\/pack_code.rl","new_contents":"\/* This file was generated by Ragel. Your edits will be lost.\n *\n * This is a state machine implementation of Array#pack.\n *\n * vim: filetype=cpp\n *\/\n\n#include \"vm\/config.h\"\n\n#include \"vm.hpp\"\n#include \"object_utils.hpp\"\n#include \"on_stack.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n\nnamespace rubinius {\n namespace pack {\n static Object* integer(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, call_frame, state->symbol(\"pack_to_int\"), args);\n }\n\n static String* string_or_nil(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n Object* result = G(rubinius)->send(state, call_frame,\n state->symbol(\"pack_to_str_or_nil\"), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n static String* string(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n Object* result = G(rubinius)->send(state, call_frame,\n state->symbol(\"pack_to_s\"), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n typedef String* (*EncodingCoerce)(STATE, CallFrame*, Object*);\n\n inline static String* encoding_string(STATE, CallFrame* call_frame, Object* obj,\n EncodingCoerce coerce)\n {\n String* s = try_as(obj);\n if(s) return s;\n\n return coerce(state, call_frame, obj);\n }\n\n static Object* float_t(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, call_frame, state->symbol(\"pack_to_float\"), args);\n }\n\n inline uint16_t swap16(uint16_t x) {\n return (((x & 0x00ff)<<8) | ((x & 0xff00)>>8));\n }\n\n inline uint32_t swap32(uint32_t x) {\n return (((x & 0x000000ff) << 24)\n |((x & 0xff000000) >> 24)\n |((x & 0x0000ff00) << 8)\n |((x & 0x00ff0000) >> 8));\n }\n\n inline uint64_t swap64(uint64_t x) {\n return (((x & 0x00000000000000ffLL) << 56)\n |((x & 0xff00000000000000LL) >> 56)\n |((x & 0x000000000000ff00LL) << 40)\n |((x & 0x00ff000000000000LL) >> 40)\n |((x & 0x0000000000ff0000LL) << 24)\n |((x & 0x0000ff0000000000LL) >> 24)\n |((x & 0x00000000ff000000LL) << 8)\n |((x & 0x000000ff00000000LL) >> 8));\n }\n\n inline static void swapf(std::string& str, float value) {\n uint32_t x;\n\n memcpy(&x, &value, sizeof(float));\n x = swap32(x);\n\n str.append((const char*)&x, sizeof(uint32_t));\n }\n\n inline static void swapd(std::string& str, double value) {\n uint64_t x;\n\n memcpy(&x, &value, sizeof(double));\n x = swap64(x);\n\n str.append((const char*)&x, sizeof(uint64_t));\n }\n\n inline static void double_element(std::string& str, double value) {\n str.append((const char*)&value, sizeof(double));\n }\n\n inline static void float_element(std::string& str, float value) {\n str.append((const char*)&value, sizeof(float));\n }\n\n#define QUOTABLE_PRINTABLE_BUFSIZE 1024\n\n static void quotable_printable(String* s, std::string& str, int count) {\n static char hex_table[] = \"0123456789ABCDEF\";\n char buf[QUOTABLE_PRINTABLE_BUFSIZE];\n\n uint8_t* b = s->byte_address();\n uint8_t* e = b + s->size();\n int i = 0, n = 0, prev = -1;\n\n for(; b < e; b++) {\n if((*b > 126) || (*b < 32 && *b != '\\n' && *b != '\\t') || (*b == '=')) {\n buf[i++] = '=';\n buf[i++] = hex_table[*b >> 4];\n buf[i++] = hex_table[*b & 0x0f];\n n += 3;\n prev = -1;\n } else if(*b == '\\n') {\n if(prev == ' ' || prev == '\\t') {\n buf[i++] = '=';\n buf[i++] = *b;\n }\n buf[i++] = *b;\n n = 0;\n prev = *b;\n } else {\n buf[i++] = *b;\n n++;\n prev = *b;\n }\n\n if(n > count) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n n = 0;\n prev = '\\n';\n }\n\n if(i > QUOTABLE_PRINTABLE_BUFSIZE - 5) {\n str.append(buf, i);\n i = 0;\n }\n }\n\n if(n > 0) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n }\n\n if(i > 0) {\n str.append(buf, i);\n }\n }\n\n inline static size_t bit_extra(String* s, bool rest, size_t& count) {\n size_t extra = 0;\n\n if(rest) {\n count = s->size();\n } else {\n size_t size = s->size();\n if(count > size) {\n extra = (count - size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n static void bit_high(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n byte |= *b & 1;\n if(i & 7) {\n byte <<= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if (count & 7) {\n byte <<= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n static void bit_low(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n if(*b & 1)\n byte |= 128;\n\n if(i & 7) {\n byte >>= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte >>= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n inline static size_t hex_extra(String* s, bool rest, size_t& count) {\n size_t extra = 0;\n\n if(rest) {\n count = s->size();\n } else {\n size_t size = s->size();\n if(count > size) {\n extra = (count + 1) \/ 2 - (size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n static void hex_high(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= ((*b & 15) + 9) & 15;\n } else {\n byte |= *b & 15;\n }\n\n if(i & 1) {\n byte <<= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n static void hex_low(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= (((*b & 15) + 9) & 15) << 4;\n } else {\n byte |= (*b & 15) << 4;\n }\n\n if(i & 1) {\n byte >>= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n }\n\n#define BITS_LONG (RBX_SIZEOF_LONG * 8)\n#define BITS_64 (64)\n\n#define CONVERT_INTEGER(T, v, m, b, n) \\\n if((n)->fixnum_p()) { \\\n v = (T)STRIP_FIXNUM_TAG(n); \\\n } else { \\\n Bignum* big = as(n); \\\n big->verify_size(state, b); \\\n v = big->m(); \\\n }\n\n#define CONVERT_TO_INT(n) CONVERT_INTEGER(int, int_value, to_int, BITS_LONG, n)\n#define CONVERT_TO_LONG(n) CONVERT_INTEGER(long long, long_value, to_long_long, BITS_64, n)\n\n#define PACK_INT_ELEMENTS(mask) PACK_ELEMENTS(Integer, pack::integer, INT, mask)\n#define PACK_LONG_ELEMENTS(mask) PACK_ELEMENTS(Integer, pack::integer, LONG, mask)\n\n#define pack_float_elements(format) pack_elements(Float, pack::float_t, format)\n\n#define pack_double_le pack_float_elements(pack_double_element_le)\n#define pack_double_be pack_float_elements(pack_double_element_be)\n\n#define pack_float_le pack_float_elements(pack_float_element_le)\n#define pack_float_be pack_float_elements(pack_float_element_be)\n\n#define pack_elements(T, coerce, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, call_frame, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n format(value); \\\n }\n\n#define PACK_ELEMENTS(T, coerce, size, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, call_frame, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n CONVERT_TO_ ## size(value); \\\n format; \\\n }\n\n#define PACK_STRING_ELEMENT(coerce) { \\\n Object* item = self->get(state, index); \\\n String* value = try_as(item); \\\n if(!value) { \\\n value = coerce(state, call_frame, item); \\\n if(!value) return 0; \\\n } \\\n if(RTEST(value->tainted_p(state))) tainted = true; \\\n size_t size = value->size(); \\\n if(rest) count = size; \\\n if(count <= size) { \\\n str.append((const char*)value->byte_address(), count); \\\n count = 0; \\\n } else { \\\n str.append((const char*)value->byte_address(), size); \\\n count = count - size; \\\n } \\\n index++; \\\n}\n\n#define BYTE1(x) (((x) & 0x00000000000000ff))\n#define BYTE2(x) (((x) & 0x000000000000ff00) >> 8)\n#define BYTE3(x) (((x) & 0x0000000000ff0000) >> 16)\n#define BYTE4(x) (((x) & 0x00000000ff000000) >> 24)\n\n#define BYTE5(x) (((x) & 0x000000ff00000000LL) >> 32)\n#define BYTE6(x) (((x) & 0x0000ff0000000000LL) >> 40)\n#define BYTE7(x) (((x) & 0x00ff000000000000LL) >> 48)\n#define BYTE8(x) (((x) & 0xff00000000000000LL) >> 56)\n\n#ifdef RBX_LITTLE_ENDIAN\n# define MASK_16BITS LE_MASK_16BITS\n# define MASK_32BITS LE_MASK_32BITS\n# define MASK_64BITS LE_MASK_64BITS\n\n# define pack_double_element_le(v) (pack::double_element(str, (v)->val))\n# define pack_double_element_be(v) (pack::swapd(str, (v)->val))\n# define pack_double pack_double_le\n\n# define pack_float_element_le(v) (pack::float_element(str, (v)->val))\n# define pack_float_element_be(v) (pack::swapf(str, (v)->val))\n# define pack_float pack_float_le\n#else\n# define MASK_16BITS BE_MASK_16BITS\n# define MASK_32BITS BE_MASK_32BITS\n# define MASK_64BITS BE_MASK_64BITS\n\n# define pack_double_element_le(v) (pack::swapd(str, (v)->val))\n# define pack_double_element_be(v) (pack::double_element(str, (v)->val))\n# define pack_double pack_double_be\n\n# define pack_float_element_le(v) (pack::swapf(str, (v)->val))\n# define pack_float_element_be(v) (pack::float_element(str, (v)->val))\n# define pack_float pack_float_be\n#endif\n\n#define LE_MASK_64BITS \\\n str.push_back(BYTE1(long_value)); \\\n str.push_back(BYTE2(long_value)); \\\n str.push_back(BYTE3(long_value)); \\\n str.push_back(BYTE4(long_value)); \\\n str.push_back(BYTE5(long_value)); \\\n str.push_back(BYTE6(long_value)); \\\n str.push_back(BYTE7(long_value)); \\\n str.push_back(BYTE8(long_value)); \\\n\n#define BE_MASK_64BITS \\\n str.push_back(BYTE8(long_value)); \\\n str.push_back(BYTE7(long_value)); \\\n str.push_back(BYTE6(long_value)); \\\n str.push_back(BYTE5(long_value)); \\\n str.push_back(BYTE4(long_value)); \\\n str.push_back(BYTE3(long_value)); \\\n str.push_back(BYTE2(long_value)); \\\n str.push_back(BYTE1(long_value)); \\\n\n#define LE_MASK_32BITS \\\n str.push_back(BYTE1(int_value)); \\\n str.push_back(BYTE2(int_value)); \\\n str.push_back(BYTE3(int_value)); \\\n str.push_back(BYTE4(int_value)); \\\n\n#define BE_MASK_32BITS \\\n str.push_back(BYTE4(int_value)); \\\n str.push_back(BYTE3(int_value)); \\\n str.push_back(BYTE2(int_value)); \\\n str.push_back(BYTE1(int_value)); \\\n\n#define LE_MASK_16BITS \\\n str.push_back(BYTE1(int_value)); \\\n str.push_back(BYTE2(int_value)); \\\n\n#define BE_MASK_16BITS \\\n str.push_back(BYTE2(int_value)); \\\n str.push_back(BYTE1(int_value)); \\\n\n#define MASK_BYTE \\\n str.push_back(BYTE1(int_value));\n\n String* Array::pack(STATE, String* directives, CallFrame* call_frame) {\n \/\/ Ragel-specific variables\n std::string d(directives->c_str(), directives->size());\n const char *p = d.c_str();\n const char *pe = p + d.size();\n const char *eof = pe;\n int cs;\n\n \/\/ pack-specific variables\n Array* self = this;\n OnStack<1> sv(state, self);\n\n size_t index = 0;\n size_t count = 0;\n size_t stop = 0;\n bool rest = false;\n bool platform = false;\n bool tainted = false;\n\n int int_value = 0;\n long long long_value = 0;\n std::string str(\"\");\n\n \/\/ Use information we have to reduce repeated allocation.\n str.reserve(size() * 4);\n\n%%{\n\n machine pack;\n\n include \"pack.rl\";\n\n}%%\n\n if(pack_first_final && pack_error && pack_en_main) {\n \/\/ do nothing\n }\n\n return force_as(Primitives::failure());\n }\n}\n","old_contents":"\/* This file was generated by Ragel. Your edits will be lost.\n *\n * This is a state machine implementation of Array#pack.\n *\n * vim: filetype=cpp\n *\/\n\n#include \"vm\/config.h\"\n\n#include \"vm.hpp\"\n#include \"object_utils.hpp\"\n#include \"on_stack.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n\nnamespace rubinius {\n namespace pack {\n static Object* integer(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, call_frame, state->symbol(\"pack_to_int\"), args);\n }\n\n static String* string_or_nil(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n Object* result = G(rubinius)->send(state, call_frame,\n state->symbol(\"pack_to_str_or_nil\"), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n static String* string(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n Object* result = G(rubinius)->send(state, call_frame,\n state->symbol(\"pack_to_s\"), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n typedef String* (*EncodingCoerce)(STATE, CallFrame*, Object*);\n\n inline static String* encoding_string(STATE, CallFrame* call_frame, Object* obj,\n EncodingCoerce coerce)\n {\n String* s = try_as(obj);\n if(s) return s;\n\n return coerce(state, call_frame, obj);\n }\n\n static Object* float_t(STATE, CallFrame* call_frame, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, call_frame, state->symbol(\"pack_to_float\"), args);\n }\n\n inline uint16_t swap16(uint16_t x) {\n return (((x & 0x00ff)<<8) | ((x & 0xff00)>>8));\n }\n\n inline uint32_t swap32(uint32_t x) {\n return (((x & 0x000000ff) << 24)\n |((x & 0xff000000) >> 24)\n |((x & 0x0000ff00) << 8)\n |((x & 0x00ff0000) >> 8));\n }\n\n inline uint64_t swap64(uint64_t x) {\n return (((x & 0x00000000000000ffLL) << 56)\n |((x & 0xff00000000000000LL) >> 56)\n |((x & 0x000000000000ff00LL) << 40)\n |((x & 0x00ff000000000000LL) >> 40)\n |((x & 0x0000000000ff0000LL) << 24)\n |((x & 0x0000ff0000000000LL) >> 24)\n |((x & 0x00000000ff000000LL) << 8)\n |((x & 0x000000ff00000000LL) >> 8));\n }\n\n inline static void swapf(std::string& str, float value) {\n uint32_t x;\n\n memcpy(&x, &value, sizeof(float));\n x = swap32(x);\n\n str.append((const char*)&x, sizeof(uint32_t));\n }\n\n inline static void swapd(std::string& str, double value) {\n uint64_t x;\n\n memcpy(&x, &value, sizeof(double));\n x = swap64(x);\n\n str.append((const char*)&x, sizeof(uint64_t));\n }\n\n inline static void double_element(std::string& str, double value) {\n str.append((const char*)&value, sizeof(double));\n }\n\n inline static void float_element(std::string& str, float value) {\n str.append((const char*)&value, sizeof(float));\n }\n\n#define QUOTABLE_PRINTABLE_BUFSIZE 1024\n\n static void quotable_printable(String* s, std::string& str, int count) {\n static char hex_table[] = \"0123456789ABCDEF\";\n char buf[QUOTABLE_PRINTABLE_BUFSIZE];\n\n uint8_t* b = s->byte_address();\n uint8_t* e = b + s->size();\n int i = 0, n = 0, prev = -1;\n\n for(; b < e; b++) {\n if((*b > 126) || (*b < 32 && *b != '\\n' && *b != '\\t') || (*b == '=')) {\n buf[i++] = '=';\n buf[i++] = hex_table[*b >> 4];\n buf[i++] = hex_table[*b & 0x0f];\n n += 3;\n prev = -1;\n } else if(*b == '\\n') {\n if(prev == ' ' || prev == '\\t') {\n buf[i++] = '=';\n buf[i++] = *b;\n }\n buf[i++] = *b;\n n = 0;\n prev = *b;\n } else {\n buf[i++] = *b;\n n++;\n prev = *b;\n }\n\n if(n > count) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n n = 0;\n prev = '\\n';\n }\n\n if(i > QUOTABLE_PRINTABLE_BUFSIZE - 5) {\n str.append(buf, i);\n i = 0;\n }\n }\n\n if(n > 0) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n }\n\n if(i > 0) {\n str.append(buf, i);\n }\n }\n\n inline static size_t bit_extra(String* s, bool rest, size_t& count) {\n size_t extra = 0;\n\n if(rest) {\n count = s->size();\n } else {\n size_t size = s->size();\n if(count > size) {\n extra = (count - size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n static void bit_high(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n byte |= *b & 1;\n if(i & 7) {\n byte <<= 1;\n } else {\n str.push_back(byte & 0xff);\n }\n }\n\n if (count & 7) {\n byte <<= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n static void bit_low(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n if(*b & 1)\n byte |= 128;\n\n if(i & 7) {\n byte >>= 1;\n } else {\n str.push_back(byte & 0xff);\n }\n }\n\n if(count & 7) {\n byte >>= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n inline static size_t hex_extra(String* s, bool rest, size_t& count) {\n size_t extra = 0;\n\n if(rest) {\n count = s->size();\n } else {\n size_t size = s->size();\n if(count > size) {\n extra = (count + 1) \/ 2 - (size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n static void hex_high(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= ((*b & 15) + 9) & 15;\n } else {\n byte |= *b & 15;\n }\n\n if(i & 1) {\n byte <<= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n static void hex_low(String* s, std::string& str, size_t count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(size_t i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= (((*b & 15) + 9) & 15) << 4;\n } else {\n byte |= (*b & 15) << 4;\n }\n\n if(i & 1) {\n byte >>= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n }\n\n#define BITS_LONG (RBX_SIZEOF_LONG * 8)\n#define BITS_64 (64)\n\n#define CONVERT_INTEGER(T, v, m, b, n) \\\n if((n)->fixnum_p()) { \\\n v = (T)STRIP_FIXNUM_TAG(n); \\\n } else { \\\n Bignum* big = as(n); \\\n big->verify_size(state, b); \\\n v = big->m(); \\\n }\n\n#define CONVERT_TO_INT(n) CONVERT_INTEGER(int, int_value, to_int, BITS_LONG, n)\n#define CONVERT_TO_LONG(n) CONVERT_INTEGER(long long, long_value, to_long_long, BITS_64, n)\n\n#define PACK_INT_ELEMENTS(mask) PACK_ELEMENTS(Integer, pack::integer, INT, mask)\n#define PACK_LONG_ELEMENTS(mask) PACK_ELEMENTS(Integer, pack::integer, LONG, mask)\n\n#define pack_float_elements(format) pack_elements(Float, pack::float_t, format)\n\n#define pack_double_le pack_float_elements(pack_double_element_le)\n#define pack_double_be pack_float_elements(pack_double_element_be)\n\n#define pack_float_le pack_float_elements(pack_float_element_le)\n#define pack_float_be pack_float_elements(pack_float_element_be)\n\n#define pack_elements(T, coerce, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, call_frame, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n format(value); \\\n }\n\n#define PACK_ELEMENTS(T, coerce, size, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, call_frame, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n CONVERT_TO_ ## size(value); \\\n format; \\\n }\n\n#define PACK_STRING_ELEMENT(coerce) { \\\n Object* item = self->get(state, index); \\\n String* value = try_as(item); \\\n if(!value) { \\\n value = coerce(state, call_frame, item); \\\n if(!value) return 0; \\\n } \\\n if(RTEST(value->tainted_p(state))) tainted = true; \\\n size_t size = value->size(); \\\n if(rest) count = size; \\\n if(count <= size) { \\\n str.append((const char*)value->byte_address(), count); \\\n count = 0; \\\n } else { \\\n str.append((const char*)value->byte_address(), size); \\\n count = count - size; \\\n } \\\n index++; \\\n}\n\n#define BYTE1(x) (((x) & 0x00000000000000ff))\n#define BYTE2(x) (((x) & 0x000000000000ff00) >> 8)\n#define BYTE3(x) (((x) & 0x0000000000ff0000) >> 16)\n#define BYTE4(x) (((x) & 0x00000000ff000000) >> 24)\n\n#define BYTE5(x) (((x) & 0x000000ff00000000LL) >> 32)\n#define BYTE6(x) (((x) & 0x0000ff0000000000LL) >> 40)\n#define BYTE7(x) (((x) & 0x00ff000000000000LL) >> 48)\n#define BYTE8(x) (((x) & 0xff00000000000000LL) >> 56)\n\n#ifdef RBX_LITTLE_ENDIAN\n# define MASK_16BITS LE_MASK_16BITS\n# define MASK_32BITS LE_MASK_32BITS\n# define MASK_64BITS LE_MASK_64BITS\n\n# define pack_double_element_le(v) (pack::double_element(str, (v)->val))\n# define pack_double_element_be(v) (pack::swapd(str, (v)->val))\n# define pack_double pack_double_le\n\n# define pack_float_element_le(v) (pack::float_element(str, (v)->val))\n# define pack_float_element_be(v) (pack::swapf(str, (v)->val))\n# define pack_float pack_float_le\n#else\n# define MASK_16BITS BE_MASK_16BITS\n# define MASK_32BITS BE_MASK_32BITS\n# define MASK_64BITS BE_MASK_64BITS\n\n# define pack_double_element_le(v) (pack::swapd(str, (v)->val))\n# define pack_double_element_be(v) (pack::double_element(str, (v)->val))\n# define pack_double pack_double_be\n\n# define pack_float_element_le(v) (pack::swapf(str, (v)->val))\n# define pack_float_element_be(v) (pack::float_element(str, (v)->val))\n# define pack_float pack_float_be\n#endif\n\n#define LE_MASK_64BITS \\\n str.push_back(BYTE1(long_value)); \\\n str.push_back(BYTE2(long_value)); \\\n str.push_back(BYTE3(long_value)); \\\n str.push_back(BYTE4(long_value)); \\\n str.push_back(BYTE5(long_value)); \\\n str.push_back(BYTE6(long_value)); \\\n str.push_back(BYTE7(long_value)); \\\n str.push_back(BYTE8(long_value)); \\\n\n#define BE_MASK_64BITS \\\n str.push_back(BYTE8(long_value)); \\\n str.push_back(BYTE7(long_value)); \\\n str.push_back(BYTE6(long_value)); \\\n str.push_back(BYTE5(long_value)); \\\n str.push_back(BYTE4(long_value)); \\\n str.push_back(BYTE3(long_value)); \\\n str.push_back(BYTE2(long_value)); \\\n str.push_back(BYTE1(long_value)); \\\n\n#define LE_MASK_32BITS \\\n str.push_back(BYTE1(int_value)); \\\n str.push_back(BYTE2(int_value)); \\\n str.push_back(BYTE3(int_value)); \\\n str.push_back(BYTE4(int_value)); \\\n\n#define BE_MASK_32BITS \\\n str.push_back(BYTE4(int_value)); \\\n str.push_back(BYTE3(int_value)); \\\n str.push_back(BYTE2(int_value)); \\\n str.push_back(BYTE1(int_value)); \\\n\n#define LE_MASK_16BITS \\\n str.push_back(BYTE1(int_value)); \\\n str.push_back(BYTE2(int_value)); \\\n\n#define BE_MASK_16BITS \\\n str.push_back(BYTE2(int_value)); \\\n str.push_back(BYTE1(int_value)); \\\n\n#define MASK_BYTE \\\n str.push_back(BYTE1(int_value));\n\n String* Array::pack(STATE, String* directives, CallFrame* call_frame) {\n \/\/ Ragel-specific variables\n std::string d(directives->c_str(), directives->size());\n const char *p = d.c_str();\n const char *pe = p + d.size();\n const char *eof = pe;\n int cs;\n\n \/\/ pack-specific variables\n Array* self = this;\n OnStack<1> sv(state, self);\n\n size_t index = 0;\n size_t count = 0;\n size_t stop = 0;\n bool rest = false;\n bool platform = false;\n bool tainted = false;\n\n int int_value = 0;\n long long long_value = 0;\n std::string str(\"\");\n\n \/\/ Use information we have to reduce repeated allocation.\n str.reserve(size() * 4);\n\n%%{\n\n machine pack;\n\n include \"pack.rl\";\n\n}%%\n\n if(pack_first_final && pack_error && pack_en_main) {\n \/\/ do nothing\n }\n\n return force_as(Primitives::failure());\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"eaf64a2f4ecc3e800ece38b8923c164b80783d4e","subject":"add comments on the files purpose","message":"add comments on the files purpose\n","repos":"modulexcite\/dns,letsencrypt\/dns,jmhodges\/dns,tonnerre\/golang-dns,tsenart\/dns,curtiszimmerman\/dns,josephyzhou\/dns,skynet\/dns,janstk\/dns,hugozhu\/dns,asergeyev\/dns,michaelharo\/dns,rolandshoemaker\/dns,Git-Host\/dns,AlexCheong\/dns,bragr\/dns,FiloSottile\/dns,Psiphon-Inc\/dns,miekg\/dns,jdef\/dns,ezoic\/dns,ym\/go-dns,cloudflare\/dns,benbearchen\/dns,flebarbe\/dns,skyportsystems\/dns,bboreham\/dns,ErikDubbelboer\/dns,tempbottle\/dns","old_file":"kparse.rl","new_file":"kparse.rl","new_contents":"# parse priv key files an' stuff\n","old_contents":"","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"32606af0a93f2caa3742a5e71b9fbaa225c84bc0","subject":"Clear out the path before assigning to it.","message":"Clear out the path before assigning to it.\n\nChange-Id: I5ce91b6d46bf789c5dd13e7bcc92091a29e1e0cf\nReviewed-on: https:\/\/gerrit.dechocorp.com\/7008\nReviewed-by: Jeremy Stanley <8cc48e55af0ea00a29d3ccf3190022dccfb4961b@decho.com>\n","repos":"ccutrer\/mordor,adfin\/mordor,mtanski\/mordor,cgaebel\/mordor,adfin\/mordor,cgaebel\/mordor,ccutrer\/mordor,mozy\/mordor,ccutrer\/mordor,adfin\/mordor,mozy\/mordor,mtanski\/mordor,mozy\/mordor,mtanski\/mordor","old_file":"mordor\/uri.rl","new_file":"mordor\/uri.rl","new_contents":"\/\/ Copyright (c) 2009 - Mozy, Inc.\n\/* To compile to .cpp:\n ragel uri.rl -G2 -o uri.cpp\n*\/\n\n#include \"mordor\/pch.h\"\n\n#include \"mordor\/uri.h\"\n\n#include \n\n#include \"mordor\/ragel.h\"\n#include \"mordor\/string.h\"\n#include \"mordor\/version.h\"\n\nnamespace Mordor {\n\nstatic const std::string unreserved(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\");\nstatic const std::string sub_delims(\"!$&'()*+,;=\");\nstatic const std::string scheme(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.\");\nstatic const std::string userinfo(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string host(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string pchar(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\");\nstatic const std::string path(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/\");\nstatic const std::string segment_nc(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \"@\");\nstatic const std::string query(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/?\");\nstatic const std::string queryString(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$'()*+,\" \":@\" \"\/?\");\n\nstatic std::string escape(const std::string& str, const std::string& allowedChars, bool spaceAsPlus = false)\n{\n const char *hexdigits = \"0123456789ABCDEF\";\n std::string result(str);\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while(c < end)\n {\n if (allowedChars.find(*c) == std::string::npos) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n if (*c == ' ' && spaceAsPlus) {\n result.append(1, '+');\n } else {\n result.append(1, '%');\n result.append(1, hexdigits[(unsigned char)*c >> 4]);\n result.append(1, hexdigits[*c & 0xf]);\n }\n } else {\n if (differed) {\n result.append(1, *c);\n }\n }\n ++c;\n }\n\n if (differed) {\n MORDOR_ASSERT(result.length() >= str.length());\n } else {\n MORDOR_ASSERT(result == str);\n }\n return result;\n}\n\nstd::string unescape(const std::string& str, bool spaceAsPlus = false)\n{\n std::string result = str;\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while (c < end)\n {\n if (*c == '%') {\n MORDOR_ASSERT(c + 2 < end);\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n char decoded;\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded = (*c - 'a' + 10) << 4;\n else if (*c >= 'A' && *c <= 'F')\n decoded = (*c - 'A' + 10) << 4;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded = (*c - '0') << 4;\n }\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded |= *c - 'a' + 10;\n else if (*c >= 'A' && *c <= 'F')\n decoded |= *c - 'A' + 10;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded |= *c - '0';\n }\n result.append(1, decoded);\n } else if (*c == '+' && spaceAsPlus) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n result.append(1, ' ');\n } else if (differed) {\n result.append(1, *c);\n }\n ++c;\n }\n return result;\n}\n\nstd::string\nURI::encode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return escape(str, unreserved, false);\n case QUERYSTRING:\n return escape(str, Mordor::queryString, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\nstd::string\nURI::decode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return unescape(str, false);\n case QUERYSTRING:\n return unescape(str, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\n%%{\n # See RFC 3986: http:\/\/www.ietf.org\/rfc\/rfc3986.txt\n\n machine uri_parser;\n\n gen_delims = \":\" | \"\/\" | \"?\" | \"#\" | \"[\" | \"]\" | \"@\";\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\" | \"=\";\n reserved = gen_delims | sub_delims;\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n\n action marku { mark = fpc; }\n action save_scheme\n {\n m_uri->scheme(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n scheme = (alpha | digit | \"+\" | \"-\" | \".\")+ >marku %save_scheme;\n\n action save_port\n {\n if (fpc == mark)\n m_uri->authority.port(-1);\n else\n m_uri->authority.port(atoi(mark));\n mark = NULL;\n }\n action save_userinfo\n {\n m_uri->authority.userinfo(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n action save_host\n {\n if (mark != NULL) {\n m_uri->authority.host(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n }\n\n userinfo = (unreserved | pct_encoded | sub_delims | \":\")*;\n dec_octet = digit | [1-9] digit | \"1\" digit{2} | 2 [0-4] digit | \"25\" [0-5];\n IPv4address = dec_octet \".\" dec_octet \".\" dec_octet \".\" dec_octet;\n h16 = xdigit{1,4};\n ls32 = (h16 \":\" h16) | IPv4address;\n IPv6address = ( (h16 \":\"){6} ls32) |\n ( \"::\" (h16 \":\"){5} ls32) |\n (( h16)? \"::\" (h16 \":\"){4} ls32) |\n (((h16 \":\"){1} h16)? \"::\" (h16 \":\"){3} ls32) |\n (((h16 \":\"){2} h16)? \"::\" (h16 \":\"){2} ls32) |\n (((h16 \":\"){3} h16)? \"::\" (h16 \":\"){1} ls32) |\n (((h16 \":\"){4} h16)? \"::\" ls32) |\n (((h16 \":\"){5} h16)? \"::\" h16 ) |\n (((h16 \":\"){6} h16)? \"::\" );\n IPvFuture = \"v\" xdigit+ \".\" (unreserved | sub_delims | \":\")+;\n IP_literal = \"[\" (IPv6address | IPvFuture) \"]\";\n reg_name = (unreserved | pct_encoded | sub_delims)*;\n host = IP_literal | IPv4address | reg_name;\n port = digit*;\n\n authority = ( (userinfo %save_userinfo \"@\")? host >marku %save_host (\":\" port >marku %save_port)? ) >marku;\n\n action save_segment\n {\n m_path->segments.push_back(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n segment = pchar* >marku %save_segment;\n segment_nz = pchar+ >marku %save_segment;\n segment_nz_nc = (pchar - \":\")+ >marku %save_segment;\n\n action set_absolute\n {\n m_path->type = URI::Path::ABSOLUTE;\n }\n action set_relative\n {\n m_path->type = URI::Path::RELATIVE;\n }\n\n path_abempty = (\"\/\" segment >set_absolute)*;\n path_absolute = \"\/\" (segment_nz (\"\/\" segment)*)? >set_absolute;\n path_noscheme = segment_nz_nc >set_relative (\"\/\" segment)*;\n path_rootless = segment_nz >set_relative (\"\/\" segment)*;\n path_empty = \"\" %set_relative;\n path = (path_abempty | path_absolute | path_noscheme | path_rootless | path_empty);\n\n action save_query\n {\n m_uri->m_query = std::string(mark, fpc - mark);\n m_uri->m_queryDefined = true;\n mark = NULL;\n }\n action save_fragment\n {\n m_uri->fragment(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n query = (pchar | \"\/\" | \"?\")* >marku %save_query;\n fragment = (pchar | \"\/\" | \"?\")* >marku %save_fragment;\n\n hier_part = (\"\/\/\" authority path_abempty) | path_absolute | path_rootless | path_empty;\n\n relative_part = (\"\/\/\" authority path_abempty) | path_absolute | path_noscheme | path_empty;\n relative_ref = relative_part ( \"?\" query )? ( \"#\" fragment )?;\n\n absolute_URI = scheme \":\" hier_part ( \"?\" query )? ;\n # Obsolete, but referenced from HTTP, so we translate\n relative_URI = relative_part ( \"?\" query )?;\n\n URI = scheme \":\" hier_part ( \"?\" query )? ( \"#\" fragment )?;\n URI_reference = URI | relative_ref;\n}%%\n\n%%{\n machine uri_parser_proper;\n include uri_parser;\n main := URI_reference;\n write data;\n}%%\n\nclass URIParser : public RagelParser\n{\npublic:\n URIParser(URI& uri)\n {\n m_uri = &uri;\n m_path = &m_uri->path;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_parser_proper_first_final;\n }\n\n bool error() const\n {\n return cs == uri_parser_proper_error;\n }\n\nprivate:\n URI *m_uri;\n URI::Path *m_path;\n};\n\n%%{\n machine uri_path_parser;\n include uri_parser;\n main := path;\n write data;\n}%%\nclass URIPathParser : public RagelParser\n{\npublic:\n URIPathParser(URI::Path& path)\n {\n m_path = &path;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_path_parser_first_final;\n }\n\n bool error() const\n {\n return cs == uri_path_parser_error;\n }\n\nprivate:\n URI::Path *m_path;\n};\n\nURI::URI()\n{\n reset();\n}\n\nURI::URI(const std::string& uri)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const char *uri)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const Buffer &uri)\n{\n reset();\n *this = uri;\n}\n\nURI&\nURI::operator=(const std::string& uri)\n{\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n throw std::invalid_argument(\"uri\");\n return *this;\n}\n\nURI&\nURI::operator=(const Buffer &uri)\n{\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n throw std::invalid_argument(\"uri\");\n return *this;\n}\n\nvoid\nURI::reset()\n{\n schemeDefined(false);\n authority.hostDefined(false);\n path.type = Path::RELATIVE;\n path.segments.clear();\n queryDefined(false);\n fragmentDefined(false);\n}\n\nURI::Authority::Authority()\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n}\n\nvoid\nURI::Authority::normalize(const std::string& defaultHost, bool emptyHostValid,\n int defaultPort, bool emptyPortValid)\n{\n for(size_t i = 0; i < m_host.length(); ++i)\n m_host[i] = tolower(m_host[i]);\n if (m_port == defaultPort)\n m_port = -1;\n if (m_port == -1 && !emptyPortValid)\n m_portDefined = false;\n if (m_host == defaultHost)\n m_host.clear();\n if (m_host.empty() && !emptyHostValid && !m_userinfoDefined && !m_portDefined)\n m_hostDefined = false;\n}\n\nstd::string\nURI::Authority::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\n\nstd::string\nURI::Path::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstatic int boolcmp(bool lhs, bool rhs)\n{\n if (!lhs && rhs)\n return -1;\n if (lhs && !rhs)\n return 1;\n return 0;\n}\n\nint\nURI::Authority::cmp(const Authority &rhs) const\n{\n int x = boolcmp(m_hostDefined, rhs.m_hostDefined);\n if (x != 0) return x;\n x = strcmp(m_host.c_str(), rhs.m_host.c_str());\n if (x != 0) return x;\n x = boolcmp(m_portDefined, rhs.m_portDefined);\n if (x != 0) return x;\n x = m_port - rhs.m_port;\n if (x != 0) return x;\n x = boolcmp(m_userinfoDefined, rhs.m_userinfoDefined);\n if (x != 0) return x;\n return strcmp(m_userinfo.c_str(), rhs.m_userinfo.c_str());\n}\n\nbool\nURI::Authority::operator==(const Authority &rhs) const\n{\n return cmp(rhs) == 0;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Authority& authority)\n{\n MORDOR_ASSERT(authority.hostDefined());\n if (authority.userinfoDefined()) {\n os << escape(authority.userinfo(), userinfo) << \"@\";\n }\n os << escape(authority.host(), host);\n if (authority.portDefined()) {\n os << \":\";\n if (authority.port() > 0) {\n os << authority.port();\n }\n }\n return os;\n}\n\nURI::Path::Path()\n{\n type = RELATIVE;\n}\n\nURI::Path::Path(const char *path)\n{\n *this = path;\n}\n\nURI::Path::Path(const std::string& path)\n{\n *this = path;\n}\n\nURI::Path&\nURI::Path::operator=(const std::string& path)\n{\n type = RELATIVE;\n\tsegments.clear();\n URIPathParser parser(*this);\n parser.run(path);\n if (parser.error() || !parser.final())\n throw std::invalid_argument(\"uri\");\n return *this;\n}\n\nvoid\nURI::Path::removeDotComponents()\n{\n for(size_t i = 0; i < segments.size(); ++i) {\n if (segments[i] == \".\") {\n if (i + 1 == segments.size()) {\n segments[i].clear();\n continue;\n } else {\n segments.erase(segments.begin() + i);\n --i;\n continue;\n }\n }\n if (segments[i] == \"..\") {\n if (i == 0) {\n segments.erase(segments.begin());\n --i;\n continue;\n }\n if (i + 1 == segments.size()) {\n segments.resize(segments.size() - 1);\n segments.back().clear();\n --i;\n continue;\n }\n segments.erase(segments.begin() + i - 1, segments.begin() + i + 1);\n i -= 2;\n continue;\n }\n }\n}\n\nvoid\nURI::Path::normalize(bool emptyPathValid)\n{\n removeDotComponents();\n if (segments.empty() && !emptyPathValid)\n type = ABSOLUTE;\n}\n\nvoid\nURI::Path::merge(const Path& rhs)\n{\n MORDOR_ASSERT(rhs.type == RELATIVE);\n if (!segments.empty()) {\n segments.pop_back();\n segments.insert(segments.end(), rhs.segments.begin(), rhs.segments.end());\n } else {\n segments = rhs.segments;\n }\n}\n\nURI::Path::path_serializer\nURI::Path::serialize(bool schemeless) const\n{\n path_serializer result;\n result.p = this;\n result.schemeless = schemeless;\n return result;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path::path_serializer &p)\n{\n if (p.p->segments.empty() && p.p->type == URI::Path::ABSOLUTE) {\n return os << \"\/\";\n }\n for (size_t i = 0; i < p.p->segments.size(); ++i) {\n if (i != 0 || p.p->type == URI::Path::ABSOLUTE) {\n os << \"\/\";\n }\n if (i == 0 && p.p->type == URI::Path::RELATIVE && p.schemeless) {\n os << escape(p.p->segments[i], segment_nc);\n } else {\n os << escape(p.p->segments[i], pchar);\n }\n }\n return os;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path& path)\n{\n return os << path.serialize();\n}\n\nint\nURI::Path::cmp(const Path &rhs) const\n{\n if (type == ABSOLUTE && rhs.type == RELATIVE)\n return -1;\n if (type == RELATIVE && rhs.type == ABSOLUTE)\n return 1;\n std::vector::const_iterator itl, itr;\n itl = segments.begin(); itr = rhs.segments.begin();\n while (true) {\n if (itl == segments.end() && itr != rhs.segments.end())\n return -1;\n if (itl != segments.end() && itr == rhs.segments.end())\n return 1;\n if (itl == segments.end() && itr == rhs.segments.end())\n return 0;\n int x = strcmp(itl->c_str(), itr->c_str());\n if (x != 0) return x;\n ++itl; ++itr;\n }\n}\n\nbool\nURI::Path::operator==(const Path &rhs) const\n{\n return type == rhs.type && segments == rhs.segments;\n}\n\nvoid\nURI::normalize()\n{\n for (size_t i = 0; i < m_scheme.size(); ++i)\n m_scheme[i] = tolower(m_scheme[i]);\n\n if (m_scheme == \"http\" || m_scheme == \"https\") {\n authority.normalize(\"\", false, m_scheme.size() == 4 ? 80 : 443, false);\n path.normalize();\n } else if (m_scheme == \"file\") {\n authority.normalize(\"localhost\", true);\n path.normalize();\n } else {\n authority.normalize();\n path.normalize();\n }\n}\n\nstd::string\nURI::query() const\n{\n MORDOR_ASSERT(m_queryDefined);\n return unescape(m_query);\n}\n\nvoid\nURI::query(const std::string &q)\n{\n m_queryDefined = true;\n m_query = escape(q, Mordor::query);\n}\n\nstd::string\nURI::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI& uri)\n{\n if (uri.schemeDefined()) {\n os << escape(uri.scheme(), scheme) << \":\";\n }\n\n if (uri.authority.hostDefined()) {\n os << \"\/\/\" << uri.authority;\n }\n\n \/\/ Has scheme, but no authority, must ensure that an absolute path\n \/\/ doesn't begin with an empty segment (or could be mistaken for authority)\n if (uri.schemeDefined() && !uri.authority.hostDefined() &&\n uri.path.type == URI::Path::ABSOLUTE &&\n uri.path.segments.size() > 0 && uri.path.segments.front().empty()) {\n os << \"\/\";\n }\n os << uri.path.serialize(!uri.schemeDefined());\n\n if (uri.queryDefined()) {\n os << \"?\" << escape(uri.query(), query);\n }\n\n if (uri.fragmentDefined()) {\n os << \"#\" << escape(uri.fragment(), query);\n }\n return os;\n}\n\nURI\nURI::transform(const URI& base, const URI& relative)\n{\n MORDOR_ASSERT(base.schemeDefined());\n\n URI target;\n if (relative.schemeDefined()) {\n target.scheme(relative.scheme());\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.authority.hostDefined()) {\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.path.isEmpty()) {\n target.path = base.path;\n if (relative.queryDefined()) {\n target.query(relative.query());\n } else {\n target.m_query = base.m_query;\n target.m_queryDefined = base.m_queryDefined;\n }\n } else {\n if (relative.path.type == Path::ABSOLUTE) {\n target.path = relative.path;\n } else {\n target.path = base.path;\n target.path.merge(relative.path);\n if (!base.authority.hostDefined())\n target.path.type = Path::ABSOLUTE;\n }\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n }\n target.authority = base.authority;\n }\n target.scheme(base.scheme());\n }\n target.m_fragment = relative.m_fragment;\n target.m_fragmentDefined = relative.m_fragmentDefined;\n return target;\n}\n\nint\nURI::cmp(const URI &rhs) const\n{\n int x = boolcmp(m_schemeDefined, rhs.m_schemeDefined);\n if (x != 0) return x;\n x = strcmp(m_scheme.c_str(), rhs.m_scheme.c_str());\n if (x != 0) return x;\n x = authority.cmp(rhs.authority);\n if (x != 0) return x;\n x = path.cmp(rhs.path);\n if (x != 0) return x;\n x = boolcmp(m_queryDefined, rhs.m_queryDefined);\n if (x != 0) return x;\n x = strcmp(m_query.c_str(), rhs.m_query.c_str());\n if (x != 0) return x;\n x = boolcmp(m_fragmentDefined, rhs.m_fragmentDefined);\n if (x != 0) return x;\n return strcmp(m_fragment.c_str(), rhs.m_fragment.c_str());\n}\n\nbool\nURI::operator<(const URI &rhs) const\n{\n return cmp(rhs) < 0;\n}\n\nbool\nURI::operator==(const URI &rhs) const\n{\n return cmp(rhs) == 0;\n}\n\n%%{\n machine querystring_parser;\n\n action mark { mark = fpc; }\n action saveKey {\n m_iterator = m_qs.insert(std::make_pair(\n unescape(std::string(mark, fpc - mark), true), std::string()));\n mark = NULL;\n }\n action saveValue {\n MORDOR_ASSERT(m_iterator != m_qs.end());\n m_iterator->second = unescape(std::string(mark, fpc - mark), true);\n m_iterator = m_qs.end();\n mark = NULL;\n }\n\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\";\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n querychar = (pchar | \"\/\" | \"?\") -- '&' -- ';';\n key = querychar+;\n value = (querychar | '=')+;\n keyValue = key >mark %saveKey ('=' value >mark %saveValue)?;\n main := keyValue? ( ('&' | ';') keyValue? )*;\n write data;\n}%%\n\nclass QueryStringParser : public RagelParser\n{\npublic:\n QueryStringParser(URI::QueryString &qs)\n : m_qs(qs),\n m_iterator(m_qs.end())\n {}\n\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\n bool complete() const { return false; }\n bool final() const\n {\n return cs >= querystring_parser_first_final;\n }\n\n bool error() const\n {\n return cs == querystring_parser_error;\n }\n\nprivate:\n URI::QueryString &m_qs;\n URI::QueryString::iterator m_iterator;\n};\n\nURI::QueryString &\nURI::QueryString::operator =(const std::string &string)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(string);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nURI::QueryString &\nURI::QueryString::operator =(Stream &stream)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(stream);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nstd::string\nURI::QueryString::toString() const\n{\n std::ostringstream os;\n for (const_iterator it = begin();\n it != end();\n ++it) {\n if (it != begin()) {\n os << '&';\n }\n os << escape(it->first, Mordor::queryString, true);\n if (!it->second.empty())\n os << '=' << escape(it->second, Mordor::queryString, true);\n }\n return os.str();\n}\n\n}\n","old_contents":"\/\/ Copyright (c) 2009 - Mozy, Inc.\n\/* To compile to .cpp:\n ragel uri.rl -G2 -o uri.cpp\n*\/\n\n#include \"mordor\/pch.h\"\n\n#include \"mordor\/uri.h\"\n\n#include \n\n#include \"mordor\/ragel.h\"\n#include \"mordor\/string.h\"\n#include \"mordor\/version.h\"\n\nnamespace Mordor {\n\nstatic const std::string unreserved(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\");\nstatic const std::string sub_delims(\"!$&'()*+,;=\");\nstatic const std::string scheme(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.\");\nstatic const std::string userinfo(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string host(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":\");\nstatic const std::string pchar(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\");\nstatic const std::string path(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/\");\nstatic const std::string segment_nc(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \"@\");\nstatic const std::string query(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$&'()*+,;=\" \":@\" \"\/?\");\nstatic const std::string queryString(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\" \"!$'()*+,\" \":@\" \"\/?\");\n\nstatic std::string escape(const std::string& str, const std::string& allowedChars, bool spaceAsPlus = false)\n{\n const char *hexdigits = \"0123456789ABCDEF\";\n std::string result(str);\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while(c < end)\n {\n if (allowedChars.find(*c) == std::string::npos) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n if (*c == ' ' && spaceAsPlus) {\n result.append(1, '+');\n } else {\n result.append(1, '%');\n result.append(1, hexdigits[(unsigned char)*c >> 4]);\n result.append(1, hexdigits[*c & 0xf]);\n }\n } else {\n if (differed) {\n result.append(1, *c);\n }\n }\n ++c;\n }\n\n if (differed) {\n MORDOR_ASSERT(result.length() >= str.length());\n } else {\n MORDOR_ASSERT(result == str);\n }\n return result;\n}\n\nstd::string unescape(const std::string& str, bool spaceAsPlus = false)\n{\n std::string result = str;\n\n const char *c = str.c_str();\n const char *end = c + str.length();\n bool differed = false;\n while (c < end)\n {\n if (*c == '%') {\n MORDOR_ASSERT(c + 2 < end);\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n char decoded;\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded = (*c - 'a' + 10) << 4;\n else if (*c >= 'A' && *c <= 'F')\n decoded = (*c - 'A' + 10) << 4;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded = (*c - '0') << 4;\n }\n ++c;\n if (*c >= 'a' && *c <= 'f')\n decoded |= *c - 'a' + 10;\n else if (*c >= 'A' && *c <= 'F')\n decoded |= *c - 'A' + 10;\n else {\n MORDOR_ASSERT(*c >= '0' && *c <='9');\n decoded |= *c - '0';\n }\n result.append(1, decoded);\n } else if (*c == '+' && spaceAsPlus) {\n if (!differed) {\n result.resize(c - str.c_str());\n differed = true;\n }\n result.append(1, ' ');\n } else if (differed) {\n result.append(1, *c);\n }\n ++c;\n }\n return result;\n}\n\nstd::string\nURI::encode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return escape(str, unreserved, false);\n case QUERYSTRING:\n return escape(str, Mordor::queryString, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\nstd::string\nURI::decode(const std::string &str, CharacterClass charClass)\n{\n switch (charClass) {\n case UNRESERVED:\n return unescape(str, false);\n case QUERYSTRING:\n return unescape(str, true);\n default:\n MORDOR_NOTREACHED();\n }\n}\n\n%%{\n # See RFC 3986: http:\/\/www.ietf.org\/rfc\/rfc3986.txt\n\n machine uri_parser;\n\n gen_delims = \":\" | \"\/\" | \"?\" | \"#\" | \"[\" | \"]\" | \"@\";\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\" | \"=\";\n reserved = gen_delims | sub_delims;\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n\n action marku { mark = fpc; }\n action save_scheme\n {\n m_uri->scheme(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n scheme = (alpha | digit | \"+\" | \"-\" | \".\")+ >marku %save_scheme;\n\n action save_port\n {\n if (fpc == mark)\n m_uri->authority.port(-1);\n else\n m_uri->authority.port(atoi(mark));\n mark = NULL;\n }\n action save_userinfo\n {\n m_uri->authority.userinfo(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n action save_host\n {\n if (mark != NULL) {\n m_uri->authority.host(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n }\n\n userinfo = (unreserved | pct_encoded | sub_delims | \":\")*;\n dec_octet = digit | [1-9] digit | \"1\" digit{2} | 2 [0-4] digit | \"25\" [0-5];\n IPv4address = dec_octet \".\" dec_octet \".\" dec_octet \".\" dec_octet;\n h16 = xdigit{1,4};\n ls32 = (h16 \":\" h16) | IPv4address;\n IPv6address = ( (h16 \":\"){6} ls32) |\n ( \"::\" (h16 \":\"){5} ls32) |\n (( h16)? \"::\" (h16 \":\"){4} ls32) |\n (((h16 \":\"){1} h16)? \"::\" (h16 \":\"){3} ls32) |\n (((h16 \":\"){2} h16)? \"::\" (h16 \":\"){2} ls32) |\n (((h16 \":\"){3} h16)? \"::\" (h16 \":\"){1} ls32) |\n (((h16 \":\"){4} h16)? \"::\" ls32) |\n (((h16 \":\"){5} h16)? \"::\" h16 ) |\n (((h16 \":\"){6} h16)? \"::\" );\n IPvFuture = \"v\" xdigit+ \".\" (unreserved | sub_delims | \":\")+;\n IP_literal = \"[\" (IPv6address | IPvFuture) \"]\";\n reg_name = (unreserved | pct_encoded | sub_delims)*;\n host = IP_literal | IPv4address | reg_name;\n port = digit*;\n\n authority = ( (userinfo %save_userinfo \"@\")? host >marku %save_host (\":\" port >marku %save_port)? ) >marku;\n\n action save_segment\n {\n m_path->segments.push_back(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n segment = pchar* >marku %save_segment;\n segment_nz = pchar+ >marku %save_segment;\n segment_nz_nc = (pchar - \":\")+ >marku %save_segment;\n\n action set_absolute\n {\n m_path->type = URI::Path::ABSOLUTE;\n }\n action set_relative\n {\n m_path->type = URI::Path::RELATIVE;\n }\n\n path_abempty = (\"\/\" segment >set_absolute)*;\n path_absolute = \"\/\" (segment_nz (\"\/\" segment)*)? >set_absolute;\n path_noscheme = segment_nz_nc >set_relative (\"\/\" segment)*;\n path_rootless = segment_nz >set_relative (\"\/\" segment)*;\n path_empty = \"\" %set_relative;\n path = (path_abempty | path_absolute | path_noscheme | path_rootless | path_empty);\n\n action save_query\n {\n m_uri->m_query = std::string(mark, fpc - mark);\n m_uri->m_queryDefined = true;\n mark = NULL;\n }\n action save_fragment\n {\n m_uri->fragment(unescape(std::string(mark, fpc - mark)));\n mark = NULL;\n }\n\n query = (pchar | \"\/\" | \"?\")* >marku %save_query;\n fragment = (pchar | \"\/\" | \"?\")* >marku %save_fragment;\n\n hier_part = (\"\/\/\" authority path_abempty) | path_absolute | path_rootless | path_empty;\n\n relative_part = (\"\/\/\" authority path_abempty) | path_absolute | path_noscheme | path_empty;\n relative_ref = relative_part ( \"?\" query )? ( \"#\" fragment )?;\n\n absolute_URI = scheme \":\" hier_part ( \"?\" query )? ;\n # Obsolete, but referenced from HTTP, so we translate\n relative_URI = relative_part ( \"?\" query )?;\n\n URI = scheme \":\" hier_part ( \"?\" query )? ( \"#\" fragment )?;\n URI_reference = URI | relative_ref;\n}%%\n\n%%{\n machine uri_parser_proper;\n include uri_parser;\n main := URI_reference;\n write data;\n}%%\n\nclass URIParser : public RagelParser\n{\npublic:\n URIParser(URI& uri)\n {\n m_uri = &uri;\n m_path = &m_uri->path;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_parser_proper_first_final;\n }\n\n bool error() const\n {\n return cs == uri_parser_proper_error;\n }\n\nprivate:\n URI *m_uri;\n URI::Path *m_path;\n};\n\n%%{\n machine uri_path_parser;\n include uri_parser;\n main := path;\n write data;\n}%%\nclass URIPathParser : public RagelParser\n{\npublic:\n URIPathParser(URI::Path& path)\n {\n m_path = &path;\n }\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\nprotected:\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\npublic:\n bool complete() const\n {\n return false;\n }\n\n bool final() const\n {\n return cs >= uri_path_parser_first_final;\n }\n\n bool error() const\n {\n return cs == uri_path_parser_error;\n }\n\nprivate:\n URI::Path *m_path;\n};\n\nURI::URI()\n{\n reset();\n}\n\nURI::URI(const std::string& uri)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const char *uri)\n{\n reset();\n *this = uri;\n}\n\nURI::URI(const Buffer &uri)\n{\n reset();\n *this = uri;\n}\n\nURI&\nURI::operator=(const std::string& uri)\n{\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n throw std::invalid_argument(\"uri\");\n return *this;\n}\n\nURI&\nURI::operator=(const Buffer &uri)\n{\n URIParser parser(*this);\n parser.run(uri);\n if (parser.error() || !parser.final())\n throw std::invalid_argument(\"uri\");\n return *this;\n}\n\nvoid\nURI::reset()\n{\n schemeDefined(false);\n authority.hostDefined(false);\n path.type = Path::RELATIVE;\n path.segments.clear();\n queryDefined(false);\n fragmentDefined(false);\n}\n\nURI::Authority::Authority()\n{\n userinfoDefined(false);\n hostDefined(false);\n portDefined(false);\n}\n\nvoid\nURI::Authority::normalize(const std::string& defaultHost, bool emptyHostValid,\n int defaultPort, bool emptyPortValid)\n{\n for(size_t i = 0; i < m_host.length(); ++i)\n m_host[i] = tolower(m_host[i]);\n if (m_port == defaultPort)\n m_port = -1;\n if (m_port == -1 && !emptyPortValid)\n m_portDefined = false;\n if (m_host == defaultHost)\n m_host.clear();\n if (m_host.empty() && !emptyHostValid && !m_userinfoDefined && !m_portDefined)\n m_hostDefined = false;\n}\n\nstd::string\nURI::Authority::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\n\nstd::string\nURI::Path::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstatic int boolcmp(bool lhs, bool rhs)\n{\n if (!lhs && rhs)\n return -1;\n if (lhs && !rhs)\n return 1;\n return 0;\n}\n\nint\nURI::Authority::cmp(const Authority &rhs) const\n{\n int x = boolcmp(m_hostDefined, rhs.m_hostDefined);\n if (x != 0) return x;\n x = strcmp(m_host.c_str(), rhs.m_host.c_str());\n if (x != 0) return x;\n x = boolcmp(m_portDefined, rhs.m_portDefined);\n if (x != 0) return x;\n x = m_port - rhs.m_port;\n if (x != 0) return x;\n x = boolcmp(m_userinfoDefined, rhs.m_userinfoDefined);\n if (x != 0) return x;\n return strcmp(m_userinfo.c_str(), rhs.m_userinfo.c_str());\n}\n\nbool\nURI::Authority::operator==(const Authority &rhs) const\n{\n return cmp(rhs) == 0;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Authority& authority)\n{\n MORDOR_ASSERT(authority.hostDefined());\n if (authority.userinfoDefined()) {\n os << escape(authority.userinfo(), userinfo) << \"@\";\n }\n os << escape(authority.host(), host);\n if (authority.portDefined()) {\n os << \":\";\n if (authority.port() > 0) {\n os << authority.port();\n }\n }\n return os;\n}\n\nURI::Path::Path()\n{\n type = RELATIVE;\n}\n\nURI::Path::Path(const char *path)\n{\n *this = path;\n}\n\nURI::Path::Path(const std::string& path)\n{\n *this = path;\n}\n\nURI::Path&\nURI::Path::operator=(const std::string& path)\n{\n URIPathParser parser(*this);\n parser.run(path);\n if (parser.error() || !parser.final())\n throw std::invalid_argument(\"uri\");\n return *this;\n}\n\nvoid\nURI::Path::removeDotComponents()\n{\n for(size_t i = 0; i < segments.size(); ++i) {\n if (segments[i] == \".\") {\n if (i + 1 == segments.size()) {\n segments[i].clear();\n continue;\n } else {\n segments.erase(segments.begin() + i);\n --i;\n continue;\n }\n }\n if (segments[i] == \"..\") {\n if (i == 0) {\n segments.erase(segments.begin());\n --i;\n continue;\n }\n if (i + 1 == segments.size()) {\n segments.resize(segments.size() - 1);\n segments.back().clear();\n --i;\n continue;\n }\n segments.erase(segments.begin() + i - 1, segments.begin() + i + 1);\n i -= 2;\n continue;\n }\n }\n}\n\nvoid\nURI::Path::normalize(bool emptyPathValid)\n{\n removeDotComponents();\n if (segments.empty() && !emptyPathValid)\n type = ABSOLUTE;\n}\n\nvoid\nURI::Path::merge(const Path& rhs)\n{\n MORDOR_ASSERT(rhs.type == RELATIVE);\n if (!segments.empty()) {\n segments.pop_back();\n segments.insert(segments.end(), rhs.segments.begin(), rhs.segments.end());\n } else {\n segments = rhs.segments;\n }\n}\n\nURI::Path::path_serializer\nURI::Path::serialize(bool schemeless) const\n{\n path_serializer result;\n result.p = this;\n result.schemeless = schemeless;\n return result;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path::path_serializer &p)\n{\n if (p.p->segments.empty() && p.p->type == URI::Path::ABSOLUTE) {\n return os << \"\/\";\n }\n for (size_t i = 0; i < p.p->segments.size(); ++i) {\n if (i != 0 || p.p->type == URI::Path::ABSOLUTE) {\n os << \"\/\";\n }\n if (i == 0 && p.p->type == URI::Path::RELATIVE && p.schemeless) {\n os << escape(p.p->segments[i], segment_nc);\n } else {\n os << escape(p.p->segments[i], pchar);\n }\n }\n return os;\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI::Path& path)\n{\n return os << path.serialize();\n}\n\nint\nURI::Path::cmp(const Path &rhs) const\n{\n if (type == ABSOLUTE && rhs.type == RELATIVE)\n return -1;\n if (type == RELATIVE && rhs.type == ABSOLUTE)\n return 1;\n std::vector::const_iterator itl, itr;\n itl = segments.begin(); itr = rhs.segments.begin();\n while (true) {\n if (itl == segments.end() && itr != rhs.segments.end())\n return -1;\n if (itl != segments.end() && itr == rhs.segments.end())\n return 1;\n if (itl == segments.end() && itr == rhs.segments.end())\n return 0;\n int x = strcmp(itl->c_str(), itr->c_str());\n if (x != 0) return x;\n ++itl; ++itr;\n }\n}\n\nbool\nURI::Path::operator==(const Path &rhs) const\n{\n return type == rhs.type && segments == rhs.segments;\n}\n\nvoid\nURI::normalize()\n{\n for (size_t i = 0; i < m_scheme.size(); ++i)\n m_scheme[i] = tolower(m_scheme[i]);\n\n if (m_scheme == \"http\" || m_scheme == \"https\") {\n authority.normalize(\"\", false, m_scheme.size() == 4 ? 80 : 443, false);\n path.normalize();\n } else if (m_scheme == \"file\") {\n authority.normalize(\"localhost\", true);\n path.normalize();\n } else {\n authority.normalize();\n path.normalize();\n }\n}\n\nstd::string\nURI::query() const\n{\n MORDOR_ASSERT(m_queryDefined);\n return unescape(m_query);\n}\n\nvoid\nURI::query(const std::string &q)\n{\n m_queryDefined = true;\n m_query = escape(q, Mordor::query);\n}\n\nstd::string\nURI::toString() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const URI& uri)\n{\n if (uri.schemeDefined()) {\n os << escape(uri.scheme(), scheme) << \":\";\n }\n\n if (uri.authority.hostDefined()) {\n os << \"\/\/\" << uri.authority;\n }\n\n \/\/ Has scheme, but no authority, must ensure that an absolute path\n \/\/ doesn't begin with an empty segment (or could be mistaken for authority)\n if (uri.schemeDefined() && !uri.authority.hostDefined() &&\n uri.path.type == URI::Path::ABSOLUTE &&\n uri.path.segments.size() > 0 && uri.path.segments.front().empty()) {\n os << \"\/\";\n }\n os << uri.path.serialize(!uri.schemeDefined());\n\n if (uri.queryDefined()) {\n os << \"?\" << escape(uri.query(), query);\n }\n\n if (uri.fragmentDefined()) {\n os << \"#\" << escape(uri.fragment(), query);\n }\n return os;\n}\n\nURI\nURI::transform(const URI& base, const URI& relative)\n{\n MORDOR_ASSERT(base.schemeDefined());\n\n URI target;\n if (relative.schemeDefined()) {\n target.scheme(relative.scheme());\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.authority.hostDefined()) {\n target.authority = relative.authority;\n target.path = relative.path;\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n } else {\n if (relative.path.isEmpty()) {\n target.path = base.path;\n if (relative.queryDefined()) {\n target.query(relative.query());\n } else {\n target.m_query = base.m_query;\n target.m_queryDefined = base.m_queryDefined;\n }\n } else {\n if (relative.path.type == Path::ABSOLUTE) {\n target.path = relative.path;\n } else {\n target.path = base.path;\n target.path.merge(relative.path);\n if (!base.authority.hostDefined())\n target.path.type = Path::ABSOLUTE;\n }\n target.path.removeDotComponents();\n target.m_query = relative.m_query;\n target.m_queryDefined = relative.m_queryDefined;\n }\n target.authority = base.authority;\n }\n target.scheme(base.scheme());\n }\n target.m_fragment = relative.m_fragment;\n target.m_fragmentDefined = relative.m_fragmentDefined;\n return target;\n}\n\nint\nURI::cmp(const URI &rhs) const\n{\n int x = boolcmp(m_schemeDefined, rhs.m_schemeDefined);\n if (x != 0) return x;\n x = strcmp(m_scheme.c_str(), rhs.m_scheme.c_str());\n if (x != 0) return x;\n x = authority.cmp(rhs.authority);\n if (x != 0) return x;\n x = path.cmp(rhs.path);\n if (x != 0) return x;\n x = boolcmp(m_queryDefined, rhs.m_queryDefined);\n if (x != 0) return x;\n x = strcmp(m_query.c_str(), rhs.m_query.c_str());\n if (x != 0) return x;\n x = boolcmp(m_fragmentDefined, rhs.m_fragmentDefined);\n if (x != 0) return x;\n return strcmp(m_fragment.c_str(), rhs.m_fragment.c_str());\n}\n\nbool\nURI::operator<(const URI &rhs) const\n{\n return cmp(rhs) < 0;\n}\n\nbool\nURI::operator==(const URI &rhs) const\n{\n return cmp(rhs) == 0;\n}\n\n%%{\n machine querystring_parser;\n\n action mark { mark = fpc; }\n action saveKey {\n m_iterator = m_qs.insert(std::make_pair(\n unescape(std::string(mark, fpc - mark), true), std::string()));\n mark = NULL;\n }\n action saveValue {\n MORDOR_ASSERT(m_iterator != m_qs.end());\n m_iterator->second = unescape(std::string(mark, fpc - mark), true);\n m_iterator = m_qs.end();\n mark = NULL;\n }\n\n sub_delims = \"!\" | \"$\" | \"&\" | \"'\" | \"(\" | \")\" | \"*\" | \"+\" | \",\" | \";\";\n unreserved = alpha | digit | \"-\" | \".\" | \"_\" | \"~\";\n pct_encoded = \"%\" xdigit xdigit;\n pchar = unreserved | pct_encoded | sub_delims | \":\" | \"@\";\n querychar = (pchar | \"\/\" | \"?\") -- '&' -- ';';\n key = querychar+;\n value = (querychar | '=')+;\n keyValue = key >mark %saveKey ('=' value >mark %saveValue)?;\n main := keyValue? ( ('&' | ';') keyValue? )*;\n write data;\n}%%\n\nclass QueryStringParser : public RagelParser\n{\npublic:\n QueryStringParser(URI::QueryString &qs)\n : m_qs(qs),\n m_iterator(m_qs.end())\n {}\n\n\n void init()\n {\n RagelParser::init();\n %% write init;\n }\n\n void exec()\n {\n#ifdef MSVC\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#endif\n %% write exec;\n#ifdef MSVC\n#pragma warning(pop)\n#endif\n }\n\n bool complete() const { return false; }\n bool final() const\n {\n return cs >= querystring_parser_first_final;\n }\n\n bool error() const\n {\n return cs == querystring_parser_error;\n }\n\nprivate:\n URI::QueryString &m_qs;\n URI::QueryString::iterator m_iterator;\n};\n\nURI::QueryString &\nURI::QueryString::operator =(const std::string &string)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(string);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nURI::QueryString &\nURI::QueryString::operator =(Stream &stream)\n{\n clear();\n QueryStringParser parser(*this);\n parser.run(stream);\n if (!parser.final() || parser.error())\n MORDOR_THROW_EXCEPTION(std::invalid_argument(\"Invalid QueryString\"));\n return *this;\n}\n\nstd::string\nURI::QueryString::toString() const\n{\n std::ostringstream os;\n for (const_iterator it = begin();\n it != end();\n ++it) {\n if (it != begin()) {\n os << '&';\n }\n os << escape(it->first, Mordor::queryString, true);\n if (!it->second.empty())\n os << '=' << escape(it->second, Mordor::queryString, true);\n }\n return os.str();\n}\n\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"6cbea02b73d5488695211e47767c7d4486dda1ec","subject":"Dinstinguish between metalanguage and user language scanner error messages.","message":"Dinstinguish between metalanguage and user language scanner error messages.\n","repos":"timoc\/colm,timoc\/colm,timoc\/colm,timoc\/colm","old_file":"colm\/lmscan.rl","new_file":"colm\/lmscan.rl","new_contents":"\/*\n * Copyright 2006-2007 Adrian Thurston \n *\/\n\n\/* This file is part of Colm.\n *\n * Colm is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Colm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Colm; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"colm.h\"\n#include \"lmscan.h\"\n#include \"lmparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\n\/\/#define PRINT_TOKENS\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid Scanner::sectionParseInit()\n{\n\t%% write init;\n}\n\nostream &Scanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 &&\n\t\t\t\tstrcmp( si->sectionName, inclSectionName ) == 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\t\n}\n\nvoid Scanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = ts;\n\t\/\/cerr << \"adding \" << te - from << \" to column\" << endl;\n\tcolumn += te - from;\n\tlastnl = 0;\n}\n\nvoid Scanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid Scanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\n%%{\n\tmachine section_parse;\n\timport \"lmparse.h\";\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_include\n\t{\n\t\t#if 0\n\t\tchar *inclSectionName = word;\n\t\tchar *inclFileName = 0;\n\n\t\t\/* Implement defaults for the input file and section name. *\/\n\t\tif ( inclSectionName == 0 )\n\t\t\tinclSectionName = parser->sectionName;\n\n\t\tif ( lit != 0 ) \n\t\t\tinclFileName = prepareFileName( lit, lit_len );\n\t\telse\n\t\t\tinclFileName = fileName;\n\n\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t * name then check if what we are including is already in the stack. *\/\n\t\tincludeStack.append( IncludeStackItem( fileName, parser->sectionName ) );\n\n\t\tif ( recursiveInclude( inclFileName, inclSectionName ) )\n\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\t\telse {\n\t\t\t\/* Open the input file for reading. *\/\n\t\t\tifstream *inFile = new ifstream( inclFileName );\n\t\t\tif ( ! inFile->is_open() ) {\n\t\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\t\tinclFileName << \" for reading\" << endl;\n\t\t\t}\n\n\t\t\tScanner scanner( inclFileName, *inFile, output, parser,\n\t\t\t\t\tinclSectionName, includeDepth+1 );\n\t\t\tscanner.do_scan( );\n\t\t\tdelete inFile;\n\t\t}\n\n\t\t\/* Remove the last element (len-1) *\/\n\t\tincludeStack.remove( -1 );\n\t\t#endif\n\t}\n\n\tinclude_target = \n\t\tTK_Literal >clear_words @store_lit;\n\n\tinclude_stmt =\n\t\t( KW_Include include_target ';' ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction handle_token\n\t{\n\t\tInputLoc loc;\n\n\t\t#ifdef PRINT_TOKENS\n\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\tcerr << \" \" << toklen;\n\t\tif ( tokdata != 0 )\n\t\t\tcerr << \" \" << tokdata;\n\t\tcerr << endl;\n\t\t#endif\n\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = column;\n\n\t\tif ( tokdata != 0 && tokdata[toklen-1] == '\\n' )\n\t\t\tloc.line -= 1;\n\n\t\tparser->token( loc, type, tokdata, toklen );\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Include ) @handle_token;\n\n\tmain := ( \n\t\tinclude_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid Scanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\tint *eof = 0;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n}\n\nvoid Scanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t\/* Probably use: token( -1 ); *\/\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( TK_ReChar, '\\0' ); };\n\t\t'\\\\a' => { token( TK_ReChar, '\\a' ); };\n\t\t'\\\\b' => { token( TK_ReChar, '\\b' ); };\n\t\t'\\\\t' => { token( TK_ReChar, '\\t' ); };\n\t\t'\\\\n' => { token( TK_ReChar, '\\n' ); };\n\t\t'\\\\v' => { token( TK_ReChar, '\\v' ); };\n\t\t'\\\\f' => { token( TK_ReChar, '\\f' ); };\n\t\t'\\\\r' => { token( TK_ReChar, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( TK_ReChar, ts+1, te ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( TK_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( TK_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( TK_ReChar, ts, te ); };\n\n\t*|;\n\n\tregular_type := |*\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, ts, te ); };\n\t\thex_number => { token( TK_Hex, ts, te ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, ts, te ); };\n\n\t\t'[' => { token( TK_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( TK_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( '\/'); fret; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\n\t\t':>' => { token( TK_ColonGt ); };\n\t\t':>>' => { token( TK_ColonGtGt ); };\n\t\t'<:' => { token( TK_LtColon ); };\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n\n\tliteral_pattern := |*\n\t\t'\\\\' 'a' { litBuf.append( '\\a' ); };\n\t\t'\\\\' 'b' { litBuf.append( '\\b' ); };\n\t\t'\\\\' 't' { litBuf.append( '\\t' ); };\n\t\t'\\\\' 'n' { litBuf.append( '\\n' ); };\n\t\t'\\\\' 'v' { litBuf.append( '\\v' ); };\n\t\t'\\\\' 'f' { litBuf.append( '\\f' ); };\n\t\t'\\\\' 'r' { litBuf.append( '\\r' ); };\n\n\t\t'\\\\' any {\n\t\t\tlitBuf.append( ts[1] );\n\t\t};\n\t\t'\"' => {\n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\tNL => {\n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\tlitBuf.append( '\\n' );\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\t'[' => { \n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '[' );\n\t\t\tfcall main;\n\t\t};\n\t\tany => { \n\t\t\tlitBuf.append( *ts );\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tmain := |*\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'commit' => { token( KW_Commit ); };\n\t\t'token' => { token( KW_Token ); };\n\t\t'literal' => { token( KW_Literal ); };\n\t\t'rl' => { token( KW_Rl ); };\n\t\t'def' => { token( KW_Def ); };\n\t\t'ignore' => { token( KW_Ignore ); };\n\t\t'construct' => { token( KW_Construct ); };\n\t\t'new' => { token( KW_New ); };\n\t\t'if' => { token( KW_If ); };\n\t\t'reject' => { token( KW_Reject ); };\n\t\t'while' => { token( KW_While ); };\n\t\t'else' => { token( KW_Else ); };\n\t\t'elsif' => { token( KW_Elsif ); };\n\t\t'match' => { token( KW_Match ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'iter' => { token( KW_Iter ); };\n\t\t'print' => { token( KW_Print ); };\n\t\t'print_xml_ac' => { token( KW_PrintXMLAC ); };\n\t\t'print_xml' => { token( KW_PrintXML ); };\n\t\t'namespace' => { token( KW_Namespace ); };\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'map' => { token( KW_Map ); };\n\t\t'list' => { token( KW_List ); };\n\t\t'vector' => { token( KW_Vector ); };\n\t\t'return' => { token( KW_Return ); };\n\t\t'break' => { token( KW_Break ); };\n\t\t'yield' => { token( KW_Yield ); };\n\t\t'typeid' => { token( KW_TypeId ); };\n\t\t'make_token' => { token( KW_MakeToken ); };\n\t\t'make_tree' => { token( KW_MakeTree ); };\n\t\t'reducefirst' => { token( KW_ReduceFirst ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'in' => { token( KW_In ); };\n\t\t'nil' => { token( KW_Nil ); };\n\t\t'true' => { token( KW_True ); };\n\t\t'false' => { token( KW_False ); };\n\t\t'parse' => { token( KW_Parse ); };\n\t\t'parse_stop' => { token( KW_ParseStop ); };\n\t\t'global' => { token( KW_Global ); };\n\t\t'ptr' => { token( KW_Ptr ); };\n\t\t'ref' => { token( KW_Ref ); };\n\t\t'deref' => { token( KW_Deref ); };\n\t\t'require' => { token( KW_Require ); };\n\t\t'preeof' => { token( KW_Preeof ); };\n\t\t'left' => { token( KW_Left ); };\n\t\t'right' => { token( KW_Right ); };\n\t\t'nonassoc' => { token( KW_Nonassoc ); };\n\t\t'prec' => { token( KW_Prec ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\tnumber => { token( TK_Number, ts, te ); };\n\n\t\t'\/' => { \n\t\t\ttoken( '\/' ); \n\t\t\tfcall regular_type;\n\t\t};\n\n\t\t\"~\" [^\\n]* NL => { \n\t\t\ttoken( '\"' );\n\t\t\ttoken( TK_LitPat, ts+1, te );\n\t\t\ttoken( '\"' );\n\t\t};\n\n\t\ts_literal => {\n\t\t\ttoken( TK_Literal, ts, te );\n\t\t};\n\n\t\t'\"' => { \n\t\t\ttoken( '\"' );\n\t\t\tlitBuf.clear(); \n\t\t\tfcall literal_pattern;\n\t\t};\n\t\t'[' => { \n\t\t\ttoken( '[' ); \n\t\t\tfcall main;\n\t\t};\n\n\t\t']' => {\n\t\t\ttoken( ']' );\n\t\t\tif ( top > 0 )\n\t\t\t\tfret;\n\t\t};\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\t\t'==' => { token( TK_DoubleEql ); };\n\t\t'!=' => { token( TK_NotEql ); };\n\t\t'::' => { token( TK_DoubleColon ); };\n\t\t'<=' => { token( TK_LessEql ); };\n\t\t'>=' => { token( TK_GrtrEql ); };\n\t\t'->' => { token( TK_RightArrow ); };\n\t\t'&&' => { token( TK_AmpAmp ); };\n\t\t'||' => { token( TK_BarBar ); };\n\t\t\n\t\t('+' | '-' | '*' | '\/' | '(' | ')' | '@' | '$' ) => { token( *ts ); };\n\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n}%%\n\n%% write data;\n\nvoid Scanner::do_scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[32];\n\tbool execute = true;\n\n\tsectionParseInit();\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( ts != 0 )\n\t\t\t\tts = newbuf + ( ts - buf );\n\t\t\tte = newbuf + ( te - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\tchar *eof = 0;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"colm scanner error (metalanguage)\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = ts;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( ts != 0 )\n\t\t\t\tts -= shiftback;\n\t\t\tte -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\tdelete[] buf;\n\n\tInputLoc loc;\n\tloc.fileName = \"\";\n\tloc.line = line;\n\tloc.col = 1;\n\tparser->token( loc, Parser_tk_eof, 0, 0 );\n}\n\nvoid scan( char *fileName, istream &input, ostream &output )\n{\n\tScanner scanner( fileName, input, output, 0, 0, 0 );\n}\n","old_contents":"\/*\n * Copyright 2006-2007 Adrian Thurston \n *\/\n\n\/* This file is part of Colm.\n *\n * Colm is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * Colm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Colm; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n *\/\n\n#include \n#include \n#include \n\n#include \"colm.h\"\n#include \"lmscan.h\"\n#include \"lmparse.h\"\n#include \"parsedata.h\"\n#include \"avltree.h\"\n#include \"vector.h\"\n\n\/\/#define PRINT_TOKENS\n\nusing std::ifstream;\nusing std::istream;\nusing std::ostream;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n%%{\n\tmachine section_parse;\n\talphtype int;\n\twrite data;\n}%%\n\nvoid Scanner::sectionParseInit()\n{\n\t%% write init;\n}\n\nostream &Scanner::scan_error()\n{\n\t\/* Maintain the error count. *\/\n\tgblErrorCount += 1;\n\tcerr << fileName << \":\" << line << \":\" << column << \": \";\n\treturn cerr;\n}\n\nbool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )\n{\n\tfor ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {\n\t\tif ( strcmp( si->fileName, inclFileName ) == 0 &&\n\t\t\t\tstrcmp( si->sectionName, inclSectionName ) == 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\t\n}\n\nvoid Scanner::updateCol()\n{\n\tchar *from = lastnl;\n\tif ( from == 0 )\n\t\tfrom = ts;\n\t\/\/cerr << \"adding \" << te - from << \" to column\" << endl;\n\tcolumn += te - from;\n\tlastnl = 0;\n}\n\nvoid Scanner::token( int type, char c )\n{\n\ttoken( type, &c, &c + 1 );\n}\n\nvoid Scanner::token( int type )\n{\n\ttoken( type, 0, 0 );\n}\n\n%%{\n\tmachine section_parse;\n\timport \"lmparse.h\";\n\n\taction clear_words { word = lit = 0; word_len = lit_len = 0; }\n\taction store_lit { lit = tokdata; lit_len = toklen; }\n\n\taction mach_err { scan_error() << \"bad machine statement\" << endl; }\n\taction incl_err { scan_error() << \"bad include statement\" << endl; }\n\taction write_err { scan_error() << \"bad write statement\" << endl; }\n\n\taction handle_include\n\t{\n\t\t#if 0\n\t\tchar *inclSectionName = word;\n\t\tchar *inclFileName = 0;\n\n\t\t\/* Implement defaults for the input file and section name. *\/\n\t\tif ( inclSectionName == 0 )\n\t\t\tinclSectionName = parser->sectionName;\n\n\t\tif ( lit != 0 ) \n\t\t\tinclFileName = prepareFileName( lit, lit_len );\n\t\telse\n\t\t\tinclFileName = fileName;\n\n\t\t\/* Check for a recursive include structure. Add the current file\/section\n\t\t * name then check if what we are including is already in the stack. *\/\n\t\tincludeStack.append( IncludeStackItem( fileName, parser->sectionName ) );\n\n\t\tif ( recursiveInclude( inclFileName, inclSectionName ) )\n\t\t\tscan_error() << \"include: this is a recursive include operation\" << endl;\n\t\telse {\n\t\t\t\/* Open the input file for reading. *\/\n\t\t\tifstream *inFile = new ifstream( inclFileName );\n\t\t\tif ( ! inFile->is_open() ) {\n\t\t\t\tscan_error() << \"include: could not open \" << \n\t\t\t\t\t\tinclFileName << \" for reading\" << endl;\n\t\t\t}\n\n\t\t\tScanner scanner( inclFileName, *inFile, output, parser,\n\t\t\t\t\tinclSectionName, includeDepth+1 );\n\t\t\tscanner.do_scan( );\n\t\t\tdelete inFile;\n\t\t}\n\n\t\t\/* Remove the last element (len-1) *\/\n\t\tincludeStack.remove( -1 );\n\t\t#endif\n\t}\n\n\tinclude_target = \n\t\tTK_Literal >clear_words @store_lit;\n\n\tinclude_stmt =\n\t\t( KW_Include include_target ';' ) @handle_include\n\t\t<>err incl_err <>eof incl_err;\n\n\taction handle_token\n\t{\n\t\tInputLoc loc;\n\n\t\t#ifdef PRINT_TOKENS\n\t\tcerr << \"scanner:\" << line << \":\" << column << \n\t\t\t\t\": sending token to the parser \" << Parser_lelNames[*p];\n\t\tcerr << \" \" << toklen;\n\t\tif ( tokdata != 0 )\n\t\t\tcerr << \" \" << tokdata;\n\t\tcerr << endl;\n\t\t#endif\n\n\t\tloc.fileName = fileName;\n\t\tloc.line = line;\n\t\tloc.col = column;\n\n\t\tif ( tokdata != 0 && tokdata[toklen-1] == '\\n' )\n\t\t\tloc.line -= 1;\n\n\t\tparser->token( loc, type, tokdata, toklen );\n\t}\n\n\t# Catch everything else.\n\teverything_else = ^( KW_Include ) @handle_token;\n\n\tmain := ( \n\t\tinclude_stmt |\n\t\teverything_else\n\t)*;\n}%%\n\nvoid Scanner::token( int type, char *start, char *end )\n{\n\tchar *tokdata = 0;\n\tint toklen = 0;\n\tint *p = &type;\n\tint *pe = &type + 1;\n\tint *eof = 0;\n\n\tif ( start != 0 ) {\n\t\ttoklen = end-start;\n\t\ttokdata = new char[toklen+1];\n\t\tmemcpy( tokdata, start, toklen );\n\t\ttokdata[toklen] = 0;\n\t}\n\n\t%%{\n\t\tmachine section_parse;\n\t\twrite exec;\n\t}%%\n\n\tupdateCol();\n}\n\nvoid Scanner::endSection( )\n{\n\t\/* Execute the eof actions for the section parser. *\/\n\t\/* Probably use: token( -1 ); *\/\n}\n\n%%{\n\tmachine rlscan;\n\n\t# This is sent by the driver code.\n\tEOF = 0;\n\t\n\taction inc_nl { \n\t\tlastnl = p; \n\t\tcolumn = 0;\n\t\tline++;\n\t}\n\tNL = '\\n' @inc_nl;\n\n\t# Identifiers, numbers, commetns, and other common things.\n\tident = ( alpha | '_' ) ( alpha |digit |'_' )*;\n\tnumber = digit+;\n\thex_number = '0x' [0-9a-fA-F]+;\n\n\t# These literal forms are common to C-like host code and ragel.\n\ts_literal = \"'\" ([^'\\\\] | NL | '\\\\' (any | NL))* \"'\";\n\td_literal = '\"' ([^\"\\\\] | NL | '\\\\' (any | NL))* '\"';\n\n\twhitespace = [ \\t] | NL;\n\tpound_comment = '#' [^\\n]* NL;\n\n\tor_literal := |*\n\t\t# Escape sequences in OR expressions.\n\t\t'\\\\0' => { token( TK_ReChar, '\\0' ); };\n\t\t'\\\\a' => { token( TK_ReChar, '\\a' ); };\n\t\t'\\\\b' => { token( TK_ReChar, '\\b' ); };\n\t\t'\\\\t' => { token( TK_ReChar, '\\t' ); };\n\t\t'\\\\n' => { token( TK_ReChar, '\\n' ); };\n\t\t'\\\\v' => { token( TK_ReChar, '\\v' ); };\n\t\t'\\\\f' => { token( TK_ReChar, '\\f' ); };\n\t\t'\\\\r' => { token( TK_ReChar, '\\r' ); };\n\t\t'\\\\\\n' => { updateCol(); };\n\t\t'\\\\' any => { token( TK_ReChar, ts+1, te ); };\n\n\t\t# Range dash in an OR expression.\n\t\t'-' => { token( TK_Dash, 0, 0 ); };\n\n\t\t# Terminate an OR expression.\n\t\t']'\t=> { token( TK_SqClose ); fret; };\n\n\t\tEOF => {\n\t\t\tscan_error() << \"unterminated OR literal\" << endl;\n\t\t};\n\n\t\t# Characters in an OR expression.\n\t\t[^\\]] => { token( TK_ReChar, ts, te ); };\n\n\t*|;\n\n\tregular_type := |*\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\t# Numbers\n\t\tnumber => { token( TK_UInt, ts, te ); };\n\t\thex_number => { token( TK_Hex, ts, te ); };\n\n\t\t# Literals, with optionals.\n\t\t( s_literal | d_literal ) [i]? \n\t\t\t=> { token( TK_Literal, ts, te ); };\n\n\t\t'[' => { token( TK_SqOpen ); fcall or_literal; };\n\t\t'[^' => { token( TK_SqOpenNeg ); fcall or_literal; };\n\n\t\t'\/' => { token( '\/'); fret; };\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'..' => { token( TK_DotDot ); };\n\t\t'**' => { token( TK_StarStar ); };\n\t\t'--' => { token( TK_DashDash ); };\n\n\t\t':>' => { token( TK_ColonGt ); };\n\t\t':>>' => { token( TK_ColonGtGt ); };\n\t\t'<:' => { token( TK_LtColon ); };\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\n\t\t# If we are in a single line machine then newline may end the spec.\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n\n\tliteral_pattern := |*\n\t\t'\\\\' 'a' { litBuf.append( '\\a' ); };\n\t\t'\\\\' 'b' { litBuf.append( '\\b' ); };\n\t\t'\\\\' 't' { litBuf.append( '\\t' ); };\n\t\t'\\\\' 'n' { litBuf.append( '\\n' ); };\n\t\t'\\\\' 'v' { litBuf.append( '\\v' ); };\n\t\t'\\\\' 'f' { litBuf.append( '\\f' ); };\n\t\t'\\\\' 'r' { litBuf.append( '\\r' ); };\n\n\t\t'\\\\' any {\n\t\t\tlitBuf.append( ts[1] );\n\t\t};\n\t\t'\"' => {\n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\tNL => {\n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\tlitBuf.append( '\\n' );\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '\"' );\n\t\t\tfret;\n\t\t};\n\t\t'[' => { \n\t\t\tif ( litBuf.length > 0 ) {\n\t\t\t\ttoken( TK_LitPat, litBuf.data, litBuf.data+litBuf.length );\n\t\t\t\tlitBuf.clear();\n\t\t\t}\n\t\t\ttoken( '[' );\n\t\t\tfcall main;\n\t\t};\n\t\tany => { \n\t\t\tlitBuf.append( *ts );\n\t\t};\n\t*|;\n\n\t# Parser definitions. \n\tmain := |*\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'commit' => { token( KW_Commit ); };\n\t\t'token' => { token( KW_Token ); };\n\t\t'literal' => { token( KW_Literal ); };\n\t\t'rl' => { token( KW_Rl ); };\n\t\t'def' => { token( KW_Def ); };\n\t\t'ignore' => { token( KW_Ignore ); };\n\t\t'construct' => { token( KW_Construct ); };\n\t\t'new' => { token( KW_New ); };\n\t\t'if' => { token( KW_If ); };\n\t\t'reject' => { token( KW_Reject ); };\n\t\t'while' => { token( KW_While ); };\n\t\t'else' => { token( KW_Else ); };\n\t\t'elsif' => { token( KW_Elsif ); };\n\t\t'match' => { token( KW_Match ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'iter' => { token( KW_Iter ); };\n\t\t'print' => { token( KW_Print ); };\n\t\t'print_xml_ac' => { token( KW_PrintXMLAC ); };\n\t\t'print_xml' => { token( KW_PrintXML ); };\n\t\t'namespace' => { token( KW_Namespace ); };\n\t\t'lex' => { token( KW_Lex ); };\n\t\t'map' => { token( KW_Map ); };\n\t\t'list' => { token( KW_List ); };\n\t\t'vector' => { token( KW_Vector ); };\n\t\t'return' => { token( KW_Return ); };\n\t\t'break' => { token( KW_Break ); };\n\t\t'yield' => { token( KW_Yield ); };\n\t\t'typeid' => { token( KW_TypeId ); };\n\t\t'make_token' => { token( KW_MakeToken ); };\n\t\t'make_tree' => { token( KW_MakeTree ); };\n\t\t'reducefirst' => { token( KW_ReduceFirst ); };\n\t\t'for' => { token( KW_For ); };\n\t\t'in' => { token( KW_In ); };\n\t\t'nil' => { token( KW_Nil ); };\n\t\t'true' => { token( KW_True ); };\n\t\t'false' => { token( KW_False ); };\n\t\t'parse' => { token( KW_Parse ); };\n\t\t'parse_stop' => { token( KW_ParseStop ); };\n\t\t'global' => { token( KW_Global ); };\n\t\t'ptr' => { token( KW_Ptr ); };\n\t\t'ref' => { token( KW_Ref ); };\n\t\t'deref' => { token( KW_Deref ); };\n\t\t'require' => { token( KW_Require ); };\n\t\t'preeof' => { token( KW_Preeof ); };\n\t\t'left' => { token( KW_Left ); };\n\t\t'right' => { token( KW_Right ); };\n\t\t'nonassoc' => { token( KW_Nonassoc ); };\n\t\t'prec' => { token( KW_Prec ); };\n\n\t\t# Identifiers.\n\t\tident => { token( TK_Word, ts, te ); } ;\n\n\t\tnumber => { token( TK_Number, ts, te ); };\n\n\t\t'\/' => { \n\t\t\ttoken( '\/' ); \n\t\t\tfcall regular_type;\n\t\t};\n\n\t\t\"~\" [^\\n]* NL => { \n\t\t\ttoken( '\"' );\n\t\t\ttoken( TK_LitPat, ts+1, te );\n\t\t\ttoken( '\"' );\n\t\t};\n\n\t\ts_literal => {\n\t\t\ttoken( TK_Literal, ts, te );\n\t\t};\n\n\t\t'\"' => { \n\t\t\ttoken( '\"' );\n\t\t\tlitBuf.clear(); \n\t\t\tfcall literal_pattern;\n\t\t};\n\t\t'[' => { \n\t\t\ttoken( '[' ); \n\t\t\tfcall main;\n\t\t};\n\n\t\t']' => {\n\t\t\ttoken( ']' );\n\t\t\tif ( top > 0 )\n\t\t\t\tfret;\n\t\t};\n\n\t\t# Ignore.\n\t\tpound_comment => { updateCol(); };\n\n\t\t'=>' => { token( TK_DoubleArrow ); };\n\t\t'==' => { token( TK_DoubleEql ); };\n\t\t'!=' => { token( TK_NotEql ); };\n\t\t'::' => { token( TK_DoubleColon ); };\n\t\t'<=' => { token( TK_LessEql ); };\n\t\t'>=' => { token( TK_GrtrEql ); };\n\t\t'->' => { token( TK_RightArrow ); };\n\t\t'&&' => { token( TK_AmpAmp ); };\n\t\t'||' => { token( TK_BarBar ); };\n\t\t\n\t\t('+' | '-' | '*' | '\/' | '(' | ')' | '@' | '$' ) => { token( *ts ); };\n\n\n\t\t# Whitespace other than newline.\n\t\t[ \\t\\r]+ => { updateCol(); };\n\t\tNL => { updateCol(); };\n\n\t\t# Consume eof.\n\t\tEOF;\n\n\t\tany => { token( *ts ); } ;\n\t*|;\n}%%\n\n%% write data;\n\nvoid Scanner::do_scan()\n{\n\tint bufsize = 8;\n\tchar *buf = new char[bufsize];\n\tconst char last_char = 0;\n\tint cs, act, have = 0;\n\tint top, stack[32];\n\tbool execute = true;\n\n\tsectionParseInit();\n\t%% write init;\n\n\twhile ( execute ) {\n\t\tchar *p = buf + have;\n\t\tint space = bufsize - have;\n\n\t\tif ( space == 0 ) {\n\t\t\t\/* We filled up the buffer trying to scan a token. Grow it. *\/\n\t\t\tbufsize = bufsize * 2;\n\t\t\tchar *newbuf = new char[bufsize];\n\n\t\t\t\/* Recompute p and space. *\/\n\t\t\tp = newbuf + have;\n\t\t\tspace = bufsize - have;\n\n\t\t\t\/* Patch up pointers possibly in use. *\/\n\t\t\tif ( ts != 0 )\n\t\t\t\tts = newbuf + ( ts - buf );\n\t\t\tte = newbuf + ( te - buf );\n\n\t\t\t\/* Copy the new buffer in. *\/\n\t\t\tmemcpy( newbuf, buf, have );\n\t\t\tdelete[] buf;\n\t\t\tbuf = newbuf;\n\t\t}\n\n\t\tinput.read( p, space );\n\t\tint len = input.gcount();\n\n\t\t\/* If we see eof then append the EOF char. *\/\n\t \tif ( len == 0 ) {\n\t\t\tp[0] = last_char, len = 1;\n\t\t\texecute = false;\n\t\t}\n\n\t\tchar *pe = p + len;\n\t\tchar *eof = 0;\n\t\t%% write exec;\n\n\t\t\/* Check if we failed. *\/\n\t\tif ( cs == rlscan_error ) {\n\t\t\t\/* Machine failed before finding a token. I'm not yet sure if this\n\t\t\t * is reachable. *\/\n\t\t\tscan_error() << \"scanner error\" << endl;\n\t\t\texit(1);\n\t\t}\n\n\t\t\/* Decide if we need to preserve anything. *\/\n\t\tchar *preserve = ts;\n\n\t\t\/* Now set up the prefix. *\/\n\t\tif ( preserve == 0 )\n\t\t\thave = 0;\n\t\telse {\n\t\t\t\/* There is data that needs to be shifted over. *\/\n\t\t\thave = pe - preserve;\n\t\t\tmemmove( buf, preserve, have );\n\t\t\tunsigned int shiftback = preserve - buf;\n\t\t\tif ( ts != 0 )\n\t\t\t\tts -= shiftback;\n\t\t\tte -= shiftback;\n\n\t\t\tpreserve = buf;\n\t\t}\n\t}\n\tdelete[] buf;\n\n\tInputLoc loc;\n\tloc.fileName = \"\";\n\tloc.line = line;\n\tloc.col = 1;\n\tparser->token( loc, Parser_tk_eof, 0, 0 );\n}\n\nvoid scan( char *fileName, istream &input, ostream &output )\n{\n\tScanner scanner( fileName, input, output, 0, 0, 0 );\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"f87091b6f58f8650b587741e9d9f0f9679d44f52","subject":"Fixed anonymous selectors","message":"Fixed anonymous selectors\n","repos":"fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil,fjolnir\/Tranquil,fjolnir\/Tranquil,gabrielPeart\/Tranquil","old_file":"Source\/Tranquil\/lex.rl","new_file":"Source\/Tranquil\/lex.rl","new_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")* \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new]\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = [NSError errorWithDomain:kTQSyntaxErrorDomain\n code:kTQGenericError\n userInfo:[NSDictionary dictionaryWithObject:[e reason] forKey:@\"reason\"]];\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","old_contents":"#include \"parse.h\"\n#include \n#include \n#include \n#include \n#import \n\ntypedef struct {\n int currentLine;\n BOOL atBeginningOfExpr;\n TQNodeRootBlock *root;\n} TQParserState;\n\n#define NSStr(lTrim, rTrim) (ts ? [[[NSMutableString alloc] initWithBytes:ts+(lTrim) length:te-ts-(lTrim)-(rTrim) encoding:NSUTF8StringEncoding] autorelease] : nil)\n\n#define CopyCStr() ((unsigned char *)strndup((char *)ts, te-ts))\n\n#define _EmitToken(tokenId, val) do { \\\n \/*NSLog(@\"emitting %d = %@ on line: %d\", tokenId, val, parserState.currentLine);*\/ \\\n Parse(parser, tokenId, [TQToken withId:tokenId value:val line:parserState.currentLine], &parserState); \\\n parserState.atBeginningOfExpr = NO; \\\n} while(0);\n\n#define EmitToken(tokenId) EmitStringToken((tokenId), 0, 0)\n\n#define EmitStringToken(tokenId, lTrim, rTrim) _EmitToken(tokenId, NSStr(lTrim, rTrim))\n\n#define EmitConstStringToken(tokenId, lTrim, rTrim) do { \\\n BOOL hasQuotes = *(ts+1) == '\"'; \\\n EmitStringToken((tokenId), lTrim+1+hasQuotes, rTrim+hasQuotes); \\\n} while(0)\n\n#define EmitIntToken(tokenId, base, prefixLen) do { \\\n unsigned char *str = CopyCStr(); \\\n long long numVal = strtoll((char *)str + (prefixLen), NULL, (base)); \\\n _EmitToken((tokenId), [NSNumber numberWithLongLong:numVal]); \\\n free(str); \\\n} while(0)\n\n#define EmitFloatToken(tokenId) do { \\\n unsigned char *str = CopyCStr(); \\\n _EmitToken((tokenId), [NSNumber numberWithDouble:atof((char *)str)]); \\\n free(str); \\\n} while(0)\n\n#define IncrementLine() (++parserState.currentLine)\n\n#define BacktrackTerm() do { \\\n if(*p == '}') \\\n --p; \\\n for(unsigned char *cursor = ts; cursor != te; ++cursor) { \\\n if(*cursor == '\\n') \\\n IncrementLine(); \\\n } \\\n} while(0)\n\n#define ExprBeg() parserState.atBeginningOfExpr = YES\n\n@interface TQToken : NSObject\n@property(readwrite, assign) int id, line;\n@property(readwrite, strong) id value;\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line;\n@end\n@implementation TQToken\n+ (TQToken *)withId:(int)id value:(id)value line:(int)line\n{\n TQToken *ret = [self new];\n ret.id = id;\n ret.value = value;\n ret.line = line;\n return [ret autorelease];\n}\n@end\n\n%%{\n machine Tranquil;\n alphtype unsigned char;\n include WChar \"utf8.rl\";\n\n int = udigit+;\n float = (udigit+)? '.' udigit+;\n hex = \"0x\"i xdigit+;\n bin = \"0b\"i [0-1]+;\n oct = \"0o\"i [0-7]+;\n anybase = udigit+ \"r\"i ([0-9]|[a-zA-Z])+;\n\n char = ualnum | '?' | '!' | '_';\n constant = '_'* uupper char*;\n identifier = '_'* ulower char*;\n comment = '\\\\' [^\\n]*;\n nl = ((space|comment)* '\\n' space*);\n whitespace = (nl|space|comment);\n whitespaceNoNl = (\" \"|\"\\t\"|comment);\n term = whitespace* (nl|\"}\");\n\n lGuillmt = 0xC2 0xAB; # \u00ab\n rGuillmt = 0xC2 0xBB; # \u00bb\n\n strCont = (ualnum | ascii) - '\"';\n simpleStr = '\"' strCont* '\"';\n constStr = \"@\" (simpleStr | [^\\n ;,\\]}.)`]+);\n selector = (ualnum | \"+\" | \"-\" | \"*\" | \"\/\" | \"^\" | \"=\" | \"~\" | \"<\" | \">\" | \"[\" \"]\" | \"_\")+ \":\";\n\n regexCont = (ualnum | ascii) - '\/';\n\nstring := |*\n '\\\\n' => { [strBuf appendString:@\"\\n\"]; };\n '\\\\t' => { [strBuf appendString:@\"\\t\"]; };\n '\\\\r' => { [strBuf appendString:@\"\\r\"]; };\n '\\\\\"' => { [strBuf appendString:@\"\\\"\"]; };\n \"\\\\'\" => { [strBuf appendString:@\"'\"]; };\n \"\\\\\\\\\" => { [strBuf appendString:@\"\\\\\"]; };\n '\\\\x' %{ temp1 = p; } [0-9a-zA-Z]* => {\n long long code = strtoll((char*)temp1, NULL, 16);\n [strBuf appendFormat:@\"%c\", (int)code];\n };\n \"\\\\\" ualnum+ => { TQAssert(NO, @\"Invalid escape %@\", NSStr(0,0)); };\n strCont => { [strBuf appendString:NSStr(0, 0)]; };\n\n lGuillmt => { _EmitToken(temp3 == 1 ? LSTR : MSTR, strBuf); fret; };\n '\"' term => { _EmitToken(temp3 == 1 ? STRNL : RSTRNL, strBuf); fret; };\n '\"' => { _EmitToken(temp3 == 1 ? STR : RSTR, strBuf); fret; };\n*|;\n\nregex := |*\n regexCont* \"\/\" [im]* term => { --ts; EmitToken(REGEXNL); BacktrackTerm(); fret; };\n regexCont* \"\/\" [im]* => { --ts; EmitToken(REGEX); fret; };\n*|;\n\nmain := |*\n# Symbols\n # Forward slash is context sensitive, at the beginning of an expression it means the start of a regular expression\n \"\/\" => {\n if(!parserState.atBeginningOfExpr) {\n if(p != eof && *(p+1) == '=') {\n EmitToken(ASSIGNDIV);\n p += 2;\n } else\n EmitToken(FSLASH);\n ExprBeg();\n } else\n fcall regex;\n };\n \"{\" => { EmitToken(LBRACE); ExprBeg(); };\n \"}\" term => { EmitToken(RBRACENL); ExprBeg(); BacktrackTerm(); };\n \"}\" => { EmitToken(RBRACE); };\n \"[\" => { EmitToken(LBRACKET); ExprBeg(); };\n \"]\" term => { EmitToken(RBRACKETNL); ExprBeg(); BacktrackTerm(); };\n \"]\" => { EmitToken(RBRACKET); };\n \"(\" => { EmitToken(LPAREN); ExprBeg(); };\n \")\" term => { EmitToken(RPARENNL); ExprBeg(); BacktrackTerm(); };\n \")\" => { EmitToken(RPAREN); };\n \",\" => { EmitToken(COMMA); ExprBeg(); };\n \"`\" term => { EmitToken(BACKTICKNL); BacktrackTerm(); };\n \"`\" => { EmitToken(BACKTICK); };\n \";\" => { EmitToken(SEMICOLON); };\n \"=\" => { EmitToken(ASSIGN); ExprBeg(); };\n \"+=\" => { EmitToken(ASSIGNADD); ExprBeg(); };\n \"-=\" => { EmitToken(ASSIGNSUB); ExprBeg(); };\n \"*=\" => { EmitToken(ASSIGNMUL); ExprBeg(); };\n# \"\/=\" => { EmitToken(ASSIGNDIV); ExprBeg(); };\n \"||=\" => { EmitToken(ASSIGNOR); ExprBeg(); };\n \"+\" => { EmitToken(PLUS); ExprBeg(); };\n \"-\" => { EmitToken(MINUS); ExprBeg(); };\n \"--\" => { EmitToken(DECR); };\n \"--\" term => { EmitToken(DECRNL); ExprBeg();BacktrackTerm(); };\n \"++\" => { EmitToken(INCR); };\n \"++\" term => { EmitToken(INCRNL); ExprBeg();BacktrackTerm(); };\n \"*\" => { EmitToken(ASTERISK); ExprBeg(); };\n \"%\" => { EmitToken(PERCENT); ExprBeg(); };\n \"~\" => { EmitToken(TILDE); ExprBeg(); };\n \"#\" => { EmitToken(HASH); };\n \"|\" => { EmitToken(PIPE); ExprBeg(); };\n \"^\" => { EmitToken(CARET); ExprBeg(); };\n \"?\" => { EmitToken(TERNIF); ExprBeg(); };\n \"!\" => { EmitToken(TERNELSE); ExprBeg(); };\n \"==\" => { EmitToken(EQUAL); ExprBeg(); };\n \"!=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"~=\" => { EmitToken(INEQUAL); ExprBeg(); };\n \"<\" => { EmitToken(LESSER); ExprBeg(); };\n \">\" => { EmitToken(GREATER); ExprBeg(); };\n \"<=\" => { EmitToken(LEQUAL); ExprBeg(); };\n \">=\" => { EmitToken(GEQUAL); ExprBeg(); };\n \"=>\" => { EmitToken(DICTSEP); ExprBeg(); };\n\n# Message selectors\n selector => { EmitStringToken(SELPART, 0, 1); ExprBeg(); };\n\n# Keywords\n \"if\" term? => { EmitToken(IF); ExprBeg(); BacktrackTerm(); };\n \"unless\" term? => { EmitToken(UNLESS); ExprBeg(); BacktrackTerm(); };\n \"then\" term? => { EmitToken(THEN); ExprBeg(); BacktrackTerm(); };\n \"else\" term? => { EmitToken(ELSE); ExprBeg(); BacktrackTerm(); };\n \"and\"|\"&&\"term? => { EmitToken(AND); ExprBeg(); BacktrackTerm(); };\n \"or\"|\"||\" term? => { EmitToken(OR); ExprBeg(); BacktrackTerm(); };\n \"while\" term? => { EmitToken(WHILE); ExprBeg(); BacktrackTerm(); };\n \"until\" term? => { EmitToken(UNTIL); ExprBeg(); BacktrackTerm(); };\n \"import\" term? => { EmitToken(IMPORT); ExprBeg(); BacktrackTerm(); };\n \"async\" term? => { EmitToken(ASYNC); ExprBeg(); BacktrackTerm(); };\n \"wait\" term => { EmitToken(WAITNL); ExprBeg(); BacktrackTerm(); };\n \"wait\" => { EmitToken(WAIT); };\n \"lock\" => { EmitToken(LOCK); };\n \"whenFinished\" => { EmitToken(WHENFINISHED); };\n \"collect\" => { EmitToken(COLLECT); };\n \"break\" term => { EmitToken(BREAKNL); ExprBeg(); BacktrackTerm(); };\n \"break\" => { EmitToken(BREAK); };\n \"skip\" term => { EmitToken(SKIPNL); ExprBeg(); BacktrackTerm(); };\n \"skip\" => { EmitToken(SKIP); };\n \"self\" term => { EmitToken(SELFNL); ExprBeg(); BacktrackTerm(); };\n \"super\" term => { EmitToken(SUPERNL); ExprBeg(); BacktrackTerm(); };\n \"...\" term => { EmitToken(VAARGNL); ExprBeg(); BacktrackTerm(); };\n \"nil\" term => { EmitToken(NILNL); ExprBeg(); BacktrackTerm(); };\n \"valid\" term => { EmitToken(VALIDNL); ExprBeg(); BacktrackTerm(); };\n \"yes\" term => { EmitToken(YESTOKNL); ExprBeg(); BacktrackTerm(); };\n \"no\" term => { EmitToken(NOTOKNL); ExprBeg(); BacktrackTerm(); };\n \"nothing\" term => { EmitToken(NOTHINGNL); ExprBeg(); BacktrackTerm(); };\n \"self\" => { EmitToken(SELF); };\n \"super\" => { EmitToken(SUPER); };\n \"...\" => { EmitToken(VAARG); };\n \"nil\" => { EmitToken(NIL); };\n \"valid\" => { EmitToken(VALID); };\n \"yes\" => { EmitToken(YESTOK); };\n \"no\" => { EmitToken(NOTOK); };\n \"nothing\" => { EmitToken(NOTHING); };\n\n\n# Identifiers\n identifier %{temp1 = p;} term => { EmitStringToken(IDENTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n identifier => { EmitStringToken(IDENT, 0, 0); };\n\n constant %{temp1 = p;} term => { EmitStringToken(CONSTNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constant => { EmitStringToken(CONST, 0, 0); };\n\n# Literals\n int term => { EmitIntToken(NUMBERNL, 10, 0); ExprBeg(); BacktrackTerm(); };\n float term => { EmitFloatToken(NUMBERNL); ExprBeg(); BacktrackTerm(); };\n bin term => { EmitIntToken(NUMBERNL, 2, 2); ExprBeg(); BacktrackTerm(); };\n oct term => { EmitIntToken(NUMBERNL, 8, 2); ExprBeg(); BacktrackTerm(); };\n hex term => { EmitIntToken(NUMBERNL, 16, 2); ExprBeg(); BacktrackTerm(); };\n anybase term => {\n \/\/ Find the base\n NSString *str = NSStr(0,0);\n NSString *baseStr = [str substringToIndex:[str rangeOfString:@\"r\"].location];\n EmitIntToken(NUMBERNL, atoi([baseStr UTF8String]), [baseStr length]+1); ExprBeg(); BacktrackTerm();\n };\n\n int => { EmitIntToken(NUMBER, 10, 0); };\n float => { EmitFloatToken(NUMBER); };\n bin => { EmitIntToken(NUMBER, 2, 2); };\n oct => { EmitIntToken(NUMBER, 8, 2); };\n hex => { EmitIntToken(NUMBER, 16, 2); };\n\n constStr %{temp1 = p;} term => { EmitConstStringToken(CONSTSTRNL, 0, te-temp1); ExprBeg(); BacktrackTerm(); };\n constStr => { EmitConstStringToken(CONSTSTR, 0, 0); };\n\n '\"' => { temp3 = 1; strBuf = [NSMutableString string]; fcall string; };\n rGuillmt => { temp3 = 2; strBuf = [NSMutableString string]; fcall string; };\n\n nl => { IncrementLine(); };\n space;\n*|;\n}%%\n\n%% write data nofinal;\n\n#include \"parse.mm\"\n\nextern \"C\" TQNode *TQParseString(NSString *str, NSError **aoErr)\n{\n if(![str hasSuffix:@\"\\n\"])\n str = [str stringByAppendingString:@\"\\n\"];\n\n int cs, act;\n unsigned char *ts, *te = 0;\n\n \/\/ Lexer setup\n unsigned char *p = (unsigned char *)[str UTF8String];\n unsigned char *pe = p + strlen((char*)p);\n unsigned char *eof = pe;\n int top;\n int stack[1024];\n NSMutableString *strBuf;\n\n unsigned char *temp1, *temp2;\n int temp3 = 0;\n\n \/\/ Parser setup\n void *parser = ParseAlloc(malloc);\n TQParserState parserState = {\n 1, YES, [TQNodeRootBlock new]\n };\n\n @try {\n %% write init;\n %% write exec;\n\n if(p != pe)\n fprintf(stderr, \"invalid character '%c'\\n\", p[0]);\n\n EmitToken(0); \/\/ EOF\n return [parserState.root autorelease];\n } @catch(NSException *e) {\n if(aoErr)\n *aoErr = [NSError errorWithDomain:kTQSyntaxErrorDomain\n code:kTQGenericError\n userInfo:[NSDictionary dictionaryWithObject:[e reason] forKey:@\"reason\"]];\n return nil;\n } @finally {\n ParseFree(parser, free);\n }\n return nil;\n}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Ragel in Ruby Host"} {"commit":"8d65046af4622346dbfcaa5e32d3c6e76d0842c9","subject":"cleanup","message":"cleanup\n","repos":"razum2um\/params_tree","old_file":"hello_world.rl","new_file":"hello_world.rl","new_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ])+ >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); p + 1 == pe and @hash[key] = {}; };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n puts @hash_stack.inspect\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\nParamsTree::Parser.new.process \"default(all,usadasdid(zczxc(pio),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\n","old_contents":"%%{\n machine params_parser;\n action H { @head = p }\n action T { @tail = p }\n action inject_key { @hash[key] = {} }\n action push { @hash_stack.push @hash; @hash = @hash[key] }\n action pop { @hash = @hash_stack.pop }\n\n DELIMITER = ([, ])+ >H@T @{ log(:delimiter) };\n LEVEL = ('(')+ >H@T @{ log(:level) };\n END_LEVEL = (')')+ >H@T @{ log(:end_level); p + 1 == pe and inject_key; };\n INPUT = (any - LEVEL - END_LEVEL - DELIMITER)+ >H@T @{ log(:input); memo_key; };\n\n main := (\n INPUT\n (\n DELIMITER @inject_key @{ fnext main; } |\n END_LEVEL DELIMITER @inject_key @pop @{ fret; } |\n LEVEL @inject_key @push @{ fcall main; }\n )\n )*;\n}%%\n\nmodule ParamsTree\n class Parser\n attr_accessor :data\n\n def initialize\n %% write data;\n end\n\n def process(input)\n @data = input.unpack('c*')\n stack = []\n\n @log = []\n @hash = {}\n @hash_stack = []\n @key = nil\n\n %% write init;\n %% write exec;\n\n puts @hash_stack.inspect\n end\n\n def char\n @data[@head..@tail]\n end\n\n def strokes\n char.pack('c*')\n end\n\n def log(token)\n @log << { token => strokes }\n end\n\n def memo_key\n @key = char\n end\n\n def key\n @key.pack('c*')\n end\n end\nend\n\nParamsTree::Parser.new.process \"default(all,usadasdid(zczxc(pio),cvb)),isdsdd(wow,er),sed(rew,tre,yrt(dfg,gfd))\"\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"c9384d7a172ff11099dda06e3735cf5e2f8ed3fe","subject":"Removed CallFrame* from send.","message":"Removed CallFrame* from send.\n","repos":"rubinius\/rapa","old_file":"actions\/rubinius\/pack_code.rl","new_file":"actions\/rubinius\/pack_code.rl","new_contents":"\/* This file was generated by Ragel. Your edits will be lost.\n *\n * This is a state machine implementation of Array#pack.\n * See http:\/\/github.com\/rubinius\/rapa.\n *\n * vim: filetype=cpp\n *\/\n\n#include \n#include \n\n#include \"machine\/config.h\"\n\n#include \"alloc.hpp\"\n#include \"memory.hpp\"\n#include \"object_utils.hpp\"\n#include \"on_stack.hpp\"\n#include \"state.hpp\"\n#include \"vm.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/byte_array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/encoding.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n\n#ifdef RBX_WINDOWS\n#include \n#endif\n\nnamespace rubinius {\n namespace pack {\n inline Object* to_int(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->symbol(\"pack_to_int\"), args);\n }\n\n#define BITS_LONG (RBX_SIZEOF_LONG * 8)\n\n inline long check_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_LONG);\n return big->to_long();\n }\n }\n\n#define BITS_64 (64)\n\n inline long long check_long_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_64);\n return big->to_long_long();\n }\n }\n\n inline Object* to_f(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->symbol(\"pack_to_float\"), args);\n }\n\n inline String* encoding_string(STATE, Object* obj, const char* coerce_name)\n {\n String* s = try_as(obj);\n if(s) return s;\n\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n std::string coerce_method(\"pack_\");\n coerce_method += coerce_name;\n Object* result = G(rubinius)->send(state, state->symbol(coerce_method.c_str()), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n inline uint16_t swap_2bytes(uint16_t x) {\n return (((x & 0x00ff)<<8) | ((x & 0xff00)>>8));\n }\n\n inline uint32_t swap_4bytes(uint32_t x) {\n return (((x & 0x000000ff) << 24)\n |((x & 0xff000000) >> 24)\n |((x & 0x0000ff00) << 8)\n |((x & 0x00ff0000) >> 8));\n }\n\n inline uint64_t swap_8bytes(uint64_t x) {\n return (((x & 0x00000000000000ffLL) << 56)\n |((x & 0xff00000000000000LL) >> 56)\n |((x & 0x000000000000ff00LL) << 40)\n |((x & 0x00ff000000000000LL) >> 40)\n |((x & 0x0000000000ff0000LL) << 24)\n |((x & 0x0000ff0000000000LL) >> 24)\n |((x & 0x00000000ff000000LL) << 8)\n |((x & 0x000000ff00000000LL) >> 8));\n }\n\n inline void swap_float(std::string& str, float value) {\n uint32_t x;\n\n memcpy(&x, &value, sizeof(float));\n x = swap_4bytes(x);\n\n str.append((const char*)&x, sizeof(uint32_t));\n }\n\n inline void swap_double(std::string& str, double value) {\n uint64_t x;\n\n memcpy(&x, &value, sizeof(double));\n x = swap_8bytes(x);\n\n str.append((const char*)&x, sizeof(uint64_t));\n }\n\n inline void double_element(std::string& str, double value) {\n str.append((const char*)&value, sizeof(double));\n }\n\n inline void float_element(std::string& str, float value) {\n str.append((const char*)&value, sizeof(float));\n }\n\n inline void short_element(std::string& str, int16_t value) {\n str.append((const char*)&value, sizeof(int16_t));\n }\n\n inline void int_element(std::string& str, int32_t value) {\n str.append((const char*)&value, sizeof(int32_t));\n }\n\n inline void long_element(std::string& str, int64_t value) {\n str.append((const char*)&value, sizeof(int64_t));\n }\n\n inline int32_t int32_element(STATE, Integer* value) {\n if(value->fixnum_p()) {\n long l = as(value)->to_long();\n if(l > INT32_MAX || l < INT32_MIN) {\n Exception::raise_range_error(state, \"Fixnum value out of range of int32\");\n }\n return l;\n } else {\n Bignum* big = as(value);\n big->verify_size(state, 32);\n return big->to_int();\n }\n }\n\n#define QUOTABLE_PRINTABLE_BUFSIZE 1024\n\n static const char hex_table[] = \"0123456789ABCDEF\";\n void quotable_printable(String* s, std::string& str, int count) {\n char buf[QUOTABLE_PRINTABLE_BUFSIZE];\n\n uint8_t* b = s->byte_address();\n uint8_t* e = b + s->byte_size();\n int i = 0, n = 0, prev = -1;\n\n for(; b < e; b++) {\n if((*b > 126) || (*b < 32 && *b != '\\n' && *b != '\\t') || (*b == '=')) {\n buf[i++] = '=';\n buf[i++] = hex_table[*b >> 4];\n buf[i++] = hex_table[*b & 0x0f];\n n += 3;\n prev = -1;\n } else if(*b == '\\n') {\n if(prev == ' ' || prev == '\\t') {\n buf[i++] = '=';\n buf[i++] = *b;\n }\n buf[i++] = *b;\n n = 0;\n prev = *b;\n } else {\n buf[i++] = *b;\n n++;\n prev = *b;\n }\n\n if(n > count) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n n = 0;\n prev = '\\n';\n }\n\n if(i > QUOTABLE_PRINTABLE_BUFSIZE - 5) {\n str.append(buf, i);\n i = 0;\n }\n }\n\n if(n > 0) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n }\n\n if(i > 0) {\n str.append(buf, i);\n }\n }\n\n static const char uu_table[] =\n \"`!\\\"#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_\";\n static const char b64_table[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n\n#define b64_uu_byte1(t, b) t[077 & (*b >> 2)]\n#define b64_uu_byte2(t, b, c) t[077 & (((*b << 4) & 060) | ((c >> 4) & 017))]\n#define b64_uu_byte3(t, b, c) t[077 & (((b[1] << 2) & 074) | ((c >> 6) & 03))];\n#define b64_uu_byte4(t, b) t[077 & b[2]];\n\n void b64_uu_encode(String* s, std::string& str,\n native_int count, native_int count_flag,\n const char* table, int padding, bool encode_size)\n {\n char *buf = ALLOCA_N(char, count * 4 \/ 3 + 6);\n native_int i, chars, line, total = s->byte_size();\n uint8_t* b = s->byte_address();\n\n for(i = 0; total > 0; i = 0, total -= line) {\n line = total > count ? count : total;\n\n if(encode_size) buf[i++] = line + ' ';\n\n for(chars = line; chars >= 3; chars -= 3, b += 3) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, b[2]);\n buf[i++] = b64_uu_byte4(table, b);\n }\n\n if(chars == 2) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, '\\0');\n buf[i++] = padding;\n } else if(chars == 1) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, '\\0');\n buf[i++] = padding;\n buf[i++] = padding;\n }\n\n b += chars;\n if(encode_size || (!encode_size && count_flag > 0)) {\n buf[i++] = '\\n';\n }\n str.append(buf, i);\n }\n }\n\n void utf8_encode(STATE, std::string& str, Integer* value) {\n int32_t v = int32_element(state, value);\n\n if(!(v & ~0x7f)) {\n str.push_back(v);\n } else if(!(v & ~0x7ff)) {\n str.push_back(((v >> 6) & 0xff) | 0xc0);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0xffff)) {\n str.push_back(((v >> 12) & 0xff) | 0xe0);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x1fffff)) {\n str.push_back(((v >> 18) & 0xff) | 0xf0);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x3ffffff)) {\n str.push_back(((v >> 24) & 0xff) | 0xf8);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x7fffffff)) {\n str.push_back(((v >> 30) & 0xff) | 0xfc);\n str.push_back(((v >> 24) & 0x3f) | 0x80);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else {\n Exception::raise_range_error(state, \"pack('U') value out of range\");\n }\n }\n\n void ber_encode(STATE, std::string& str, Integer* value) {\n if(!value->positive_p()) {\n Exception::raise_argument_error(state, \"cannot BER compress a negative number\");\n }\n\n std::string buf;\n\n if(try_as(value)) {\n Fixnum* base = Fixnum::from(128);\n while(try_as(value)) {\n Array* ary;\n if(value->fixnum_p()) {\n ary = as(value)->divmod(state, base);\n } else {\n ary = as(value)->divmod(state, base);\n }\n buf.push_back(as(ary->get(state, 1))->to_native() | 0x80);\n value = as(ary->get(state, 0));\n }\n }\n\n long v = value->to_long();\n\n while(v) {\n buf.push_back((v & 0x7f) | 0x80);\n v >>= 7;\n }\n\n if(buf.size() > 0) {\n char* a = const_cast(buf.c_str());\n char* b = a + buf.size() - 1;\n\n \/\/ clear continue bit\n *a &= 0x7f;\n\n \/\/ reverse string\n while(a < b) {\n int k = *a;\n *a++ = *b;\n *b-- = k;\n }\n\n str.append(buf.c_str(), buf.size());\n } else {\n str.push_back(0);\n }\n }\n\n inline native_int bit_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count - size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void bit_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n byte |= *b & 1;\n if(i & 7) {\n byte <<= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte <<= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n void bit_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(*b & 1)\n byte |= 128;\n\n if(i & 7) {\n byte >>= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte >>= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n inline native_int hex_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count + 1) \/ 2 - (size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void hex_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= ((*b & 15) + 9) & 15;\n } else {\n byte |= *b & 15;\n }\n\n if(i & 1) {\n byte <<= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n void hex_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= (((*b & 15) + 9) & 15) << 4;\n } else {\n byte |= (*b & 15) << 4;\n }\n\n if(i & 1) {\n byte >>= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n ByteArray* prepare_directives(STATE, String* directives,\n const char** p, const char** pe)\n {\n native_int size = directives->byte_size();\n ByteArray* ba = ByteArray::create_pinned(state, size + 1);\n char* b = reinterpret_cast(ba->raw_bytes());\n char* d = reinterpret_cast(directives->byte_address());\n int i = 0, j = 0;\n\n while(i < size) {\n switch(d[i]) {\n case 0:\n case ' ':\n case '\\t':\n case '\\n':\n case '\\v':\n case '\\f':\n case '\\r':\n i++;\n break;\n case '#':\n while(++i < size && d[i] != '\\n')\n ; \/\/ ignore\n if(d[i] == '\\n') i++;\n break;\n default:\n b[j++] = d[i++];\n break;\n }\n }\n\n *p = const_cast(b);\n *pe = *p + j;\n\n return ba;\n }\n\n void exceeds_length_of_string(STATE, native_int count) {\n std::ostringstream msg;\n msg << \"X\" << count << \" exceeds length of string\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n\n void non_native_error(STATE, const char c) {\n std::ostringstream msg;\n msg << \"'\" << c << \"' allowed only after types sSiIlL\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n }\n\n\n\/\/ Pack Float elements\n#define pack_float_elements(format) pack_elements(Float, pack::to_f, format)\n\n#define pack_double_le pack_float_elements(pack_double_element_le)\n#define pack_double_be pack_float_elements(pack_double_element_be)\n\n#define pack_float_le pack_float_elements(pack_float_element_le)\n#define pack_float_be pack_float_elements(pack_float_element_be)\n\n\/\/ Pack Integer elements\n#define pack_integer_elements(format) pack_elements(Integer, pack::to_int, format)\n\n#define pack_byte_element(v) str.push_back(pack::check_long(state, v))\n#define pack_byte pack_integer_elements(pack_byte_element)\n\n#define pack_short_le pack_integer_elements(pack_short_element_le)\n#define pack_short_be pack_integer_elements(pack_short_element_be)\n\n#define pack_int_le pack_integer_elements(pack_int_element_le)\n#define pack_int_be pack_integer_elements(pack_int_element_be)\n\n#define pack_long_le pack_integer_elements(pack_long_element_le)\n#define pack_long_be pack_integer_elements(pack_long_element_be)\n\n\/\/ Pack UTF-8 elements\n#define pack_utf8_element(v) pack::utf8_encode(state, str, v)\n#define pack_utf8 pack_elements(Integer, pack::to_int, pack_utf8_element)\n\n\/\/ Pack BER-compressed integers\n#define pack_ber_element(v) pack::ber_encode(state, str, v)\n#define pack_ber pack_elements(Integer, pack::to_int, pack_ber_element)\n\n\/\/ Wraps the logic for iterating over a number of elements,\n\/\/ coercing them to the correct class and formatting them\n\/\/ for the output string.\n#define pack_elements(T, coerce, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n format(value); \\\n }\n\n\/\/ Macros that depend on endianness\n#ifdef RBX_LITTLE_ENDIAN\n\n# define pack_double_element_le(v) (pack::double_element(str, (v)->val))\n# define pack_double_element_be(v) (pack::swap_double(str, (v)->val))\n# define pack_double pack_double_le\n\n# define pack_float_element_le(v) (pack::float_element(str, (v)->val))\n# define pack_float_element_be(v) (pack::swap_float(str, (v)->val))\n# define pack_float pack_float_le\n\n# define pack_short_element_le(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short_element_be(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short pack_short_le\n\n# define pack_int_element_le(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int_element_be(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int pack_int_le\n\n# define pack_long_element_le(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long_element_be(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long pack_long_le\n\n#else \/\/ Big endian\n\n# define pack_double_element_le(v) (pack::swap_double(str, (v)->val))\n# define pack_double_element_be(v) (pack::double_element(str, (v)->val))\n# define pack_double pack_double_be\n\n# define pack_float_element_le(v) (pack::swap_float(str, (v)->val))\n# define pack_float_element_be(v) (pack::float_element(str, (v)->val))\n# define pack_float pack_float_be\n\n# define pack_short_element_le(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short_element_be(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short pack_short_be\n\n# define pack_int_element_le(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int_element_be(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int pack_int_be\n\n# define pack_long_element_le(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long_element_be(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long pack_long_be\n\n#endif\n\n\n String* Array::pack(STATE, String* directives) {\n \/\/ Ragel-specific variables\n const char* p;\n const char* pe;\n ByteArray* d = pack::prepare_directives(state, directives, &p, &pe);\n const char *eof = pe;\n int cs;\n\n \/\/ pack-specific variables\n Array* self = this;\n OnStack<2> sv(state, self, d);\n\n native_int array_size = self->size();\n native_int index = 0;\n native_int count UNUSED = 0;\n native_int count_flag = -1;\n native_int stop = 0;\n bool rest UNUSED = false;\n bool tainted UNUSED = false;\n bool untrusted UNUSED = false;\n bool ascii_encoding = false;\n bool utf8_encoding = false;\n bool string_encoding = false;\n\n String* string_value = 0;\n std::string str(\"\");\n\n \/\/ Use information we have to reduce repeated allocation.\n str.reserve(array_size * 4);\n\n if(directives->byte_size() == 0) ascii_encoding = true;\n if(CBOOL(directives->tainted_p(state))) tainted = true;\n if(CBOOL(directives->untrusted_p(state))) untrusted = true;\n%%{\n\n machine pack;\n\n include \"pack.rl\";\n\n}%%\n\n if(en_main) {\n \/\/ do nothing\n }\n\n return force_as(Primitives::failure());\n }\n}\n","old_contents":"\/* This file was generated by Ragel. Your edits will be lost.\n *\n * This is a state machine implementation of Array#pack.\n * See http:\/\/github.com\/rubinius\/rapa.\n *\n * vim: filetype=cpp\n *\/\n\n#include \n#include \n\n#include \"machine\/config.h\"\n\n#include \"alloc.hpp\"\n#include \"memory.hpp\"\n#include \"object_utils.hpp\"\n#include \"on_stack.hpp\"\n#include \"state.hpp\"\n#include \"vm.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/byte_array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/encoding.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n\n#ifdef RBX_WINDOWS\n#include \n#endif\n\nnamespace rubinius {\n namespace pack {\n inline Object* to_int(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->vm()->get_call_frame(),\n state->symbol(\"pack_to_int\"), args);\n }\n\n#define BITS_LONG (RBX_SIZEOF_LONG * 8)\n\n inline long check_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_LONG);\n return big->to_long();\n }\n }\n\n#define BITS_64 (64)\n\n inline long long check_long_long(STATE, Integer* obj) {\n if((obj)->fixnum_p()) {\n return force_as(obj)->to_long_long();\n } else {\n Bignum* big = as(obj);\n big->verify_size(state, BITS_64);\n return big->to_long_long();\n }\n }\n\n inline Object* to_f(STATE, Object* obj) {\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n return G(rubinius)->send(state, state->vm()->get_call_frame(),\n state->symbol(\"pack_to_float\"), args);\n }\n\n inline String* encoding_string(STATE, Object* obj, const char* coerce_name)\n {\n String* s = try_as(obj);\n if(s) return s;\n\n Array* args = Array::create(state, 1);\n args->set(state, 0, obj);\n\n std::string coerce_method(\"pack_\");\n coerce_method += coerce_name;\n Object* result = G(rubinius)->send(state, state->vm()->get_call_frame(),\n state->symbol(coerce_method.c_str()), args);\n\n if(!result) return 0;\n return as(result);\n }\n\n inline uint16_t swap_2bytes(uint16_t x) {\n return (((x & 0x00ff)<<8) | ((x & 0xff00)>>8));\n }\n\n inline uint32_t swap_4bytes(uint32_t x) {\n return (((x & 0x000000ff) << 24)\n |((x & 0xff000000) >> 24)\n |((x & 0x0000ff00) << 8)\n |((x & 0x00ff0000) >> 8));\n }\n\n inline uint64_t swap_8bytes(uint64_t x) {\n return (((x & 0x00000000000000ffLL) << 56)\n |((x & 0xff00000000000000LL) >> 56)\n |((x & 0x000000000000ff00LL) << 40)\n |((x & 0x00ff000000000000LL) >> 40)\n |((x & 0x0000000000ff0000LL) << 24)\n |((x & 0x0000ff0000000000LL) >> 24)\n |((x & 0x00000000ff000000LL) << 8)\n |((x & 0x000000ff00000000LL) >> 8));\n }\n\n inline void swap_float(std::string& str, float value) {\n uint32_t x;\n\n memcpy(&x, &value, sizeof(float));\n x = swap_4bytes(x);\n\n str.append((const char*)&x, sizeof(uint32_t));\n }\n\n inline void swap_double(std::string& str, double value) {\n uint64_t x;\n\n memcpy(&x, &value, sizeof(double));\n x = swap_8bytes(x);\n\n str.append((const char*)&x, sizeof(uint64_t));\n }\n\n inline void double_element(std::string& str, double value) {\n str.append((const char*)&value, sizeof(double));\n }\n\n inline void float_element(std::string& str, float value) {\n str.append((const char*)&value, sizeof(float));\n }\n\n inline void short_element(std::string& str, int16_t value) {\n str.append((const char*)&value, sizeof(int16_t));\n }\n\n inline void int_element(std::string& str, int32_t value) {\n str.append((const char*)&value, sizeof(int32_t));\n }\n\n inline void long_element(std::string& str, int64_t value) {\n str.append((const char*)&value, sizeof(int64_t));\n }\n\n inline int32_t int32_element(STATE, Integer* value) {\n if(value->fixnum_p()) {\n long l = as(value)->to_long();\n if(l > INT32_MAX || l < INT32_MIN) {\n Exception::raise_range_error(state, \"Fixnum value out of range of int32\");\n }\n return l;\n } else {\n Bignum* big = as(value);\n big->verify_size(state, 32);\n return big->to_int();\n }\n }\n\n#define QUOTABLE_PRINTABLE_BUFSIZE 1024\n\n static const char hex_table[] = \"0123456789ABCDEF\";\n void quotable_printable(String* s, std::string& str, int count) {\n char buf[QUOTABLE_PRINTABLE_BUFSIZE];\n\n uint8_t* b = s->byte_address();\n uint8_t* e = b + s->byte_size();\n int i = 0, n = 0, prev = -1;\n\n for(; b < e; b++) {\n if((*b > 126) || (*b < 32 && *b != '\\n' && *b != '\\t') || (*b == '=')) {\n buf[i++] = '=';\n buf[i++] = hex_table[*b >> 4];\n buf[i++] = hex_table[*b & 0x0f];\n n += 3;\n prev = -1;\n } else if(*b == '\\n') {\n if(prev == ' ' || prev == '\\t') {\n buf[i++] = '=';\n buf[i++] = *b;\n }\n buf[i++] = *b;\n n = 0;\n prev = *b;\n } else {\n buf[i++] = *b;\n n++;\n prev = *b;\n }\n\n if(n > count) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n n = 0;\n prev = '\\n';\n }\n\n if(i > QUOTABLE_PRINTABLE_BUFSIZE - 5) {\n str.append(buf, i);\n i = 0;\n }\n }\n\n if(n > 0) {\n buf[i++] = '=';\n buf[i++] = '\\n';\n }\n\n if(i > 0) {\n str.append(buf, i);\n }\n }\n\n static const char uu_table[] =\n \"`!\\\"#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_\";\n static const char b64_table[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n\n#define b64_uu_byte1(t, b) t[077 & (*b >> 2)]\n#define b64_uu_byte2(t, b, c) t[077 & (((*b << 4) & 060) | ((c >> 4) & 017))]\n#define b64_uu_byte3(t, b, c) t[077 & (((b[1] << 2) & 074) | ((c >> 6) & 03))];\n#define b64_uu_byte4(t, b) t[077 & b[2]];\n\n void b64_uu_encode(String* s, std::string& str,\n native_int count, native_int count_flag,\n const char* table, int padding, bool encode_size)\n {\n char *buf = ALLOCA_N(char, count * 4 \/ 3 + 6);\n native_int i, chars, line, total = s->byte_size();\n uint8_t* b = s->byte_address();\n\n for(i = 0; total > 0; i = 0, total -= line) {\n line = total > count ? count : total;\n\n if(encode_size) buf[i++] = line + ' ';\n\n for(chars = line; chars >= 3; chars -= 3, b += 3) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, b[2]);\n buf[i++] = b64_uu_byte4(table, b);\n }\n\n if(chars == 2) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, b[1]);\n buf[i++] = b64_uu_byte3(table, b, '\\0');\n buf[i++] = padding;\n } else if(chars == 1) {\n buf[i++] = b64_uu_byte1(table, b);\n buf[i++] = b64_uu_byte2(table, b, '\\0');\n buf[i++] = padding;\n buf[i++] = padding;\n }\n\n b += chars;\n if(encode_size || (!encode_size && count_flag > 0)) {\n buf[i++] = '\\n';\n }\n str.append(buf, i);\n }\n }\n\n void utf8_encode(STATE, std::string& str, Integer* value) {\n int32_t v = int32_element(state, value);\n\n if(!(v & ~0x7f)) {\n str.push_back(v);\n } else if(!(v & ~0x7ff)) {\n str.push_back(((v >> 6) & 0xff) | 0xc0);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0xffff)) {\n str.push_back(((v >> 12) & 0xff) | 0xe0);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x1fffff)) {\n str.push_back(((v >> 18) & 0xff) | 0xf0);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x3ffffff)) {\n str.push_back(((v >> 24) & 0xff) | 0xf8);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else if(!(v & ~0x7fffffff)) {\n str.push_back(((v >> 30) & 0xff) | 0xfc);\n str.push_back(((v >> 24) & 0x3f) | 0x80);\n str.push_back(((v >> 18) & 0x3f) | 0x80);\n str.push_back(((v >> 12) & 0x3f) | 0x80);\n str.push_back(((v >> 6) & 0x3f) | 0x80);\n str.push_back((v & 0x3f) | 0x80);\n } else {\n Exception::raise_range_error(state, \"pack('U') value out of range\");\n }\n }\n\n void ber_encode(STATE, std::string& str, Integer* value) {\n if(!value->positive_p()) {\n Exception::raise_argument_error(state, \"cannot BER compress a negative number\");\n }\n\n std::string buf;\n\n if(try_as(value)) {\n Fixnum* base = Fixnum::from(128);\n while(try_as(value)) {\n Array* ary;\n if(value->fixnum_p()) {\n ary = as(value)->divmod(state, base);\n } else {\n ary = as(value)->divmod(state, base);\n }\n buf.push_back(as(ary->get(state, 1))->to_native() | 0x80);\n value = as(ary->get(state, 0));\n }\n }\n\n long v = value->to_long();\n\n while(v) {\n buf.push_back((v & 0x7f) | 0x80);\n v >>= 7;\n }\n\n if(buf.size() > 0) {\n char* a = const_cast(buf.c_str());\n char* b = a + buf.size() - 1;\n\n \/\/ clear continue bit\n *a &= 0x7f;\n\n \/\/ reverse string\n while(a < b) {\n int k = *a;\n *a++ = *b;\n *b-- = k;\n }\n\n str.append(buf.c_str(), buf.size());\n } else {\n str.push_back(0);\n }\n }\n\n inline native_int bit_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count - size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void bit_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n byte |= *b & 1;\n if(i & 7) {\n byte <<= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte <<= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n void bit_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(*b & 1)\n byte |= 128;\n\n if(i & 7) {\n byte >>= 1;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 7) {\n byte >>= 7 - (count & 7);\n str.push_back(byte & 0xff);\n }\n }\n\n inline native_int hex_extra(String* s, bool rest, native_int& count) {\n native_int extra = 0;\n\n if(rest) {\n count = s->byte_size();\n } else {\n native_int size = s->byte_size();\n if(count > size) {\n extra = (count + 1) \/ 2 - (size + 1) \/ 2;\n count = size;\n }\n }\n\n return extra;\n }\n\n void hex_high(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= ((*b & 15) + 9) & 15;\n } else {\n byte |= *b & 15;\n }\n\n if(i & 1) {\n byte <<= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n void hex_low(String* s, std::string& str, native_int count) {\n uint8_t* b = s->byte_address();\n int byte = 0;\n\n for(native_int i = 0; i++ < count; b++) {\n if(ISALPHA(*b)) {\n byte |= (((*b & 15) + 9) & 15) << 4;\n } else {\n byte |= (*b & 15) << 4;\n }\n\n if(i & 1) {\n byte >>= 4;\n } else {\n str.push_back(byte & 0xff);\n byte = 0;\n }\n }\n\n if(count & 1) {\n str.push_back(byte & 0xff);\n }\n }\n\n ByteArray* prepare_directives(STATE, String* directives,\n const char** p, const char** pe)\n {\n native_int size = directives->byte_size();\n ByteArray* ba = ByteArray::create_pinned(state, size + 1);\n char* b = reinterpret_cast(ba->raw_bytes());\n char* d = reinterpret_cast(directives->byte_address());\n int i = 0, j = 0;\n\n while(i < size) {\n switch(d[i]) {\n case 0:\n case ' ':\n case '\\t':\n case '\\n':\n case '\\v':\n case '\\f':\n case '\\r':\n i++;\n break;\n case '#':\n while(++i < size && d[i] != '\\n')\n ; \/\/ ignore\n if(d[i] == '\\n') i++;\n break;\n default:\n b[j++] = d[i++];\n break;\n }\n }\n\n *p = const_cast(b);\n *pe = *p + j;\n\n return ba;\n }\n\n void exceeds_length_of_string(STATE, native_int count) {\n std::ostringstream msg;\n msg << \"X\" << count << \" exceeds length of string\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n\n void non_native_error(STATE, const char c) {\n std::ostringstream msg;\n msg << \"'\" << c << \"' allowed only after types sSiIlL\";\n Exception::raise_argument_error(state, msg.str().c_str());\n }\n }\n\n\n\/\/ Pack Float elements\n#define pack_float_elements(format) pack_elements(Float, pack::to_f, format)\n\n#define pack_double_le pack_float_elements(pack_double_element_le)\n#define pack_double_be pack_float_elements(pack_double_element_be)\n\n#define pack_float_le pack_float_elements(pack_float_element_le)\n#define pack_float_be pack_float_elements(pack_float_element_be)\n\n\/\/ Pack Integer elements\n#define pack_integer_elements(format) pack_elements(Integer, pack::to_int, format)\n\n#define pack_byte_element(v) str.push_back(pack::check_long(state, v))\n#define pack_byte pack_integer_elements(pack_byte_element)\n\n#define pack_short_le pack_integer_elements(pack_short_element_le)\n#define pack_short_be pack_integer_elements(pack_short_element_be)\n\n#define pack_int_le pack_integer_elements(pack_int_element_le)\n#define pack_int_be pack_integer_elements(pack_int_element_be)\n\n#define pack_long_le pack_integer_elements(pack_long_element_le)\n#define pack_long_be pack_integer_elements(pack_long_element_be)\n\n\/\/ Pack UTF-8 elements\n#define pack_utf8_element(v) pack::utf8_encode(state, str, v)\n#define pack_utf8 pack_elements(Integer, pack::to_int, pack_utf8_element)\n\n\/\/ Pack BER-compressed integers\n#define pack_ber_element(v) pack::ber_encode(state, str, v)\n#define pack_ber pack_elements(Integer, pack::to_int, pack_ber_element)\n\n\/\/ Wraps the logic for iterating over a number of elements,\n\/\/ coercing them to the correct class and formatting them\n\/\/ for the output string.\n#define pack_elements(T, coerce, format) \\\n for(; index < stop; index++) { \\\n Object* item = self->get(state, index); \\\n T* value = try_as(item); \\\n if(!value) { \\\n item = coerce(state, item); \\\n if(!item) return 0; \\\n value = as(item); \\\n } \\\n format(value); \\\n }\n\n\/\/ Macros that depend on endianness\n#ifdef RBX_LITTLE_ENDIAN\n\n# define pack_double_element_le(v) (pack::double_element(str, (v)->val))\n# define pack_double_element_be(v) (pack::swap_double(str, (v)->val))\n# define pack_double pack_double_le\n\n# define pack_float_element_le(v) (pack::float_element(str, (v)->val))\n# define pack_float_element_be(v) (pack::swap_float(str, (v)->val))\n# define pack_float pack_float_le\n\n# define pack_short_element_le(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short_element_be(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short pack_short_le\n\n# define pack_int_element_le(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int_element_be(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int pack_int_le\n\n# define pack_long_element_le(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long_element_be(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long pack_long_le\n\n#else \/\/ Big endian\n\n# define pack_double_element_le(v) (pack::swap_double(str, (v)->val))\n# define pack_double_element_be(v) (pack::double_element(str, (v)->val))\n# define pack_double pack_double_be\n\n# define pack_float_element_le(v) (pack::swap_float(str, (v)->val))\n# define pack_float_element_be(v) (pack::float_element(str, (v)->val))\n# define pack_float pack_float_be\n\n# define pack_short_element_le(v) (pack::short_element(str, \\\n pack::swap_2bytes(pack::check_long(state, v))))\n# define pack_short_element_be(v) (pack::short_element(str, pack::check_long(state, v)))\n# define pack_short pack_short_be\n\n# define pack_int_element_le(v) (pack::int_element(str, \\\n pack::swap_4bytes(pack::check_long(state, v))))\n# define pack_int_element_be(v) (pack::int_element(str, pack::check_long(state, v)))\n# define pack_int pack_int_be\n\n# define pack_long_element_le(v) (pack::long_element(str, \\\n pack::swap_8bytes(pack::check_long_long(state, v))))\n# define pack_long_element_be(v) (pack::long_element(str, pack::check_long_long(state, v)))\n# define pack_long pack_long_be\n\n#endif\n\n\n String* Array::pack(STATE, String* directives) {\n \/\/ Ragel-specific variables\n const char* p;\n const char* pe;\n ByteArray* d = pack::prepare_directives(state, directives, &p, &pe);\n const char *eof = pe;\n int cs;\n\n \/\/ pack-specific variables\n Array* self = this;\n OnStack<2> sv(state, self, d);\n\n native_int array_size = self->size();\n native_int index = 0;\n native_int count UNUSED = 0;\n native_int count_flag = -1;\n native_int stop = 0;\n bool rest UNUSED = false;\n bool tainted UNUSED = false;\n bool untrusted UNUSED = false;\n bool ascii_encoding = false;\n bool utf8_encoding = false;\n bool string_encoding = false;\n\n String* string_value = 0;\n std::string str(\"\");\n\n \/\/ Use information we have to reduce repeated allocation.\n str.reserve(array_size * 4);\n\n if(directives->byte_size() == 0) ascii_encoding = true;\n if(CBOOL(directives->tainted_p(state))) tainted = true;\n if(CBOOL(directives->untrusted_p(state))) untrusted = true;\n%%{\n\n machine pack;\n\n include \"pack.rl\";\n\n}%%\n\n if(en_main) {\n \/\/ do nothing\n }\n\n return force_as(Primitives::failure());\n }\n}\n","returncode":0,"stderr":"","license":"mit","lang":"Ragel in Ruby Host"} {"commit":"ee4ccdf6d046f8b826cf3bad70b2f6311dd23ab2","subject":"warnings","message":"warnings\n","repos":"markwharton\/wikiparser,markwharton\/wikiparser","old_file":"wiki2html.rl","new_file":"wiki2html.rl","new_contents":"\/*\n\nC wiki parser library and sample application.\n\nCopyright (c) 2010, Mark Wharton\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n#include \n#include \n#include \n\n#define MAX_HEADINGS WIKI_PARSER_TOKEN_TYPE_HEADING6 - WIKI_PARSER_TOKEN_TYPE_HEADING0\n\ntypedef struct Wiki2HTMLUserDataStruct {\n\tint headings[MAX_HEADINGS];\n\tbool indexed;\n\tint lastIndex;\n\tchar* outlink;\n\tint rowCount;\n} Wiki2HTMLUserData, *Wiki2HTMLUserDataPtr;\n\n#define userDataHeadings (((Wiki2HTMLUserDataPtr)userData)->headings)\n#define userDataIndexed (((Wiki2HTMLUserDataPtr)userData)->indexed)\n#define userDataLastIndex (((Wiki2HTMLUserDataPtr)userData)->lastIndex)\n#define userDataOutlink (((Wiki2HTMLUserDataPtr)userData)->outlink)\n#define userDataRowCount (((Wiki2HTMLUserDataPtr)userData)->rowCount)\n\nbool echoHeadingID(void *userData, WikiParserBuffer *text)\n{\n\tbool error = false;\n\tchar *id = createWikiParserString(text->data, text->size);\n\tif (id) {\n\t\tint i = 0;\n\t\tchar *p = id;\n\t\tfor (; i < text->size; i++) {\n\t\t\tchar c = text->data[i];\n\t\t\tif (isalnum(c)) *p++ = tolower(c);\n\t\t\telse if (p > id && *(p - 1) != '-') *p++ = '-';\n\t\t}\n\t\t*p = '\\0';\n\t\terror = fprintf(stdout, \"%s\", id) <= 0;\n\t\twikiParserStringFree(id);\n\t\tid = NULL;\n\t}\n\telse error = true; \/\/ out of memory\n\treturn !error;\n}\n\nbool echoHeadingIndex(void *userData, int index)\n{\n\tbool error = false;\n\tint i = 1; \/* skip title *\/\n\tfor (; i < index && !error; i++) {\n\t\terror = fprintf(stdout, \"%d.\", userDataHeadings[i]) <= 0;\n\t}\n\tfor (; i < MAX_HEADINGS; i++) {\n\t\tuserDataHeadings[i] = 0;\n\t}\n\treturn !error;\n}\n\n%%{\n\tmachine EscapeTextWriter;\n\twrite data;\n}%%\n\n#pragma unused (EscapeTextWriter_en_main,EscapeTextWriter_error)\n\nbool escapeTextWriter(void *userData, WikiParserBuffer *text)\n{\n\tassert(text);\n\tbool error = false;\n\tconst char *p = text->data;\n\tconst char *pe = text->data + text->size;\n\tconst char *eof = pe;\n\tint act;\n\tint cs;\n\tconst char *ts;\n\tconst char *te;\n\n\t%%{\n\t\tmain := |*\n\t\t\t'&' { if ((error = fprintf(stdout, \"&\" ) <= 0)) fbreak; };\n\t\t\t'<' { if ((error = fprintf(stdout, \"<\" ) <= 0)) fbreak; };\n\t\t\t'>' { if ((error = fprintf(stdout, \">\" ) <= 0)) fbreak; };\n\t\t\t'\"' { if ((error = fprintf(stdout, \""\") <= 0)) fbreak; };\n\t\t\t[^&<>\"\"]+ { if ((error = fwrite(ts, te - ts, 1, stdout) <= 0)) fbreak; };\n\t\t*|;\n\n\t\t# Initialize and execute.\n\t\twrite init;\n\t\twrite exec;\n\t}%%\n\n\tif (!error) error = cs < EscapeTextWriter_first_final;\n\treturn !error;\n}\n\nbool wikiReader(void *userData, WikiParserBuffer *buffer, size_t *size) {\n\t*size = fread((char *)buffer->data, 1, buffer->size, stdin);\n\treturn ferror(stdin) == 0;\n}\n\nbool wikiTitleWriter(void *userData, WikiParserToken *token)\n{\n\tassert(token);\n\tbool error = false;\n\tswitch (token->type) {\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING1:\n\t\t{\n\t\t\tint index = token->type - WIKI_PARSER_TOKEN_TYPE_HEADING0;\n\t\t\tint i = index - 1;\n\t\t\tif (userDataHeadings[i] == 0) {\n\t\t\t\tif (!error) error = !escapeTextWriter(userData, token->text);\n\t\t\t\tuserDataHeadings[i] = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn !error;\n}\n\nbool wikiTOCWriter(void *userData, WikiParserToken *token)\n{\n\tassert(token);\n\tbool error = false;\n\tswitch (token->type) {\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING0: \/* Not used directly; for calculations. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING1: \/* title *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING2: \/* 1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING3: \/* 1.1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING4: \/* 1.1.1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING5: \/* 1.1.1.1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING6: \/* 1.1.1.1.1. *\/\n\t\t{\n\t\t\tint index = token->type - WIKI_PARSER_TOKEN_TYPE_HEADING0;\n\t\t\tint i = index - 1;\n\t\t\tuserDataHeadings[i]++;\n\t\t\tif (i) {\n\t\t\t\ti = index - userDataLastIndex;\n\t\t\t\tif (i < 0) {\n\t\t\t\t\ti = -i;\n\t\t\t\t\twhile (i-- && !error) error = fprintf(stdout, \"<\/ol>\") <= 0;\n\t\t\t\t}\n\t\t\t\telse if (i > 0) while (i-- && !error) error = fprintf(stdout, \"

    \") <= 0;\n\t\t\t\tif (!error) error = fprintf(stdout, \"
  1. \") <= 0;\n\t\t\t\tif (userDataIndexed) {\n\t\t\t\t\tif (!error) error = !echoHeadingIndex(userData, index);\n\t\t\t\t\tif (!error) error = fprintf(stdout, \" \") <= 0;\n\t\t\t\t}\n\t\t\t\tif (!error) error = !escapeTextWriter(userData, token->text);\n\t\t\t\tif (!error) error = fprintf(stdout, \"<\/a><\/li>\") <= 0;\n\t\t\t}\n\t\t\tuserDataLastIndex = index;\n\t\t\tbreak;\n\t\t}\n\t\tcase WIKI_PARSER_TOKEN_TYPE_NONE:\n\t\t{\n\t\t\tint index = 1, i;\n\t\t\ti = index - userDataLastIndex;\n\t\t\tif (i < 0) {\n\t\t\t\ti = -i;\n\t\t\t\twhile (i-- && !error) error = fprintf(stdout, \"<\/ol>\") <= 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn !error;\n}\n\nbool wikiWriter(void *userData, WikiParserToken *token)\n{\n\tassert(token);\n\tbool error = false;\n\tswitch (token->type) {\n\t\tcase WIKI_PARSER_TOKEN_TYPE_BOLD:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/strong>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_CODE:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/code>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_DEFINITIONDESC:\n\t\t\terror = fprintf(stdout, token->state ? \"
    \" : \"<\/dd>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_DEFINITIONLIST:\n\t\t\terror = fprintf(stdout, token->state ? \"
    \" : \"<\/dl>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_DEFINITIONTERM:\n\t\t\terror = fprintf(stdout, token->state ? \"
    \" : \"<\/dt>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING0: \/* Not used directly; for calculations. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING1: \/* title *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING2: \/* 1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING3: \/* 1.1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING4: \/* 1.1.1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING5: \/* 1.1.1.1. *\/\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HEADING6: \/* 1.1.1.1.1. *\/\n\t\t{\n\t\t\tint index = token->type - WIKI_PARSER_TOKEN_TYPE_HEADING0;\n\t\t\tint i = index - 1;\n\t\t\tuserDataHeadings[i]++;\n\t\t\tif (!error) error = fprintf(stdout, \"\") <= 0;\n\t\t\tif (!error) error = fprintf(stdout, \"text);\n\t\t\tif (!error) error = fprintf(stdout, \"\\\" \/>\") <= 0;\n\t\t\tif (userDataIndexed) {\n\t\t\t\tif (!error) error = !echoHeadingIndex(userData, index);\n\t\t\t\tif (!error) error = fprintf(stdout, \" \") <= 0;\n\t\t\t}\n\t\t\tif (!error) error = !escapeTextWriter(userData, token->text);\n\t\t\tif (!error) error = fprintf(stdout, \"<\/h%d>\", index) <= 0;\n\t\t\tbreak;\n\t\t}\n\t\tcase WIKI_PARSER_TOKEN_TYPE_HORIZONTALRULE:\n\t\t\terror = fprintf(stdout, \"
    \") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_IMAGE:\n\t\t\tif (!error) error = fprintf(stdout, \"source);\n\t\t\tif (token->text) {\n\t\t\t\tif (!error) error = fprintf(stdout, \"\\\" alt=\\\"\") <= 0;\n\t\t\t\tif (!error) error = !escapeTextWriter(userData, token->text);\n\t\t\t}\n\t\t\tif (!error) error = fprintf(stdout, \"\\\" \/>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_ITALIC:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/em>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_KEYBOARD:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/kbd>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_LINEBREAK:\n\t\t\terror = fprintf(stdout, \"
    \") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_LINK:\n\t\t\tif (!error) error = fprintf(stdout, \"
    target);\n\t\t\tif (token->target->size == 1 && *token->target->data == '#') { \/* Page reference text. *\/\n\t\t\t\tif (!error) error = !echoHeadingID(userData, token->text ? token->text : token->target);\n\t\t\t}\n\t\t\tif (!error) error = fprintf(stdout, \"\\\">\") <= 0;\n\t\t\tif (token->source) {\n\t\t\t\t\/\/ image inside links hack\n\t\t\t\tif (!error) error = fprintf(stdout, \"source);\n\t\t\t\tif (!error) error = fprintf(stdout, \"\\\" \/>\") <= 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (!error) error = !escapeTextWriter(userData, token->text ? token->text : token->target);\n\t\t\t}\n\t\t\tif (userDataOutlink && *userDataOutlink && (strncmp(token->target->data, \"http\", 4) == 0 || strncmp(token->target->data, \".\/\", 2) == 0)) { \/* HTML markup for outlink. *\/\n\t\t\t\tif (!error) error = fprintf(stdout, \"%s\", userDataOutlink) <= 0;\n\t\t\t}\n\t\t\tif (!error) error = fprintf(stdout, \"<\/a>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_LISTITEM:\n\t\t\terror = fprintf(stdout, token->state ? \"
  2. \" : \"<\/li>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_ORDEREDLIST:\n\t\t\terror = fprintf(stdout, token->state ? \"
      \" : \"<\/ol>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_PARAGRAPH:\n\t\t\terror = fprintf(stdout, token->state ? \"

      \" : \"<\/p>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_PREFORMATTED:\n\t\t\tif (!error) error = fprintf(stdout, \"

      \") <= 0;\n\t\t\tif (!error) error = !escapeTextWriter(userData, token->text);\n\t\t\tif (!error) error = fprintf(stdout, \"<\/pre>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_SAMPLECODE:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/samp>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_SUBSCRIPT:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/sub>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_SUPERSCRIPT:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/sup>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLE:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/table>\") <= 0;\n\t\t\tuserDataRowCount = 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLEDATA:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"\" : \"<\/tr>\") <= 0;\n\t\t\tif (token->state) userDataRowCount += 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TEXT:\n\t\t\terror = !escapeTextWriter(userData, token->text);\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_UNDERLINE:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/span>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_UNORDEREDLIST:\n\t\t\terror = fprintf(stdout, token->state ? \"
      \" : \"<\/td>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLEHEADER:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/th>\") <= 0;\n\t\t\tuserDataRowCount = 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLEROW:\n\t\t{\n\t\t\tbool alt = userDataRowCount % 2; \/* User data is used to keep track of the row state. *\/\n\t\t\terror = fprintf(stdout, token->state ? alt ? \"
      \" : \"<\/table>\") <= 0;\n\t\t\tuserDataRowCount = 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLEDATA:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"\" : \"<\/tr>\") <= 0;\n\t\t\tif (token->state) userDataRowCount += 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TEXT:\n\t\t\terror = !escapeTextWriter(userData, token->text);\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_UNDERLINE:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/span>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_UNORDEREDLIST:\n\t\t\terror = fprintf(stdout, token->state ? \"
      \" : \"<\/td>\") <= 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLEHEADER:\n\t\t\terror = fprintf(stdout, token->state ? \"\" : \"<\/th>\") <= 0;\n\t\t\tuserDataRowCount = 0;\n\t\t\tbreak;\n\t\tcase WIKI_PARSER_TOKEN_TYPE_TABLEROW:\n\t\t{\n\t\t\tbool alt = userDataRowCount % 2; \/* User data is used to keep track of the row state. *\/\n\t\t\terror = fprintf(stdout, token->state ? alt ? \"