nom_operator/operator.rs
1// Copyright 2017 The nom-operator project developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! An Operator wrapper with extra info for parsing
10
11use std::fmt;
12use IResult;
13use Parser;
14
15/// An Operator wrapper with extra info for parsing
16pub struct Operator<O> {
17 /// The underlying operator enum
18 pub op: O,
19
20 /// The associativity of the operator
21 pub associativity: Associativity,
22
23 /// Size of the operator, Unary, Binary, etc...
24 pub size: OperatorSize,
25
26 /// The precedence of the operator
27 /// If * has precedence 10 and - has precedence 9
28 /// the following expression 1 * 2 - 3
29 /// would parse as (1 * 2) - 3
30 pub precedence: usize,
31
32 /// The nom parser function
33 pub parser: Parser,
34}
35
36
37impl<O> Operator<O> {
38 /// Creates a new operator
39 pub fn new(op: O,
40 assoc: Associativity,
41 size: OperatorSize,
42 prec: usize,
43 parser: Parser) -> Self {
44 Operator {
45 op: op,
46 associativity: assoc,
47 size: size,
48 precedence: prec,
49 parser: parser,
50 }
51 }
52}
53
54impl<O: fmt::Debug> fmt::Debug for Operator<O> {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 write!(f,
57 "Operator<{:?}>: \n\tAssociativity: {:?}\n\tPrecedence: {}",
58 self.op,
59 self.associativity,
60 self.precedence)
61 }
62}
63
64impl<O: PartialEq> PartialEq for Operator<O> {
65 // TODO: Should we compare the parser?
66 fn eq(&self, other: &Operator<O>) -> bool {
67 self.op == other.op &&
68 self.associativity == other.associativity &&
69 self.precedence == other.precedence
70 }
71}
72
73/// Size of the operator
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub enum OperatorSize {
76 /// Unary operator
77 ///
78 /// ++x
79 Unary,
80
81 /// Binary operator
82 ///
83 /// 5 ^ 5
84 Binary,
85}
86
87
88/// Associativity of the operator
89#[derive(Debug, Clone, Copy, PartialEq)]
90pub enum Associativity {
91 /// Left associative operator
92 ///
93 /// 5 * 5 * 7 = (5 * 5) * 7
94 Left,
95
96 /// Right associative operator
97 ///
98 /// 5 ^ 5 ^ 9 = 5 ^ (5 ^ 9)
99 Right,
100}
101