/usr/lib/python2.7/dist-packages/nwdiag/parser.py is in python-nwdiag 1.0.3-4.1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 195 196 197 198 199 200 201 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 | # -*- coding: utf-8 -*-
# Copyright (c) 2008/2009 Andrey Vlasovskikh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
r'''A DOT language parser using funcparserlib.
The parser is based on [the DOT grammar][1]. It is pretty complete with a few
not supported things:
* Ports and compass points
* XML identifiers
At the moment, the parser builds only a parse tree, not an abstract syntax tree
(AST) or an API for dealing with DOT.
[1]: http://www.graphviz.org/doc/info/lang.html
'''
import io
from re import MULTILINE, DOTALL
from collections import namedtuple
from funcparserlib.lexer import make_tokenizer, Token, LexerError
from funcparserlib.parser import (some, a, maybe, many, finished, skip)
from blockdiag.parser import create_mapper, oneplus_to_list
from blockdiag.utils.compat import u
Diagram = namedtuple('Diagram', 'id stmts')
Network = namedtuple('Network', 'id stmts')
Group = namedtuple('Group', 'id stmts')
Node = namedtuple('Node', 'id attrs')
Attr = namedtuple('Attr', 'name value')
Edge = namedtuple('Edge', 'from_node edge_type to_node attrs')
Peer = namedtuple('Peer', 'edges')
Route = namedtuple('Route', 'edges')
Extension = namedtuple('Extension', 'type name attrs')
Statements = namedtuple('Statements', 'stmts')
class ParseException(Exception):
pass
def tokenize(string):
"""str -> Sequence(Token)"""
# flake8: NOQA
specs = [ # NOQA
('Comment', (r'/\*(.|[\r\n])*?\*/', MULTILINE)), # NOQA
('Comment', (r'(//|#).*',)), # NOQA
('NL', (r'[\r\n]+',)), # NOQA
('Space', (r'[ \t\r\n]+',)), # NOQA
('Name', (u('[A-Za-z_\u0080-\uffff]') + # NOQA
u('[A-Za-z_\\-.0-9\u0080-\uffff]*'),)), # NOQA
('Op', (r'([{};,=\[\]]|--|->)',)), # NOQA
('IPAddr', (r'([0-9]+(\.[0-9]+){3}|[:0-9a-fA-F]+)',)), # NOQA
('Number', (r'-?(\.[0-9]+)|([0-9]+(\.[0-9]*)?)',)), # NOQA
('String', (r'(?P<quote>"|\').*?(?<!\\)(?P=quote)', DOTALL)), # NOQA
]
useless = ['Comment', 'NL', 'Space']
t = make_tokenizer(specs)
return [x for x in t(string) if x.type not in useless]
def parse(seq):
"""Sequence(Token) -> object"""
id_tokens = ['Name', 'IPAddr', 'Number', 'String']
tokval = lambda x: x.value
op = lambda s: a(Token('Op', s)) >> tokval
op_ = lambda s: skip(op(s))
_id = some(lambda t: t.type in id_tokens) >> tokval
keyword = lambda s: a(Token('Name', s)) >> tokval
def make_peer(first, edge_type, second, followers, attrs):
edges = [Edge(first, edge_type, second, attrs)]
from_node = second
for edge_type, to_node in followers:
edges.append(Edge(from_node, edge_type, to_node, attrs))
from_node = to_node
return Peer(edges)
def make_route(first, edge_type, second, followers, attrs):
edges = [Edge(first, edge_type, second, attrs)]
from_node = second
for edge_type, to_node in followers:
edges.append(Edge(from_node, edge_type, to_node, attrs))
from_node = to_node
return Route(edges)
#
# parts of syntax
#
node_list = (
_id +
many(op_(',') + _id)
>> create_mapper(oneplus_to_list)
)
option_stmt = (
_id +
maybe(op_('=') + _id)
>> create_mapper(Attr)
)
option_list = (
maybe(op_('[') + option_stmt + many(op_(',') + option_stmt) + op_(']'))
>> create_mapper(oneplus_to_list, default_value=[])
)
# node statement::
# A;
# B [attr = value, attr = value];
#
node_stmt = (
_id + option_list
>> create_mapper(Node)
)
# peer network statement::
# A -- B;
#
edge_stmt = (
_id +
op('--') +
_id +
many(op('--') + _id) +
option_list
>> create_mapper(make_peer)
)
# attributes statement::
# default_shape = box;
# default_fontsize = 16;
#
attribute_stmt = (
_id + op_('=') + _id
>> create_mapper(Attr)
)
# extension statement (class, plugin)::
# class red [color = red];
# plugin attributes [name = Name];
#
extension_stmt = (
(keyword('class') | keyword('plugin')) +
_id +
option_list
>> create_mapper(Extension)
)
# group statement::
# group {
# A;
# }
#
group_inline_stmt = (
attribute_stmt |
node_stmt
)
group_inline_stmt_list = (
many(group_inline_stmt + skip(maybe(op(';'))))
)
group_stmt = (
skip(keyword('group')) +
maybe(_id) +
op_('{') +
group_inline_stmt_list +
op_('}')
>> create_mapper(Group)
)
# network statement::
# network {
# A;
# }
#
network_inline_stmt = (
attribute_stmt |
group_stmt |
node_stmt
)
network_inline_stmt_list = (
many(network_inline_stmt + skip(maybe(op(';'))))
)
network_stmt = (
skip(keyword('network')) +
maybe(_id) +
op_('{') +
network_inline_stmt_list +
op_('}')
>> create_mapper(Network)
)
# route statement::
# route {
# A -> B -> C;
# }
#
route_inline_stmt = (
_id +
op_('->') +
_id +
many(op_('->') + _id) +
option_list
>> create_mapper(make_route)
)
route_stmt = (
skip(keyword('route')) +
maybe(_id) +
op_('{') +
network_inline_stmt_list +
op_('}')
>> create_mapper(Network)
)
#
# diagram statement::
# nwdiag {
# A;
# }
#
diagram_id = (
(keyword('diagram') | keyword('nwdiag')) +
maybe(_id)
>> list
)
diagram_inline_stmt = (
extension_stmt |
network_stmt |
group_stmt |
attribute_stmt |
route_stmt |
edge_stmt |
node_stmt
)
diagram_inline_stmt_list = (
many(diagram_inline_stmt + skip(maybe(op(';'))))
)
diagram = (
maybe(diagram_id) +
op_('{') +
diagram_inline_stmt_list +
op_('}')
>> create_mapper(Diagram)
)
dotfile = diagram + skip(finished)
return dotfile.parse(seq)
def sort_tree(tree):
def weight(node):
if isinstance(node, (Attr, Extension)):
return 1
else:
return 2
if hasattr(tree, 'stmts'):
tree.stmts.sort(key=lambda x: weight(x))
for stmt in tree.stmts:
sort_tree(stmt)
return tree
def parse_string(string):
try:
tree = parse(tokenize(string))
return sort_tree(tree)
except LexerError as e:
message = "Got unexpected token at line %d column %d" % e.place
raise ParseException(message)
except Exception as e:
raise ParseException(str(e))
def parse_file(path):
code = io.open(path, 'r', encoding='utf-8-sig').read()
return parse_string(code)
|