markdown.py 7.7 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
import sys

from parsec import one, eof
from parsec.combinator import *
from parsec.text import *
from .market_math import processor

"""
使用 markdown 编写的问题应该总是一个固定格式,即

# 问题标题

问题描述

## 模板

```java
package app;
public class App {
    public static void main(String[] args){
        $code
    }
}
```

如果第一个二级标题为 template,则生成一个可选的 template 字段,template 章节中的代码段会作为代码模板,用于被生成的 notebook 

## aop

AOP(面向切面)章节定义 notebook 生成时插入的 cell ,如果定义了这个二级标题,其下复合定义的章节会插在必要的位置。

### before

这里的章节会写入到答案代码之前。

### after

这里的章节会写入到答案代码之后

## 答案

这里写正确答案。此处的代码会写入到 notebook 中,如过定义了模板章节,会将其合并后生成 notebook。

```java
```

## 选项

### A 选项标题会被忽略

可选的描述

```
//  代码
```

### B

可选的描述

```
//  代码
```

### C

可选的描述

```
//  代码
```

### D

可选的描述

```
//  代码
```

需要注意的是,选项的标题并不会出现在最终的题目中,仅作为编辑过程中的标注。而第一个选项就是答案。其顺序在最终展现时由服务代码进行混淆。

"""


class Paragraph:
    def __init__(self, source="", language=""):
        self.source = source
        self.language = language

    def isEmpty(self):
        return self.source == "" and self.language == ""

    def to_map(self):
        return {"content": self.source, "language": self.language}


class Option:
    def __init__(self, paras=None):
        self.paras = paras if paras else []

    def to_map(self):
        return [p.to_map() for p in self.paras]


class Exercise:
    def __init__(self, title, answer, description, options):
        self.title = title
        self.answer = answer
        self.description = description
        self.options = options


@Parsec
def spaces(state):
    return skip1(space)(state)


def maybe_spaces(state):
    return skip(space)(state)


def inline(state):
    char = one(state)
    if char == '\n':
        raise ParsecError(state, "unexpected newline")
    else:
        return char


@Parsec
def title(state):
    """
    解析问题标题
    """
    parser = string("#").then(spaces).then(many1(inline)).over(string('\n'))
    data = parser(state)
    return "".join(data)


@Parsec
def chapter_title(state):
    """
    解析章标题
    @param state:
    @return:
    """
    parser = string("##").then(spaces).then(many1(inline)).over(string('\n'))
    data = parser(state)
    return "".join(data)


@Parsec
def section_title(state):
    """
    解析节标题
    @param state:
    @return:
    """
    parser = string("###").then(spaces).then(many1(inline)).over(string('\n'))
    data = parser(state)
    return "".join(data)


@Parsec
def paragraph(state):
    """
    解析文字段落
    """
    buffer = ""
    line = many(inline).over(choice(attempt(string("\n")), eof))
    stop = choices(attempt(string("\n")), attempt(string("### ")), string("## "))
    while True:
        maybe_spaces(state)
        result = "".join(line(state))
        data = result
        if data:
            buffer += '\n' + result
        else:
            break
        tran = state.begin()
        try:
            stop(state)
        except ParsecError:
            continue
        finally:
            state.rollback(tran)
        return Paragraph(processor(buffer), "markdown")

    return Paragraph(processor(buffer), "markdown")


@Parsec
def code(state):
M
Mars Liu 已提交
195 196 197 198
    side = choice(attempt(string("````")), string("```"))
    left = many(attempt(inline)).over(string("\n"))

    side_token = side(state)
M
Mars Liu 已提交
199
    language = ''.join(left(state))
M
Mars Liu 已提交
200 201

    right = attempt(string("\n"+side_token).over(choice(attempt(string("\n")), eof)))
M
Mars Liu 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    buffer = ""
    while True:
        try:
            right(state)
            return Paragraph(buffer, language)
        except ParsecError:
            buffer += one(state)


@Parsec
def desc(state):
    """解析问题或选项描述
    问题描述由若干段落或代码组成,内部结构遵循 markdown 语法
    """
    buffer = []
    parser = choice(attempt(code), paragraph)
    stop = choices(attempt(string("## ")), attempt(string("### ")), eof)
    while True:
        tran = state.begin()
        try:
            stop(state)
            return buffer
        except ParsecError:
            pass
        finally:
            state.rollback(tran)

        buffer.append(parser(state))
        maybe_spaces(state)


def option(state):
    "解析选项"
    parser = attempt(string("###").then(spaces).then(many1(attempt(inline))).over(string('\n')))
    parser(state)
    maybe_spaces(state)
    return Option(desc(state))


def template(state):
    "解析模板,返回对应的模板代码对象,如果解析失败,返回 None 并恢复 state"
    tran = state.begin()
    try:
        title = chapter_title(state)
        if title == "template":
            state.commit(tran)
            maybe_spaces(state)
            return code(state)
        else:
            raise ParsecError(state, "template not found")
    except ParsecError:
        state.rollback(tran)
        return None


@Parsec
def aop_parser(state):
    """
    解析AOP,返回对应的AOP字典,如果解析失败,返回 None 并恢复 state
    @param state:
    @return:
    """
    result = {}
    stop = attempt(chapter_title)
    tt = state.begin()
    try:
        title = chapter_title(state)
        if title == "aop":
            state.commit(tt)
            maybe_spaces(state)
            while True:
                tran = state.begin()
                try:
                    stop(state)
                    state.rollback(tran)
                    if len(result) == 0:
                        return None
                    else:
                        return result
                except ParsecError:
                    state.rollback(tran)
                    maybe_spaces(state)
                    st = section_title(state)
                    maybe_spaces(state)
                    if st == "before":
                        result["before"] = desc(state)
                    elif st == "after":
                        result["after"] = desc(state)
                    else:
                        raise ParsecError(state, f"invalid section {st} in aop chapter")

        else:
            raise ParsecError(state, "aop not found")
    except ParsecError as err:
        state.rollback(tt)
        return None


@Parsec
def parse(state):
    t = title(state)
    maybe_spaces(state)
    try:
        description = desc(state)
    except ParsecError as err:
        raise err
    tmpl = template(state)
    maybe_spaces(state)
    aop = aop_parser(state)
    ct = chapter_title(state)
    if ct == "答案":
        maybe_spaces(state)
        answer = desc(state)
    else:
        raise ParsecError(state, "chapter [答案] is required")
    ct = chapter_title(state)
    if ct == "选项":
        maybe_spaces(state)
        options = []
        while True:
            try:
                opt = option(state)
                options.append(opt)
                maybe_spaces(state)
            except ParsecError as err:
                result = Exercise(t, answer, description, options)
M
Mars Liu 已提交
328 329 330 331
                if tmpl is None:
                    tmpl = template(state)
                if aop is None:
                    aop = aop_parser(state)
M
Mars Liu 已提交
332 333 334 335 336 337 338
                if tmpl is not None:
                    result.template = tmpl
                if aop is not None:
                    result.aop = aop
                return result
    else:
        raise ParsecError(state, "chapter [选项] not found")